aboutsummaryrefslogtreecommitdiff
path: root/main.c
blob: bf56603c7138c1c2db956a19d0193ca4a81dec86 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#include "facedet.h"
#include "image.h"
#include "overlay.h"

#include <ctype.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

static int token(FILE *f, char *out, size_t cap) {
    if (feof(f) || ferror(f))
        return -1;
    int c;
    for (;;) {
        c = fgetc(f);
        if (c == EOF)
            return -1;
        if (c == '#') {
            do {
                c = fgetc(f);
                if (c == EOF)
                    return -1;
            } while (c != '\n');
            continue;
        }
        if (!isspace((unsigned char)c))
            break;
    }
    size_t n = 0;
    do {
        if (n + 1 >= cap)
            return -1;
        out[n++] = (char)c;
        c = fgetc(f);
        if (c == EOF)
            return -1;
    } while (!isspace((unsigned char)c));
    /* CRLF is one header separator; raster bytes are never skipped. */
    if (c == '\r') {
        c = fgetc(f);
        if (c == EOF || (c != '\n' && ungetc(c, f) == EOF))
            return -1;
    }
    out[n] = '\0';
    return 0;
}

static int dimension(const char *s) {
    char *end;
    errno = 0;
    long v = strtol(s, &end, 10);
    return errno || !*s || *end || v < 1 || v > 4096 ? -1 : (int)v;
}

static unsigned char *read_ppm(const char *path, int *width, int *height) {
    FILE *f = fopen(path, "rb");
    if (!f)
        return NULL;
    unsigned char *rgb = NULL;
    char word[32];
    if (token(f, word, sizeof word) || strcmp(word, "P6"))
        goto end;
    if (token(f, word, sizeof word) || (*width = dimension(word)) < 0)
        goto end;
    if (token(f, word, sizeof word) || (*height = dimension(word)) < 0)
        goto end;
    if (token(f, word, sizeof word) || strcmp(word, "255"))
        goto end;
    size_t size = (size_t)*width * *height * 3;
    rgb = malloc(size);
    if (rgb && fread(rgb, 1, size, f) != size) {
        free(rgb);
        rgb = NULL;
    }
end:
    fclose(f);
    return rgb;
}

static int threshold(const char *s, float *out) {
    char *end;
    errno = 0;
    float v = strtof(s, &end);
    if (errno || !*s || *end || !isfinite(v) || v < 0.0f || v > 1.0f)
        return -1;
    *out = v;
    return 0;
}

static void usage(FILE *file, const char *program) {
    fprintf(file, "Usage: %s [-o output.ppm] image [score_threshold [nms_iou]]\n"
                  "Input: JPEG, PNG, or binary P6 PPM (maxval 255), up to 4096x4096.\n"
                  "Output: JSON on stdout. Thresholds must be finite numbers in [0, 1].\n"
                  "  -o, --out FILE  Save face boxes, scores, and landmarks as P6 PPM.\n"
                  "  --refine        Refine landmarks with optional embedded crop weights.\n"
                  "  -h, --help      Show help.\n"
                  "  --              End options, for filenames starting with '-'.\n", program);
}

