]> git.sesse.net Git - ffmpeg/blob - libavcodec/ccaption_dec.c
avcodec/ccaption_dec: do not modify pkt data and stop removing parity bit twice
[ffmpeg] / libavcodec / ccaption_dec.c
1 /*
2  * Closed Caption Decoding
3  * Copyright (c) 2015 Anshul Maheshwari
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "avcodec.h"
23 #include "ass.h"
24 #include "libavutil/opt.h"
25
26 #define SCREEN_ROWS 15
27 #define SCREEN_COLUMNS 32
28
29 #define SET_FLAG(var, val)   ( (var) |=   ( 1 << (val)) )
30 #define UNSET_FLAG(var, val) ( (var) &=  ~( 1 << (val)) )
31 #define CHECK_FLAG(var, val) ( (var) &    ( 1 << (val)) )
32
33 static const AVRational ms_tb = {1, 1000};
34
35 enum cc_mode {
36     CCMODE_POPON,
37     CCMODE_PAINTON,
38     CCMODE_ROLLUP,
39     CCMODE_TEXT,
40 };
41
42 enum cc_color_code {
43     CCCOL_WHITE,
44     CCCOL_GREEN,
45     CCCOL_BLUE,
46     CCCOL_CYAN,
47     CCCOL_RED,
48     CCCOL_YELLOW,
49     CCCOL_MAGENTA,
50     CCCOL_USERDEFINED,
51     CCCOL_BLACK,
52     CCCOL_TRANSPARENT,
53 };
54
55 enum cc_font {
56     CCFONT_REGULAR,
57     CCFONT_ITALICS,
58     CCFONT_UNDERLINED,
59     CCFONT_UNDERLINED_ITALICS,
60 };
61
62 enum cc_charset {
63     CCSET_BASIC_AMERICAN,
64     CCSET_SPECIAL_AMERICAN,
65     CCSET_EXTENDED_SPANISH_FRENCH_MISC,
66     CCSET_EXTENDED_PORTUGUESE_GERMAN_DANISH,
67 };
68
69 static const char *charset_overrides[4][128] =
70 {
71     [CCSET_BASIC_AMERICAN] = {
72         [0x27] = "\u2019",
73         [0x2a] = "\u00e1",
74         [0x5c] = "\u00e9",
75         [0x5e] = "\u00ed",
76         [0x5f] = "\u00f3",
77         [0x60] = "\u00fa",
78         [0x7b] = "\u00e7",
79         [0x7c] = "\u00f7",
80         [0x7d] = "\u00d1",
81         [0x7e] = "\u00f1",
82         [0x7f] = "\u2588"
83     },
84     [CCSET_SPECIAL_AMERICAN] = {
85         [0x30] = "\u00ae",
86         [0x31] = "\u00b0",
87         [0x32] = "\u00bd",
88         [0x33] = "\u00bf",
89         [0x34] = "\u2122",
90         [0x35] = "\u00a2",
91         [0x36] = "\u00a3",
92         [0x37] = "\u266a",
93         [0x38] = "\u00e0",
94         [0x39] = "\u00A0",
95         [0x3a] = "\u00e8",
96         [0x3b] = "\u00e2",
97         [0x3c] = "\u00ea",
98         [0x3d] = "\u00ee",
99         [0x3e] = "\u00f4",
100         [0x3f] = "\u00fb",
101     },
102     [CCSET_EXTENDED_SPANISH_FRENCH_MISC] = {
103         [0x20] = "\u00c1",
104         [0x21] = "\u00c9",
105         [0x22] = "\u00d3",
106         [0x23] = "\u00da",
107         [0x24] = "\u00dc",
108         [0x25] = "\u00fc",
109         [0x26] = "\u00b4",
110         [0x27] = "\u00a1",
111         [0x28] = "*",
112         [0x29] = "\u2018",
113         [0x2a] = "-",
114         [0x2b] = "\u00a9",
115         [0x2c] = "\u2120",
116         [0x2d] = "\u00b7",
117         [0x2e] = "\u201c",
118         [0x2f] = "\u201d",
119         [0x30] = "\u00c0",
120         [0x31] = "\u00c2",
121         [0x32] = "\u00c7",
122         [0x33] = "\u00c8",
123         [0x34] = "\u00ca",
124         [0x35] = "\u00cb",
125         [0x36] = "\u00eb",
126         [0x37] = "\u00ce",
127         [0x38] = "\u00cf",
128         [0x39] = "\u00ef",
129         [0x3a] = "\u00d4",
130         [0x3b] = "\u00d9",
131         [0x3c] = "\u00f9",
132         [0x3d] = "\u00db",
133         [0x3e] = "\u00ab",
134         [0x3f] = "\u00bb",
135     },
136     [CCSET_EXTENDED_PORTUGUESE_GERMAN_DANISH] = {
137         [0x20] = "\u00c3",
138         [0x21] = "\u00e3",
139         [0x22] = "\u00cd",
140         [0x23] = "\u00cc",
141         [0x24] = "\u00ec",
142         [0x25] = "\u00d2",
143         [0x26] = "\u00f2",
144         [0x27] = "\u00d5",
145         [0x28] = "\u00f5",
146         [0x29] = "{",
147         [0x2a] = "}",
148         [0x2b] = "\\",
149         [0x2c] = "^",
150         [0x2d] = "_",
151         [0x2e] = "|",
152         [0x2f] = "~",
153         [0x30] = "\u00c4",
154         [0x31] = "\u00e4",
155         [0x32] = "\u00d6",
156         [0x33] = "\u00f6",
157         [0x34] = "\u00df",
158         [0x35] = "\u00a5",
159         [0x36] = "\u00a4",
160         [0x37] = "\u00a6",
161         [0x38] = "\u00c5",
162         [0x39] = "\u00e5",
163         [0x3a] = "\u00d8",
164         [0x3b] = "\u00f8",
165         [0x3c] = "\u250c",
166         [0x3d] = "\u2510",
167         [0x3e] = "\u2514",
168         [0x3f] = "\u2518",
169     },
170 };
171
172 static const unsigned char pac2_attribs[32][3] = // Color, font, ident
173 {
174     { CCCOL_WHITE,   CCFONT_REGULAR,            0 },  // 0x40 || 0x60
175     { CCCOL_WHITE,   CCFONT_UNDERLINED,         0 },  // 0x41 || 0x61
176     { CCCOL_GREEN,   CCFONT_REGULAR,            0 },  // 0x42 || 0x62
177     { CCCOL_GREEN,   CCFONT_UNDERLINED,         0 },  // 0x43 || 0x63
178     { CCCOL_BLUE,    CCFONT_REGULAR,            0 },  // 0x44 || 0x64
179     { CCCOL_BLUE,    CCFONT_UNDERLINED,         0 },  // 0x45 || 0x65
180     { CCCOL_CYAN,    CCFONT_REGULAR,            0 },  // 0x46 || 0x66
181     { CCCOL_CYAN,    CCFONT_UNDERLINED,         0 },  // 0x47 || 0x67
182     { CCCOL_RED,     CCFONT_REGULAR,            0 },  // 0x48 || 0x68
183     { CCCOL_RED,     CCFONT_UNDERLINED,         0 },  // 0x49 || 0x69
184     { CCCOL_YELLOW,  CCFONT_REGULAR,            0 },  // 0x4a || 0x6a
185     { CCCOL_YELLOW,  CCFONT_UNDERLINED,         0 },  // 0x4b || 0x6b
186     { CCCOL_MAGENTA, CCFONT_REGULAR,            0 },  // 0x4c || 0x6c
187     { CCCOL_MAGENTA, CCFONT_UNDERLINED,         0 },  // 0x4d || 0x6d
188     { CCCOL_WHITE,   CCFONT_ITALICS,            0 },  // 0x4e || 0x6e
189     { CCCOL_WHITE,   CCFONT_UNDERLINED_ITALICS, 0 },  // 0x4f || 0x6f
190     { CCCOL_WHITE,   CCFONT_REGULAR,            0 },  // 0x50 || 0x70
191     { CCCOL_WHITE,   CCFONT_UNDERLINED,         0 },  // 0x51 || 0x71
192     { CCCOL_WHITE,   CCFONT_REGULAR,            4 },  // 0x52 || 0x72
193     { CCCOL_WHITE,   CCFONT_UNDERLINED,         4 },  // 0x53 || 0x73
194     { CCCOL_WHITE,   CCFONT_REGULAR,            8 },  // 0x54 || 0x74
195     { CCCOL_WHITE,   CCFONT_UNDERLINED,         8 },  // 0x55 || 0x75
196     { CCCOL_WHITE,   CCFONT_REGULAR,           12 },  // 0x56 || 0x76
197     { CCCOL_WHITE,   CCFONT_UNDERLINED,        12 },  // 0x57 || 0x77
198     { CCCOL_WHITE,   CCFONT_REGULAR,           16 },  // 0x58 || 0x78
199     { CCCOL_WHITE,   CCFONT_UNDERLINED,        16 },  // 0x59 || 0x79
200     { CCCOL_WHITE,   CCFONT_REGULAR,           20 },  // 0x5a || 0x7a
201     { CCCOL_WHITE,   CCFONT_UNDERLINED,        20 },  // 0x5b || 0x7b
202     { CCCOL_WHITE,   CCFONT_REGULAR,           24 },  // 0x5c || 0x7c
203     { CCCOL_WHITE,   CCFONT_UNDERLINED,        24 },  // 0x5d || 0x7d
204     { CCCOL_WHITE,   CCFONT_REGULAR,           28 },  // 0x5e || 0x7e
205     { CCCOL_WHITE,   CCFONT_UNDERLINED,        28 }   // 0x5f || 0x7f
206     /* total 32 entries */
207 };
208
209 struct Screen {
210     /* +1 is used to compensate null character of string */
211     uint8_t characters[SCREEN_ROWS+1][SCREEN_COLUMNS+1];
212     uint8_t charsets[SCREEN_ROWS+1][SCREEN_COLUMNS+1];
213     uint8_t colors[SCREEN_ROWS+1][SCREEN_COLUMNS+1];
214     uint8_t fonts[SCREEN_ROWS+1][SCREEN_COLUMNS+1];
215     /*
216      * Bitmask of used rows; if a bit is not set, the
217      * corresponding row is not used.
218      * for setting row 1  use row | (1 << 0)
219      * for setting row 15 use row | (1 << 14)
220      */
221     int16_t row_used;
222 };
223
224 typedef struct CCaptionSubContext {
225     AVClass *class;
226     int real_time;
227     struct Screen screen[2];
228     int active_screen;
229     uint8_t cursor_row;
230     uint8_t cursor_column;
231     uint8_t cursor_color;
232     uint8_t cursor_font;
233     uint8_t cursor_charset;
234     AVBPrint buffer;
235     int buffer_changed;
236     int rollup;
237     enum cc_mode mode;
238     int64_t start_time;
239     /* visible screen time */
240     int64_t startv_time;
241     int64_t end_time;
242     int screen_touched;
243     int64_t last_real_time;
244     char prev_cmd[2];
245     int readorder;
246 } CCaptionSubContext;
247
248
249 static av_cold int init_decoder(AVCodecContext *avctx)
250 {
251     int ret;
252     CCaptionSubContext *ctx = avctx->priv_data;
253
254     av_bprint_init(&ctx->buffer, 0, AV_BPRINT_SIZE_UNLIMITED);
255     /* taking by default roll up to 2 */
256     ctx->mode = CCMODE_ROLLUP;
257     ctx->rollup = 2;
258     ctx->cursor_row = 10;
259     ret = ff_ass_subtitle_header(avctx, "Monospace",
260                                  ASS_DEFAULT_FONT_SIZE,
261                                  ASS_DEFAULT_COLOR,
262                                  ASS_DEFAULT_BACK_COLOR,
263                                  ASS_DEFAULT_BOLD,
264                                  ASS_DEFAULT_ITALIC,
265                                  ASS_DEFAULT_UNDERLINE,
266                                  3,
267                                  ASS_DEFAULT_ALIGNMENT);
268     if (ret < 0) {
269         return ret;
270     }
271
272     return ret;
273 }
274
275 static av_cold int close_decoder(AVCodecContext *avctx)
276 {
277     CCaptionSubContext *ctx = avctx->priv_data;
278     av_bprint_finalize(&ctx->buffer, NULL);
279     return 0;
280 }
281
282 static void flush_decoder(AVCodecContext *avctx)
283 {
284     CCaptionSubContext *ctx = avctx->priv_data;
285     ctx->screen[0].row_used = 0;
286     ctx->screen[1].row_used = 0;
287     ctx->prev_cmd[0] = 0;
288     ctx->prev_cmd[1] = 0;
289     ctx->mode = CCMODE_ROLLUP;
290     ctx->rollup = 2;
291     ctx->cursor_row = 10;
292     ctx->cursor_column = 0;
293     ctx->cursor_font = 0;
294     ctx->cursor_color = 0;
295     ctx->cursor_charset = 0;
296     ctx->active_screen = 0;
297     ctx->last_real_time = 0;
298     ctx->screen_touched = 0;
299     ctx->buffer_changed = 0;
300     if (!(avctx->flags2 & AV_CODEC_FLAG2_RO_FLUSH_NOOP))
301         ctx->readorder = 0;
302     av_bprint_clear(&ctx->buffer);
303 }
304
305 /**
306  * @param ctx closed caption context just to print log
307  */
308 static void write_char(CCaptionSubContext *ctx, struct Screen *screen, char ch)
309 {
310     uint8_t col = ctx->cursor_column;
311     char *row = screen->characters[ctx->cursor_row];
312     char *font = screen->fonts[ctx->cursor_row];
313     char *color = screen->colors[ctx->cursor_row];
314     char *charset = screen->charsets[ctx->cursor_row];
315
316     if (col < SCREEN_COLUMNS) {
317         row[col] = ch;
318         font[col] = ctx->cursor_font;
319         color[col] = ctx->cursor_color;
320         charset[col] = ctx->cursor_charset;
321         ctx->cursor_charset = CCSET_BASIC_AMERICAN;
322         if (ch) ctx->cursor_column++;
323         return;
324     }
325     /* We have extra space at end only for null character */
326     else if (col == SCREEN_COLUMNS && ch == 0) {
327         row[col] = ch;
328         return;
329     }
330     else {
331         av_log(ctx, AV_LOG_WARNING, "Data Ignored since exceeding screen width\n");
332         return;
333     }
334 }
335
336 /**
337  * This function after validating parity bit, also remove it from data pair.
338  * The first byte doesn't pass parity, we replace it with a solid blank
339  * and process the pair.
340  * If the second byte doesn't pass parity, it returns INVALIDDATA
341  * user can ignore the whole pair and pass the other pair.
342  */
343 static int validate_cc_data_pair(uint8_t *cc_data_pair)
344 {
345     uint8_t cc_valid = (*cc_data_pair & 4) >>2;
346     uint8_t cc_type = *cc_data_pair & 3;
347
348     if (!cc_valid)
349         return AVERROR_INVALIDDATA;
350
351     // if EIA-608 data then verify parity.
352     if (cc_type==0 || cc_type==1) {
353         if (!av_parity(cc_data_pair[2])) {
354             return AVERROR_INVALIDDATA;
355         }
356         if (!av_parity(cc_data_pair[1])) {
357             cc_data_pair[1]=0x7F;
358         }
359     }
360
361     //Skip non-data
362     if ((cc_data_pair[0] == 0xFA || cc_data_pair[0] == 0xFC || cc_data_pair[0] == 0xFD)
363          && (cc_data_pair[1] & 0x7F) == 0 && (cc_data_pair[2] & 0x7F) == 0)
364         return AVERROR_PATCHWELCOME;
365
366     //skip 708 data
367     if (cc_type == 3 || cc_type == 2)
368         return AVERROR_PATCHWELCOME;
369
370     return 0;
371 }
372
373 static struct Screen *get_writing_screen(CCaptionSubContext *ctx)
374 {
375     switch (ctx->mode) {
376     case CCMODE_POPON:
377         // use Inactive screen
378         return ctx->screen + !ctx->active_screen;
379     case CCMODE_PAINTON:
380     case CCMODE_ROLLUP:
381     case CCMODE_TEXT:
382         // use active screen
383         return ctx->screen + ctx->active_screen;
384     }
385     /* It was never an option */
386     return NULL;
387 }
388
389 static void roll_up(CCaptionSubContext *ctx)
390 {
391     struct Screen *screen;
392     int i, keep_lines;
393
394     if (ctx->mode == CCMODE_TEXT)
395         return;
396
397     screen = get_writing_screen(ctx);
398
399     /* +1 signify cursor_row starts from 0
400      * Can't keep lines less then row cursor pos
401      */
402     keep_lines = FFMIN(ctx->cursor_row + 1, ctx->rollup);
403
404     for (i = 0; i < SCREEN_ROWS; i++) {
405         if (i > ctx->cursor_row - keep_lines && i <= ctx->cursor_row)
406             continue;
407         UNSET_FLAG(screen->row_used, i);
408     }
409
410     for (i = 0; i < keep_lines && screen->row_used; i++) {
411         const int i_row = ctx->cursor_row - keep_lines + i + 1;
412
413         memcpy(screen->characters[i_row], screen->characters[i_row+1], SCREEN_COLUMNS);
414         memcpy(screen->colors[i_row], screen->colors[i_row+1], SCREEN_COLUMNS);
415         memcpy(screen->fonts[i_row], screen->fonts[i_row+1], SCREEN_COLUMNS);
416         memcpy(screen->charsets[i_row], screen->charsets[i_row+1], SCREEN_COLUMNS);
417         if (CHECK_FLAG(screen->row_used, i_row + 1))
418             SET_FLAG(screen->row_used, i_row);
419     }
420
421     UNSET_FLAG(screen->row_used, ctx->cursor_row);
422 }
423
424 static int capture_screen(CCaptionSubContext *ctx)
425 {
426     int i, j, tab = 0;
427     struct Screen *screen = ctx->screen + ctx->active_screen;
428     enum cc_font prev_font = CCFONT_REGULAR;
429     enum cc_color_code prev_color = CCCOL_WHITE;
430     av_bprint_clear(&ctx->buffer);
431
432     for (i = 0; screen->row_used && i < SCREEN_ROWS; i++)
433     {
434         if (CHECK_FLAG(screen->row_used, i)) {
435             const char *row = screen->characters[i];
436             const char *charset = screen->charsets[i];
437             j = 0;
438             while (row[j] == ' ' && charset[j] == CCSET_BASIC_AMERICAN)
439                 j++;
440             if (!tab || j < tab)
441                 tab = j;
442         }
443     }
444
445     for (i = 0; screen->row_used && i < SCREEN_ROWS; i++)
446     {
447         if (CHECK_FLAG(screen->row_used, i)) {
448             const char *row = screen->characters[i];
449             const char *font = screen->fonts[i];
450             const char *color = screen->colors[i];
451             const char *charset = screen->charsets[i];
452             const char *override;
453             int x, y, seen_char = 0;
454             j = 0;
455
456             /* skip leading space */
457             while (row[j] == ' ' && charset[j] == CCSET_BASIC_AMERICAN && j < tab)
458                 j++;
459
460             x = ASS_DEFAULT_PLAYRESX * (0.1 + 0.0250 * j);
461             y = ASS_DEFAULT_PLAYRESY * (0.1 + 0.0533 * i);
462             av_bprintf(&ctx->buffer, "{\\an7}{\\pos(%d,%d)}", x, y);
463
464             for (; j < SCREEN_COLUMNS; j++) {
465                 const char *e_tag = "", *s_tag = "", *c_tag = "";
466
467                 if (row[j] == 0)
468                     break;
469
470                 if (prev_font != font[j]) {
471                     switch (prev_font) {
472                     case CCFONT_ITALICS:
473                         e_tag = "{\\i0}";
474                         break;
475                     case CCFONT_UNDERLINED:
476                         e_tag = "{\\u0}";
477                         break;
478                     case CCFONT_UNDERLINED_ITALICS:
479                         e_tag = "{\\u0}{\\i0}";
480                         break;
481                     }
482                     switch (font[j]) {
483                     case CCFONT_ITALICS:
484                         s_tag = "{\\i1}";
485                         break;
486                     case CCFONT_UNDERLINED:
487                         s_tag = "{\\u1}";
488                         break;
489                     case CCFONT_UNDERLINED_ITALICS:
490                         s_tag = "{\\u1}{\\i1}";
491                         break;
492                     }
493                 }
494                 if (prev_color != color[j]) {
495                     switch (color[j]) {
496                     case CCCOL_WHITE:
497                         c_tag = "{\\c&HFFFFFF&}";
498                         break;
499                     case CCCOL_GREEN:
500                         c_tag = "{\\c&H00FF00&}";
501                         break;
502                     case CCCOL_BLUE:
503                         c_tag = "{\\c&HFF0000&}";
504                         break;
505                     case CCCOL_CYAN:
506                         c_tag = "{\\c&HFFFF00&}";
507                         break;
508                     case CCCOL_RED:
509                         c_tag = "{\\c&H0000FF&}";
510                         break;
511                     case CCCOL_YELLOW:
512                         c_tag = "{\\c&H00FFFF&}";
513                         break;
514                     case CCCOL_MAGENTA:
515                         c_tag = "{\\c&HFF00FF&}";
516                         break;
517                     }
518                 }
519
520                 prev_font = font[j];
521                 prev_color = color[j];
522                 override = charset_overrides[(int)charset[j]][(int)row[j]];
523                 if (override) {
524                     av_bprintf(&ctx->buffer, "%s%s%s%s", e_tag, s_tag, c_tag, override);
525                     seen_char = 1;
526                 } else if (row[j] == ' ' && !seen_char) {
527                     av_bprintf(&ctx->buffer, "%s%s%s\\h", e_tag, s_tag, c_tag);
528                 } else {
529                     av_bprintf(&ctx->buffer, "%s%s%s%c", e_tag, s_tag, c_tag, row[j]);
530                     seen_char = 1;
531                 }
532
533             }
534             av_bprintf(&ctx->buffer, "\\N");
535         }
536     }
537     if (!av_bprint_is_complete(&ctx->buffer))
538         return AVERROR(ENOMEM);
539     if (screen->row_used && ctx->buffer.len >= 2) {
540         ctx->buffer.len -= 2;
541         ctx->buffer.str[ctx->buffer.len] = 0;
542     }
543     ctx->buffer_changed = 1;
544     return 0;
545 }
546
547 static int reap_screen(CCaptionSubContext *ctx, int64_t pts)
548 {
549     ctx->start_time = ctx->startv_time;
550     ctx->startv_time = pts;
551     ctx->end_time = pts;
552     return capture_screen(ctx);
553 }
554
555 static void handle_textattr(CCaptionSubContext *ctx, uint8_t hi, uint8_t lo)
556 {
557     int i = lo - 0x20;
558     struct Screen *screen = get_writing_screen(ctx);
559
560     if (i >= 32)
561         return;
562
563     ctx->cursor_color = pac2_attribs[i][0];
564     ctx->cursor_font = pac2_attribs[i][1];
565
566     SET_FLAG(screen->row_used, ctx->cursor_row);
567     write_char(ctx, screen, ' ');
568 }
569
570 static void handle_pac(CCaptionSubContext *ctx, uint8_t hi, uint8_t lo)
571 {
572     static const int8_t row_map[] = {
573         11, -1, 1, 2, 3, 4, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10
574     };
575     const int index = ( (hi<<1) & 0x0e) | ( (lo>>5) & 0x01 );
576     struct Screen *screen = get_writing_screen(ctx);
577     int indent, i;
578
579     if (row_map[index] <= 0) {
580         av_log(ctx, AV_LOG_DEBUG, "Invalid pac index encountered\n");
581         return;
582     }
583
584     lo &= 0x1f;
585
586     ctx->cursor_row = row_map[index] - 1;
587     ctx->cursor_color =  pac2_attribs[lo][0];
588     ctx->cursor_font = pac2_attribs[lo][1];
589     ctx->cursor_charset = CCSET_BASIC_AMERICAN;
590     ctx->cursor_column = 0;
591     indent = pac2_attribs[lo][2];
592     for (i = 0; i < indent; i++) {
593         write_char(ctx, screen, ' ');
594     }
595 }
596
597 /**
598  * @param pts it is required to set end time
599  */
600 static int handle_edm(CCaptionSubContext *ctx, int64_t pts)
601 {
602     struct Screen *screen = ctx->screen + ctx->active_screen;
603     int ret;
604
605     // In buffered mode, keep writing to screen until it is wiped.
606     // Before wiping the display, capture contents to emit subtitle.
607     if (!ctx->real_time)
608         ret = reap_screen(ctx, pts);
609
610     screen->row_used = 0;
611
612     // In realtime mode, emit an empty caption so the last one doesn't
613     // stay on the screen.
614     if (ctx->real_time)
615         ret = reap_screen(ctx, pts);
616
617     return ret;
618 }
619
620 static int handle_eoc(CCaptionSubContext *ctx, int64_t pts)
621 {
622     int ret;
623
624     ctx->active_screen = !ctx->active_screen;
625
626     // In buffered mode, we wait til the *next* EOC and
627     // reap what was already on the screen since the last EOC.
628     if (!ctx->real_time)
629         ret = handle_edm(ctx, pts);
630
631     ctx->cursor_column = 0;
632
633     // In realtime mode, we display the buffered contents (after
634     // flipping the buffer to active above) as soon as EOC arrives.
635     if (ctx->real_time)
636         ret = reap_screen(ctx, pts);
637
638     return ret;
639 }
640
641 static void handle_delete_end_of_row(CCaptionSubContext *ctx)
642 {
643     struct Screen *screen = get_writing_screen(ctx);
644     write_char(ctx, screen, 0);
645 }
646
647 static void handle_char(CCaptionSubContext *ctx, char hi, char lo)
648 {
649     struct Screen *screen = get_writing_screen(ctx);
650
651     SET_FLAG(screen->row_used, ctx->cursor_row);
652
653     switch (hi) {
654       case 0x11:
655         ctx->cursor_charset = CCSET_SPECIAL_AMERICAN;
656         break;
657       case 0x12:
658         if (ctx->cursor_column > 0)
659             ctx->cursor_column -= 1;
660         ctx->cursor_charset = CCSET_EXTENDED_SPANISH_FRENCH_MISC;
661         break;
662       case 0x13:
663         if (ctx->cursor_column > 0)
664             ctx->cursor_column -= 1;
665         ctx->cursor_charset = CCSET_EXTENDED_PORTUGUESE_GERMAN_DANISH;
666         break;
667       default:
668         ctx->cursor_charset = CCSET_BASIC_AMERICAN;
669         write_char(ctx, screen, hi);
670         break;
671     }
672
673     if (lo) {
674         write_char(ctx, screen, lo);
675     }
676     write_char(ctx, screen, 0);
677
678     if (ctx->mode != CCMODE_POPON)
679         ctx->screen_touched = 1;
680
681     if (lo)
682        ff_dlog(ctx, "(%c,%c)\n", hi, lo);
683     else
684        ff_dlog(ctx, "(%c)\n", hi);
685 }
686
687 static int process_cc608(CCaptionSubContext *ctx, int64_t pts, uint8_t hi, uint8_t lo)
688 {
689     int ret = 0;
690
691     if (hi == ctx->prev_cmd[0] && lo == ctx->prev_cmd[1]) {
692         return 0;
693     }
694
695     /* set prev command */
696     ctx->prev_cmd[0] = hi;
697     ctx->prev_cmd[1] = lo;
698
699     if ( (hi == 0x10 && (lo >= 0x40 && lo <= 0x5f)) ||
700        ( (hi >= 0x11 && hi <= 0x17) && (lo >= 0x40 && lo <= 0x7f) ) ) {
701         handle_pac(ctx, hi, lo);
702     } else if ( ( hi == 0x11 && lo >= 0x20 && lo <= 0x2f ) ||
703                 ( hi == 0x17 && lo >= 0x2e && lo <= 0x2f) ) {
704         handle_textattr(ctx, hi, lo);
705     } else if (hi == 0x14 || hi == 0x15 || hi == 0x1c) {
706         switch (lo) {
707         case 0x20:
708             /* resume caption loading */
709             ctx->mode = CCMODE_POPON;
710             break;
711         case 0x24:
712             handle_delete_end_of_row(ctx);
713             break;
714         case 0x25:
715         case 0x26:
716         case 0x27:
717             ctx->rollup = lo - 0x23;
718             ctx->mode = CCMODE_ROLLUP;
719             break;
720         case 0x29:
721             /* resume direct captioning */
722             ctx->mode = CCMODE_PAINTON;
723             break;
724         case 0x2b:
725             /* resume text display */
726             ctx->mode = CCMODE_TEXT;
727             break;
728         case 0x2c:
729             /* erase display memory */
730             handle_edm(ctx, pts);
731             break;
732         case 0x2d:
733             /* carriage return */
734             ff_dlog(ctx, "carriage return\n");
735             if (!ctx->real_time)
736                 ret = reap_screen(ctx, pts);
737             roll_up(ctx);
738             ctx->cursor_column = 0;
739             break;
740         case 0x2e:
741             /* erase buffered (non displayed) memory */
742             // Only in realtime mode. In buffered mode, we re-use the inactive screen
743             // for our own buffering.
744             if (ctx->real_time) {
745                 struct Screen *screen = ctx->screen + !ctx->active_screen;
746                 screen->row_used = 0;
747             }
748             break;
749         case 0x2f:
750             /* end of caption */
751             ff_dlog(ctx, "handle_eoc\n");
752             ret = handle_eoc(ctx, pts);
753             break;
754         default:
755             ff_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
756             break;
757         }
758     } else if (hi >= 0x11 && hi <= 0x13) {
759         /* Special characters */
760         handle_char(ctx, hi, lo);
761     } else if (hi >= 0x20) {
762         /* Standard characters (always in pairs) */
763         handle_char(ctx, hi, lo);
764         ctx->prev_cmd[0] = ctx->prev_cmd[1] = 0;
765     } else if (hi == 0x17 && lo >= 0x21 && lo <= 0x23) {
766         int i;
767         /* Tab offsets (spacing) */
768         for (i = 0; i < lo - 0x20; i++) {
769             handle_char(ctx, ' ', 0);
770         }
771     } else {
772         /* Ignoring all other non data code */
773         ff_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
774     }
775
776     return ret;
777 }
778
779 static int decode(AVCodecContext *avctx, void *data, int *got_sub, AVPacket *avpkt)
780 {
781     CCaptionSubContext *ctx = avctx->priv_data;
782     AVSubtitle *sub = data;
783     const int64_t start_time = sub->pts;
784     uint8_t *bptr = NULL;
785     int len = avpkt->size;
786     int ret = 0;
787     int i;
788
789     bptr = avpkt->data;
790
791     for (i = 0; i < len; i += 3) {
792         uint8_t cc_type = *(bptr + i) & 3;
793         if (validate_cc_data_pair(bptr + i))
794             continue;
795         /* ignoring data field 1 */
796         if (cc_type == 1)
797             continue;
798
799         ret = process_cc608(ctx, start_time, bptr[i + 1] & 0x7f, bptr[i + 2] & 0x7f);
800         if (ret < 0)
801             return ret;
802
803         if (!ctx->buffer_changed)
804             continue;
805         ctx->buffer_changed = 0;
806
807         if (ctx->buffer.str[0] || ctx->real_time) {
808             ff_dlog(ctx, "cdp writing data (%s)\n", ctx->buffer.str);
809             ret = ff_ass_add_rect(sub, ctx->buffer.str, ctx->readorder++, 0, NULL, NULL);
810             if (ret < 0)
811                 return ret;
812             sub->pts = ctx->start_time;
813             if (!ctx->real_time)
814                 sub->end_display_time = av_rescale_q(ctx->end_time - ctx->start_time,
815                                                      AV_TIME_BASE_Q, ms_tb);
816             else
817                 sub->end_display_time = -1;
818             ctx->buffer_changed = 0;
819             ctx->last_real_time = sub->pts;
820             ctx->screen_touched = 0;
821         }
822     }
823
824     if (ctx->real_time && ctx->screen_touched &&
825         sub->pts > ctx->last_real_time + av_rescale_q(200, ms_tb, AV_TIME_BASE_Q)) {
826         ctx->last_real_time = sub->pts;
827         ctx->screen_touched = 0;
828
829         capture_screen(ctx);
830         ctx->buffer_changed = 0;
831
832         ret = ff_ass_add_rect(sub, ctx->buffer.str, ctx->readorder++, 0, NULL, NULL);
833         if (ret < 0)
834             return ret;
835         sub->end_display_time = -1;
836     }
837
838     *got_sub = sub->num_rects > 0;
839     return ret;
840 }
841
842 #define OFFSET(x) offsetof(CCaptionSubContext, x)
843 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
844 static const AVOption options[] = {
845     { "real_time", "emit subtitle events as they are decoded for real-time display", OFFSET(real_time), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, SD },
846     {NULL}
847 };
848
849 static const AVClass ccaption_dec_class = {
850     .class_name = "Closed caption Decoder",
851     .item_name  = av_default_item_name,
852     .option     = options,
853     .version    = LIBAVUTIL_VERSION_INT,
854 };
855
856 AVCodec ff_ccaption_decoder = {
857     .name           = "cc_dec",
858     .long_name      = NULL_IF_CONFIG_SMALL("Closed Caption (EIA-608 / CEA-708)"),
859     .type           = AVMEDIA_TYPE_SUBTITLE,
860     .id             = AV_CODEC_ID_EIA_608,
861     .priv_data_size = sizeof(CCaptionSubContext),
862     .init           = init_decoder,
863     .close          = close_decoder,
864     .flush          = flush_decoder,
865     .decode         = decode,
866     .priv_class     = &ccaption_dec_class,
867 };