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 ReadEIA608Context {
61     const AVClass *class;
62     int start, end;
63     int nb_found;
64     int white;
65     int black;
66     float spw;
67     int chp;
68     int lp;
69 
70     uint64_t histogram[256];
71 
72     CodeItem *code;
73     LineItem *line;
74 } ReadEIA608Context;
75 
76 #define OFFSET(x) offsetof(ReadEIA608Context, x)
77 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
78 
79 static const AVOption readeia608_options[] = {
80     { "scan_min", "set from which line to scan for codes",               OFFSET(start), AV_OPT_TYPE_INT,   {.i64=0},     0, INT_MAX, FLAGS },
81     { "scan_max", "set to which line to scan for codes",                 OFFSET(end),   AV_OPT_TYPE_INT,   {.i64=29},    0, INT_MAX, FLAGS },
82     { "spw",      "set ratio of width reserved for sync code detection", OFFSET(spw),   AV_OPT_TYPE_FLOAT, {.dbl=.27}, 0.1,     0.7, FLAGS },
83     { "chp",      "check and apply parity bit",                          OFFSET(chp),   AV_OPT_TYPE_BOOL,  {.i64= 0},    0,       1, FLAGS },
84     { "lp",       "lowpass line prior to processing",                    OFFSET(lp),    AV_OPT_TYPE_BOOL,  {.i64= 1},    0,       1, FLAGS },
85     { NULL }
86 };
87 
88 AVFILTER_DEFINE_CLASS(readeia608);
89 
query_formats(AVFilterContext * ctx)90 static int query_formats(AVFilterContext *ctx)
91 {
92     static const enum AVPixelFormat pixel_fmts[] = {
93         AV_PIX_FMT_GRAY8,
94         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
95         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
96         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
97         AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
98         AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
99         AV_PIX_FMT_YUVJ411P,
100         AV_PIX_FMT_NONE
101     };
102     AVFilterFormats *formats = ff_make_format_list(pixel_fmts);
103     if (!formats)
104         return AVERROR(ENOMEM);
105     return ff_set_common_formats(ctx, formats);
106 }
107 
config_input(AVFilterLink * inlink)108 static int config_input(AVFilterLink *inlink)
109 {
110     AVFilterContext *ctx = inlink->dst;
111     ReadEIA608Context *s = ctx->priv;
112     int size = inlink->w + LAG;
113 
114     if (s->end >= inlink->h) {
115         av_log(ctx, AV_LOG_WARNING, "Last line to scan too large, clipping.\n");
116         s->end = inlink->h - 1;
117     }
118 
119     if (s->start > s->end) {
120         av_log(ctx, AV_LOG_ERROR, "Invalid range.\n");
121         return AVERROR(EINVAL);
122     }
123 
124     s->line = av_calloc(size, sizeof(*s->line));
125     s->code = av_calloc(size, sizeof(*s->code));
126     if (!s->line || !s->code)
127         return AVERROR(ENOMEM);
128 
129     return 0;
130 }
131 
build_histogram(ReadEIA608Context * s,const LineItem * line,int len)132 static void build_histogram(ReadEIA608Context *s, const LineItem *line, int len)
133 {
134     memset(s->histogram, 0, sizeof(s->histogram));
135 
136     for (int i = LAG; i < len + LAG; i++)
137         s->histogram[line[i].input]++;
138 }
139 
find_black_and_white(ReadEIA608Context * s)140 static void find_black_and_white(ReadEIA608Context *s)
141 {
142     int start = 0, end = 0, middle;
143     int black = 0, white = 0;
144     int cnt;
145 
146     for (int i = 0; i < 256; i++) {
147         if (s->histogram[i]) {
148             start = i;
149             break;
150         }
151     }
152 
153     for (int i = 255; i >= 0; i--) {
154         if (s->histogram[i]) {
155             end = i;
156             break;
157         }
158     }
159 
160     middle = start + (end - start) / 2;
161 
162     cnt = 0;
163     for (int i = start; i <= middle; i++) {
164         if (s->histogram[i] > cnt) {
165             cnt = s->histogram[i];
166             black = i;
167         }
168     }
169 
170     cnt = 0;
171     for (int i = end; i >= middle; i--) {
172         if (s->histogram[i] > cnt) {
173             cnt = s->histogram[i];
174             white = i;
175         }
176     }
177 
178     s->black = black;
179     s->white = white;
180 }
181 
meanf(const LineItem * line,int len)182 static float meanf(const LineItem *line, int len)
183 {
184     float sum = 0.0, mean = 0.0;
185 
186     for (int i = 0; i < len; i++)
187         sum += line[i].filtered;
188 
189     mean = sum / len;
190 
191     return mean;
192 }
193 
stddevf(const LineItem * line,int len)194 static float stddevf(const LineItem *line, int len)
195 {
196     float m = meanf(line, len);
197     float standard_deviation = 0.f;
198 
199     for (int i = 0; i < len; i++)
200         standard_deviation += (line[i].filtered - m) * (line[i].filtered - m);
201 
202     return sqrtf(standard_deviation / (len - 1));
203 }
204 
thresholding(ReadEIA608Context * s,LineItem * line,int lag,float threshold,float influence,int len)205 static void thresholding(ReadEIA608Context *s, LineItem *line,
206                          int lag, float threshold, float influence, int len)
207 {
208     for (int i = lag; i < len + lag; i++) {
209         line[i].unfiltered = line[i].input / 255.f;
210         line[i].filtered = line[i].unfiltered;
211     }
212 
213     for (int i = 0; i < lag; i++) {
214         line[i].unfiltered = meanf(line, len * s->spw);
215         line[i].filtered = line[i].unfiltered;
216     }
217 
218     line[lag - 1].average   = meanf(line, lag);
219     line[lag - 1].deviation = stddevf(line, lag);
220 
221     for (int i = lag; i < len + lag; i++) {
222         if (fabsf(line[i].unfiltered - line[i-1].average) > threshold * line[i-1].deviation) {
223             if (line[i].unfiltered > line[i-1].average) {
224                 line[i].output = 255;
225             } else {
226                 line[i].output = 0;
227             }
228 
229             line[i].filtered = influence * line[i].unfiltered + (1.f - influence) * line[i-1].filtered;
230         } else {
231             int distance_from_black, distance_from_white;
232 
233             distance_from_black = FFABS(line[i].input - s->black);
234             distance_from_white = FFABS(line[i].input - s->white);
235 
236             line[i].output = distance_from_black <= distance_from_white ? 0 : 255;
237         }
238 
239         line[i].average   = meanf(line + i - lag, lag);
240         line[i].deviation = stddevf(line + i - lag, lag);
241     }
242 }
243 
periods(const LineItem * line,CodeItem * code,int len)244 static int periods(const LineItem *line, CodeItem *code, int len)
245 {
246     int hold = line[LAG].output, cnt = 0;
247     int last = LAG;
248 
249     memset(code, 0, len * sizeof(*code));
250 
251     for (int i = LAG + 1; i < len + LAG; i++) {
252         if (line[i].output != hold) {
253             code[cnt].size = i - last;
254             code[cnt].bit = hold;
255             hold = line[i].output;
256             last = i;
257             cnt++;
258         }
259     }
260 
261     code[cnt].size = LAG + len - last;
262     code[cnt].bit = hold;
263 
264     return cnt + 1;
265 }
266 
dump_code(AVFilterContext * ctx,int len,int item)267 static void dump_code(AVFilterContext *ctx, int len, int item)
268 {
269     ReadEIA608Context *s = ctx->priv;
270 
271     av_log(ctx, AV_LOG_DEBUG, "%d:", item);
272     for (int i = 0; i < len; i++) {
273         av_log(ctx, AV_LOG_DEBUG, " %03d", s->code[i].size);
274     }
275     av_log(ctx, AV_LOG_DEBUG, "\n");
276 }
277 
extract_line(AVFilterContext * ctx,AVFrame * in,int w,int nb_line)278 static void extract_line(AVFilterContext *ctx, AVFrame *in, int w, int nb_line)
279 {
280     ReadEIA608Context *s = ctx->priv;
281     LineItem *line = s->line;
282     int i, j, ch, len;
283     const uint8_t *src;
284     uint8_t byte[2] = { 0 };
285     uint8_t codes[19] = { 0 };
286     float bit_size = 0.f;
287     int parity;
288 
289     memset(line, 0, (w + LAG) * sizeof(*line));
290 
291     src = &in->data[0][nb_line * in->linesize[0]];
292     if (s->lp) {
293         for (i = 0; i < w; i++) {
294             int a = FFMAX(i - 3, 0);
295             int b = FFMAX(i - 2, 0);
296             int c = FFMAX(i - 1, 0);
297             int d = FFMIN(i + 3, w-1);
298             int e = FFMIN(i + 2, w-1);
299             int f = FFMIN(i + 1, w-1);
300 
301             line[LAG + i].input = (src[a] + src[b] + src[c] + src[i] + src[d] + src[e] + src[f] + 6) / 7;
302         }
303     } else {
304         for (i = 0; i < w; i++) {
305             line[LAG + i].input = src[i];
306         }
307     }
308 
309     build_histogram(s, line, w);
310     find_black_and_white(s);
311     if (s->white - s->black < 5)
312         return;
313 
314     thresholding(s, line, LAG, 1, 0, w);
315     len = periods(line, s->code, w);
316     dump_code(ctx, len, nb_line);
317     if (len < 15 ||
318         s->code[14].bit != 0 ||
319         w / (float)s->code[14].size < SYNC_BITSIZE_MIN ||
320         w / (float)s->code[14].size > SYNC_BITSIZE_MAX) {
321         return;
322     }
323 
324     for (i = 14; i < len; i++) {
325         bit_size += s->code[i].size;
326     }
327 
328     bit_size /= 19.f;
329     for (i = 1; i < 14; i++) {
330         if (s->code[i].size / bit_size > CLOCK_BITSIZE_MAX ||
331             s->code[i].size / bit_size < CLOCK_BITSIZE_MIN) {
332             return;
333         }
334     }
335 
336     if (s->code[15].size / bit_size < 0.45f) {
337         return;
338     }
339 
340     for (j = 0, i = 14; i < len; i++) {
341         int run, bit;
342 
343         run = lrintf(s->code[i].size / bit_size);
344         bit = s->code[i].bit;
345 
346         for (int k = 0; j < 19 && k < run; k++) {
347             codes[j++] = bit;
348         }
349 
350         if (j >= 19)
351             break;
352     }
353 
354     for (ch = 0; ch < 2; ch++) {
355         for (parity = 0, i = 0; i < 8; i++) {
356             int b = codes[3 + ch * 8 + i];
357 
358             if (b == 255) {
359                 parity++;
360                 b = 1;
361             } else {
362                 b = 0;
363             }
364             byte[ch] |= b << i;
365         }
366 
367         if (s->chp) {
368             if (!(parity & 1)) {
369                 byte[ch] = 0x7F;
370             }
371         }
372     }
373 
374     {
375         uint8_t key[128], value[128];
376 
377         //snprintf(key, sizeof(key), "lavfi.readeia608.%d.bits", s->nb_found);
378         //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);
379         //av_dict_set(&in->metadata, key, value, 0);
380 
381         snprintf(key, sizeof(key), "lavfi.readeia608.%d.cc", s->nb_found);
382         snprintf(value, sizeof(value), "0x%02X%02X", byte[0], byte[1]);
383         av_dict_set(&in->metadata, key, value, 0);
384 
385         snprintf(key, sizeof(key), "lavfi.readeia608.%d.line", s->nb_found);
386         snprintf(value, sizeof(value), "%d", nb_line);
387         av_dict_set(&in->metadata, key, value, 0);
388     }
389 
390     s->nb_found++;
391 }
392 
filter_frame(AVFilterLink * inlink,AVFrame * in)393 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
394 {
395     AVFilterContext *ctx  = inlink->dst;
396     AVFilterLink *outlink = ctx->outputs[0];
397     ReadEIA608Context *s = ctx->priv;
398     int i;
399 
400     s->nb_found = 0;
401     for (i = s->start; i <= s->end; i++)
402         extract_line(ctx, in, inlink->w, i);
403 
404     return ff_filter_frame(outlink, in);
405 }
406 
uninit(AVFilterContext * ctx)407 static av_cold void uninit(AVFilterContext *ctx)
408 {
409     ReadEIA608Context *s = ctx->priv;
410 
411     av_freep(&s->code);
412     av_freep(&s->line);
413 }
414 
415 static const AVFilterPad readeia608_inputs[] = {
416     {
417         .name         = "default",
418         .type         = AVMEDIA_TYPE_VIDEO,
419         .filter_frame = filter_frame,
420         .config_props = config_input,
421     },
422     { NULL }
423 };
424 
425 static const AVFilterPad readeia608_outputs[] = {
426     {
427         .name = "default",
428         .type = AVMEDIA_TYPE_VIDEO,
429     },
430     { NULL }
431 };
432 
433 AVFilter ff_vf_readeia608 = {
434     .name          = "readeia608",
435     .description   = NULL_IF_CONFIG_SMALL("Read EIA-608 Closed Caption codes from input video and write them to frame metadata."),
436     .priv_size     = sizeof(ReadEIA608Context),
437     .priv_class    = &readeia608_class,
438     .query_formats = query_formats,
439     .inputs        = readeia608_inputs,
440     .outputs       = readeia608_outputs,
441     .uninit        = uninit,
442     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
443 };
444