int main(int argc, char **argv) {
    const char *out_path = NULL, *args[3];
    int nargs = 0, options = 1, refine = 0;
    for (int i = 1; i < argc; i++) {
        const char *arg = argv[i];
        if (options && !strcmp(arg, "--")) {
            options = 0;
            continue;
        }
        if (options && (!strcmp(arg, "-h") || !strcmp(arg, "--help"))) {
            usage(stdout, argv[0]);
            return 0;
        }
        if (options && !strcmp(arg, "--refine")) {
            if (refine) {
                fputs("Specify --refine only once.\n", stderr);
                return 1;
            }
            refine = 1;
            continue;
        }
        if (options && (!strcmp(arg, "-o") || !strcmp(arg, "--out") ||
                        !strncmp(arg, "--out=", 6))) {
            if (out_path) {
                fputs("Specify only one output file.\n", stderr);
                return 1;
            }
            if (!strncmp(arg, "--out=", 6))
                out_path = arg + 6;
            else if (i + 1 < argc)
                out_path = argv[++i];
            if (!out_path || !*out_path || !strcmp(out_path, "-")) {
                fputs("--out requires a filename; stdout is reserved for JSON.\n", stderr);
                return 1;
            }
            continue;
        }
        if ((options && arg[0] == '-') || nargs == 3) {
            usage(stderr, argv[0]);
            return 1;
        }
        args[nargs++] = arg;
    }
    float score = 0.6f, nms = 0.3f;
    if (!nargs || (nargs > 1 && threshold(args[1], &score)) ||
        (nargs > 2 && threshold(args[2], &nms))) {
        usage(stderr, argv[0]);
        return 1;
    }
    const char *input_path = args[0];
    if (out_path) {
        struct stat input_info, output_info;
        if (!strcmp(input_path, out_path) ||
            (stat(input_path, &input_info) == 0 && stat(out_path, &output_info) == 0 &&
             input_info.st_dev == output_info.st_dev && input_info.st_ino == output_info.st_ino)) {
            fputs("The output file must not be the input image.\n", stderr);
            return 1;
        }
    }
    int width = 0, height = 0;
    unsigned char *rgb = image_read_rgb(input_path, &width, &height);
    if (!rgb)
        rgb = read_ppm(input_path, &width, &height);
    if (!rgb) {
        fprintf(stderr, "Cannot read %s as JPEG, PNG, or P6 PPM (maxval 255) with dimensions 1..4096.\n", input_path);
        return 1;
    }
    int iw = (width + 31) & ~31, ih = (height + 31) & ~31;
    facedet *m = facedet_create(iw, ih);
    int rc = m ? facedet_set_rgb(m, rgb, width, height, (size_t)width * 3) : -1;
    if (rc == 0)
        rc = facedet_run(m);
    int cap = 21 * (iw / 32) * (ih / 32);
    facedet_detection *faces = rc == 0 ? malloc((size_t)cap * sizeof(*faces)) : NULL;
    int n = faces ? facedet_decode(m, score, nms, faces, cap) : -1;
    facedet_free(m);
    if (n < 0) {
        fprintf(stderr, "Inference failed; memory allocation or input validation failed.\n");
        free(faces);
        free(rgb);
        return 1;
    }
    if (refine) {
        facedet *refiner = facedet_create_refiner();
        rc = refiner ? facedet_refine(refiner, rgb, width, height, (size_t)width * 3, faces, n) : -1;
        facedet_free(refiner);
        if (rc) {
            fputs("Landmark refinement failed; check embedded weights and available memory.\n", stderr);
            free(faces);
            free(rgb);
            return 1;
        }
    }
    if (out_path && overlay_write_ppm(out_path, rgb, width, height, faces, n) != 0) {
        fprintf(stderr, "Could not write overlay to %s.\n", out_path);
        free(faces);
        free(rgb);
        return 1;
    }
    free(rgb);
    printf("{\"width\":%d,\"height\":%d,\"input_width\":%d,\"input_height\":%d,\"faces\":[",
           width, height, iw, ih);
    for (int i = 0; i < n; i++) {
        const facedet_detection *d = &faces[i];
        printf("%s{\"box\":[%.7g,%.7g,%.7g,%.7g],\"score\":%.7g,\"landmarks\":[",
               i ? "," : "", d->x, d->y, d->w, d->h, d->score);
        for (int k = 0; k < 5; k++)
            printf("%s[%.7g,%.7g]", k ? "," : "", d->lmk[k][0], d->lmk[k][1]);
        printf("]}");
    }
    printf("]}\n");
    free(faces);
    return fflush(stdout) == 0 ? 0 : 1;
}