]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_readeia608.c
avfilter/vf_readeia608: add support for slice threads
[ffmpeg] / libavfilter / vf_readeia608.c
1 /*
2  * Copyright (c) 2017 Paul B Mahol
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * Filter for reading closed captioning data (EIA-608).
24  * See also https://en.wikipedia.org/wiki/EIA-608
25  */
26
27 #include <string.h>
28
29 #include "libavutil/internal.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/pixdesc.h"
32 #include "libavutil/timestamp.h"
33
34 #include "avfilter.h"
35 #include "formats.h"
36 #include "internal.h"
37 #include "video.h"
38
39 #define LAG 25
40 #define CLOCK_BITSIZE_MIN 0.2f
41 #define CLOCK_BITSIZE_MAX 1.5f
42 #define SYNC_BITSIZE_MIN 12.f
43 #define SYNC_BITSIZE_MAX 15.f
44
45 typedef struct LineItem {
46     int   input;
47     int   output;
48
49     float unfiltered;
50     float filtered;
51     float average;
52     float deviation;
53 } LineItem;
54
55 typedef struct CodeItem {
56     uint8_t bit;
57     int size;
58 } CodeItem;
59
60 typedef struct ScanItem {
61     int nb_line;
62     int found;
63     int white;
64     int black;
65     uint64_t histogram[256];
66     uint8_t byte[2];
67
68     CodeItem *code;
69     LineItem *line;
70 } ScanItem;
71
72 typedef struct ReadEIA608Context {
73     const AVClass *class;
74
75     int start, end;
76     float spw;
77     int chp;
78     int lp;
79
80     int nb_allocated;
81     ScanItem *scan;
82 } ReadEIA608Context;
83
84 #define OFFSET(x) offsetof(ReadEIA608Context, x)
85 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_RUNTIME_PARAM
86
87 static const AVOption readeia608_options[] = {
88     { "scan_min", "set from which line to scan for codes",               OFFSET(start), AV_OPT_TYPE_INT,   {.i64=0},     0, INT_MAX, FLAGS },
89     { "scan_max", "set to which line to scan for codes",                 OFFSET(end),   AV_OPT_TYPE_INT,   {.i64=29},    0, INT_MAX, FLAGS },
90     { "spw",      "set ratio of width reserved for sync code detection", OFFSET(spw),   AV_OPT_TYPE_FLOAT, {.dbl=.27}, 0.1,     0.7, FLAGS },
91     { "chp",      "check and apply parity bit",                          OFFSET(chp),   AV_OPT_TYPE_BOOL,  {.i64= 0},    0,       1, FLAGS },
92     { "lp",       "lowpass line prior to processing",                    OFFSET(lp),    AV_OPT_TYPE_BOOL,  {.i64= 1},    0,       1, FLAGS },
93     { NULL }
94 };
95
96 AVFILTER_DEFINE_CLASS(readeia608);
97
98 static int query_formats(AVFilterContext *ctx)
99 {
100     static const enum AVPixelFormat pixel_fmts[] = {
101         AV_PIX_FMT_GRAY8,
102         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
103         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
104         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
105         AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
106         AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
107         AV_PIX_FMT_YUVJ411P,
108         AV_PIX_FMT_NONE
109     };
110     AVFilterFormats *formats = ff_make_format_list(pixel_fmts);
111     if (!formats)
112         return AVERROR(ENOMEM);
113     return ff_set_common_formats(ctx, formats);
114 }
115
116 static int config_filter(AVFilterContext *ctx, int start, int end)
117 {
118     ReadEIA608Context *s = ctx->priv;
119     AVFilterLink *inlink = ctx->inputs[0];
120     int size = inlink->w + LAG;
121
122     if (end >= inlink->h) {
123         av_log(ctx, AV_LOG_WARNING, "Last line to scan too large, clipping.\n");
124         end = inlink->h - 1;
125     }
126
127     if (start > end) {
128         av_log(ctx, AV_LOG_ERROR, "Invalid range.\n");
129         return AVERROR(EINVAL);
130     }
131
132     if (s->nb_allocated < end - start + 1) {
133         const int diff = end - start + 1 - s->nb_allocated;
134
135         s->scan = av_realloc_f(s->scan, end - start + 1, sizeof(*s->scan));
136         if (!s->scan)
137             return AVERROR(ENOMEM);
138         memset(&s->scan[s->nb_allocated], 0, diff * sizeof(*s->scan));
139         s->nb_allocated = end - start + 1;
140     }
141
142     for (int i = 0; i < s->nb_allocated; i++) {
143         ScanItem *scan = &s->scan[i];
144
145         if (!scan->line)
146             scan->line = av_calloc(size, sizeof(*scan->line));
147         if (!scan->code)
148             scan->code = av_calloc(size, sizeof(*scan->code));
149         if (!scan->line || !scan->code)
150             return AVERROR(ENOMEM);
151     }
152
153     s->start = start;
154     s->end = end;
155
156     return 0;
157 }
158
159 static int config_input(AVFilterLink *inlink)
160 {
161     AVFilterContext *ctx = inlink->dst;
162     ReadEIA608Context *s = ctx->priv;
163
164     return config_filter(ctx, s->start, s->end);
165 }
166
167 static void build_histogram(ReadEIA608Context *s, ScanItem *scan, const LineItem *line, int len)
168 {
169     memset(scan->histogram, 0, sizeof(scan->histogram));
170
171     for (int i = LAG; i < len + LAG; i++)
172         scan->histogram[line[i].input]++;
173 }
174
175 static void find_black_and_white(ReadEIA608Context *s, ScanItem *scan)
176 {
177     int start = 0, end = 0, middle;
178     int black = 0, white = 0;
179     int cnt;
180
181     for (int i = 0; i < 256; i++) {
182         if (scan->histogram[i]) {
183             start = i;
184             break;
185         }
186     }
187
188     for (int i = 255; i >= 0; i--) {
189         if (scan->histogram[i]) {
190             end = i;
191             break;
192         }
193     }
194
195     middle = start + (end - start) / 2;
196
197     cnt = 0;
198     for (int i = start; i <= middle; i++) {
199         if (scan->histogram[i] > cnt) {
200             cnt = scan->histogram[i];
201             black = i;
202         }
203     }
204
205     cnt = 0;
206     for (int i = end; i >= middle; i--) {
207         if (scan->histogram[i] > cnt) {
208             cnt = scan->histogram[i];
209             white = i;
210         }
211     }
212
213     scan->black = black;
214     scan->white = white;
215 }
216
217 static float meanf(const LineItem *line, int len)
218 {
219     float sum = 0.0, mean = 0.0;
220
221     for (int i = 0; i < len; i++)
222         sum += line[i].filtered;
223
224     mean = sum / len;
225
226     return mean;
227 }
228
229 static float stddevf(const LineItem *line, int len)
230 {
231     float m = meanf(line, len);
232     float standard_deviation = 0.f;
233
234     for (int i = 0; i < len; i++)
235         standard_deviation += (line[i].filtered - m) * (line[i].filtered - m);
236
237     return sqrtf(standard_deviation / (len - 1));
238 }
239
240 static void thresholding(ReadEIA608Context *s, ScanItem *scan, LineItem *line,
241                          int lag, float threshold, float influence, int len)
242 {
243     for (int i = lag; i < len + lag; i++) {
244         line[i].unfiltered = line[i].input / 255.f;
245         line[i].filtered = line[i].unfiltered;
246     }
247
248     for (int i = 0; i < lag; i++) {
249         line[i].unfiltered = meanf(line, len * s->spw);
250         line[i].filtered = line[i].unfiltered;
251     }
252
253     line[lag - 1].average   = meanf(line, lag);
254     line[lag - 1].deviation = stddevf(line, lag);
255
256     for (int i = lag; i < len + lag; i++) {
257         if (fabsf(line[i].unfiltered - line[i-1].average) > threshold * line[i-1].deviation) {
258             if (line[i].unfiltered > line[i-1].average) {
259                 line[i].output = 255;
260             } else {
261                 line[i].output = 0;
262             }
263
264             line[i].filtered = influence * line[i].unfiltered + (1.f - influence) * line[i-1].filtered;
265         } else {
266             int distance_from_black, distance_from_white;
267
268             distance_from_black = FFABS(line[i].input - scan->black);
269             distance_from_white = FFABS(line[i].input - scan->white);
270
271             line[i].output = distance_from_black <= distance_from_white ? 0 : 255;
272         }
273
274         line[i].average   = meanf(line + i - lag, lag);
275         line[i].deviation = stddevf(line + i - lag, lag);
276     }
277 }
278
279 static int periods(const LineItem *line, CodeItem *code, int len)
280 {
281     int hold = line[LAG].output, cnt = 0;
282     int last = LAG;
283
284     memset(code, 0, len * sizeof(*code));
285
286     for (int i = LAG + 1; i < len + LAG; i++) {
287         if (line[i].output != hold) {
288             code[cnt].size = i - last;
289             code[cnt].bit = hold;
290             hold = line[i].output;
291             last = i;
292             cnt++;
293         }
294     }
295
296     code[cnt].size = LAG + len - last;
297     code[cnt].bit = hold;
298
299     return cnt + 1;
300 }
301
302 static void dump_code(AVFilterContext *ctx, ScanItem *scan, int len, int item)
303 {
304     av_log(ctx, AV_LOG_DEBUG, "%d:", item);
305     for (int i = 0; i < len; i++) {
306         av_log(ctx, AV_LOG_DEBUG, " %03d", scan->code[i].size);
307     }
308     av_log(ctx, AV_LOG_DEBUG, "\n");
309 }
310
311 static void extract_line(AVFilterContext *ctx, AVFrame *in, ScanItem *scan, int w, int nb_line)
312 {
313     ReadEIA608Context *s = ctx->priv;
314     LineItem *line = scan->line;
315     int i, j, ch, len;
316     const uint8_t *src;
317     uint8_t codes[19] = { 0 };
318     float bit_size = 0.f;
319     int parity;
320
321     memset(line, 0, (w + LAG) * sizeof(*line));
322     scan->byte[0] = scan->byte[1] = 0;
323     scan->found = 0;
324
325     src = &in->data[0][nb_line * in->linesize[0]];
326     if (s->lp) {
327         for (i = 0; i < w; i++) {
328             int a = FFMAX(i - 3, 0);
329             int b = FFMAX(i - 2, 0);
330             int c = FFMAX(i - 1, 0);
331             int d = FFMIN(i + 3, w-1);
332             int e = FFMIN(i + 2, w-1);
333             int f = FFMIN(i + 1, w-1);
334
335             line[LAG + i].input = (src[a] + src[b] + src[c] + src[i] + src[d] + src[e] + src[f] + 6) / 7;
336         }
337     } else {
338         for (i = 0; i < w; i++) {
339             line[LAG + i].input = src[i];
340         }
341     }
342
343     build_histogram(s, scan, line, w);
344     find_black_and_white(s, scan);
345     if (scan->white - scan->black < 5)
346         return;
347
348     thresholding(s, scan, line, LAG, 1, 0, w);
349     len = periods(line, scan->code, w);
350     dump_code(ctx, scan, len, nb_line);
351     if (len < 15 ||
352         scan->code[14].bit != 0 ||
353         w / (float)scan->code[14].size < SYNC_BITSIZE_MIN ||
354         w / (float)scan->code[14].size > SYNC_BITSIZE_MAX) {
355         return;
356     }
357
358     for (i = 14; i < len; i++) {
359         bit_size += scan->code[i].size;
360     }
361
362     bit_size /= 19.f;
363     for (i = 1; i < 14; i++) {
364         if (scan->code[i].size / bit_size > CLOCK_BITSIZE_MAX ||
365             scan->code[i].size / bit_size < CLOCK_BITSIZE_MIN) {
366             return;
367         }
368     }
369
370     if (scan->code[15].size / bit_size < 0.45f) {
371         return;
372     }
373
374     for (j = 0, i = 14; i < len; i++) {
375         int run, bit;
376
377         run = lrintf(scan->code[i].size / bit_size);
378         bit = scan->code[i].bit;
379
380         for (int k = 0; j < 19 && k < run; k++) {
381             codes[j++] = bit;
382         }
383
384         if (j >= 19)
385             break;
386     }
387
388     for (ch = 0; ch < 2; ch++) {
389         for (parity = 0, i = 0; i < 8; i++) {
390             int b = codes[3 + ch * 8 + i];
391
392             if (b == 255) {
393                 parity++;
394                 b = 1;
395             } else {
396                 b = 0;
397             }
398             scan->byte[ch] |= b << i;
399         }
400
401         if (s->chp) {
402             if (!(parity & 1)) {
403                 scan->byte[ch] = 0x7F;
404             }
405         }
406     }
407
408     scan->nb_line = nb_line;
409     scan->found = 1;
410 }
411
412 static int extract_lines(AVFilterContext *ctx, void *arg,
413                          int job, int nb_jobs)
414 {
415     ReadEIA608Context *s = ctx->priv;
416     AVFilterLink *inlink = ctx->inputs[0];
417     const int h = s->end - s->start + 1;
418     const int start = (h * job) / nb_jobs;
419     const int end   = (h * (job+1)) / nb_jobs;
420     AVFrame *in = arg;
421
422     for (int i = start; i < end; i++) {
423         ScanItem *scan = &s->scan[i];
424
425         extract_line(ctx, in, scan, inlink->w, i);
426     }
427
428     return 0;
429 }
430
431 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
432 {
433     AVFilterContext *ctx  = inlink->dst;
434     AVFilterLink *outlink = ctx->outputs[0];
435     ReadEIA608Context *s = ctx->priv;
436     int nb_found;
437
438     ctx->internal->execute(ctx, extract_lines, in, NULL, FFMIN(FFMAX(s->end - s->start + 1, 1),
439                                                                ff_filter_get_nb_threads(ctx)));
440
441     nb_found = 0;
442     for (int i = 0; i < s->end - s->start + 1; i++) {
443         ScanItem *scan = &s->scan[i];
444         uint8_t key[128], value[128];
445
446         if (!scan->found)
447             continue;
448
449         //snprintf(key, sizeof(key), "lavfi.readeia608.%d.bits", nb_found);
450         //snprintf(value, sizeof(value), "0b%d%d%d%d%d%d%d%d 0b%d%d%d%d%d%d%d%d", codes[3]==255,codes[4]==255,codes[5]==255,codes[6]==255,codes[7]==255,codes[8]==255,codes[9]==255,codes[10]==255,codes[11]==255,codes[12]==255,codes[13]==255,codes[14]==255,codes[15]==255,codes[16]==255,codes[17]==255,codes[18]==255);
451         //av_dict_set(&in->metadata, key, value, 0);
452
453         snprintf(key, sizeof(key), "lavfi.readeia608.%d.cc", nb_found);
454         snprintf(value, sizeof(value), "0x%02X%02X", scan->byte[0], scan->byte[1]);
455         av_dict_set(&in->metadata, key, value, 0);
456
457         snprintf(key, sizeof(key), "lavfi.readeia608.%d.line", nb_found);
458         snprintf(value, sizeof(value), "%d", scan->nb_line);
459         av_dict_set(&in->metadata, key, value, 0);
460
461         nb_found++;
462     }
463
464     return ff_filter_frame(outlink, in);
465 }
466
467 static av_cold void uninit(AVFilterContext *ctx)
468 {
469     ReadEIA608Context *s = ctx->priv;
470
471     for (int i = 0; i < s->nb_allocated; i++) {
472         ScanItem *scan = &s->scan[i];
473
474         av_freep(&scan->code);
475         av_freep(&scan->line);
476     }
477
478     s->nb_allocated = 0;
479     av_freep(&s->scan);
480 }
481
482 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
483                            char *res, int res_len, int flags)
484 {
485     ReadEIA608Context *s = ctx->priv;
486     int ret, start = s->start, end = s->end;
487
488     ret = ff_filter_process_command(ctx, cmd, args, res, res_len, flags);
489     if (ret < 0)
490         return ret;
491
492     ret = config_filter(ctx, s->start, s->end);
493     if (ret < 0) {
494         s->start = start;
495         s->end = end;
496     }
497
498     return 0;
499 }
500
501 static const AVFilterPad readeia608_inputs[] = {
502     {
503         .name         = "default",
504         .type         = AVMEDIA_TYPE_VIDEO,
505         .filter_frame = filter_frame,
506         .config_props = config_input,
507     },
508     { NULL }
509 };
510
511 static const AVFilterPad readeia608_outputs[] = {
512     {
513         .name = "default",
514         .type = AVMEDIA_TYPE_VIDEO,
515     },
516     { NULL }
517 };
518
519 AVFilter ff_vf_readeia608 = {
520     .name          = "readeia608",
521     .description   = NULL_IF_CONFIG_SMALL("Read EIA-608 Closed Caption codes from input video and write them to frame metadata."),
522     .priv_size     = sizeof(ReadEIA608Context),
523     .priv_class    = &readeia608_class,
524     .query_formats = query_formats,
525     .inputs        = readeia608_inputs,
526     .outputs       = readeia608_outputs,
527     .uninit        = uninit,
528     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
529     .process_command = process_command,
530 };