]> git.sesse.net Git - ffmpeg/blob - libavcodec/ccaption_dec.c
avcodec/ccaption_dec: remove pts parameter from handle_char()
[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     /* buffer to store pkt data */
246     uint8_t *pktbuf;
247     int pktbuf_size;
248     int readorder;
249 } CCaptionSubContext;
250
251
252 static av_cold int init_decoder(AVCodecContext *avctx)
253 {
254     int ret;
255     CCaptionSubContext *ctx = avctx->priv_data;
256
257     av_bprint_init(&ctx->buffer, 0, AV_BPRINT_SIZE_UNLIMITED);
258     /* taking by default roll up to 2 */
259     ctx->mode = CCMODE_ROLLUP;
260     ctx->rollup = 2;
261     ctx->cursor_row = 10;
262     ret = ff_ass_subtitle_header(avctx, "Monospace",
263                                  ASS_DEFAULT_FONT_SIZE,
264                                  ASS_DEFAULT_COLOR,
265                                  ASS_DEFAULT_BACK_COLOR,
266                                  ASS_DEFAULT_BOLD,
267                                  ASS_DEFAULT_ITALIC,
268                                  ASS_DEFAULT_UNDERLINE,
269                                  3,
270                                  ASS_DEFAULT_ALIGNMENT);
271     if (ret < 0) {
272         return ret;
273     }
274
275     return ret;
276 }
277
278 static av_cold int close_decoder(AVCodecContext *avctx)
279 {
280     CCaptionSubContext *ctx = avctx->priv_data;
281     av_bprint_finalize(&ctx->buffer, NULL);
282     av_freep(&ctx->pktbuf);
283     ctx->pktbuf_size = 0;
284     return 0;
285 }
286
287 static void flush_decoder(AVCodecContext *avctx)
288 {
289     CCaptionSubContext *ctx = avctx->priv_data;
290     ctx->screen[0].row_used = 0;
291     ctx->screen[1].row_used = 0;
292     ctx->prev_cmd[0] = 0;
293     ctx->prev_cmd[1] = 0;
294     ctx->mode = CCMODE_ROLLUP;
295     ctx->rollup = 2;
296     ctx->cursor_row = 10;
297     ctx->cursor_column = 0;
298     ctx->cursor_font = 0;
299     ctx->cursor_color = 0;
300     ctx->cursor_charset = 0;
301     ctx->active_screen = 0;
302     ctx->last_real_time = 0;
303     ctx->screen_touched = 0;
304     ctx->buffer_changed = 0;
305     if (!(avctx->flags2 & AV_CODEC_FLAG2_RO_FLUSH_NOOP))
306         ctx->readorder = 0;
307     av_bprint_clear(&ctx->buffer);
308 }
309
310 /**
311  * @param ctx closed caption context just to print log
312  */
313 static void write_char(CCaptionSubContext *ctx, struct Screen *screen, char ch)
314 {
315     uint8_t col = ctx->cursor_column;
316     char *row = screen->characters[ctx->cursor_row];
317     char *font = screen->fonts[ctx->cursor_row];
318     char *color = screen->colors[ctx->cursor_row];
319     char *charset = screen->charsets[ctx->cursor_row];
320
321     if (col < SCREEN_COLUMNS) {
322         row[col] = ch;
323         font[col] = ctx->cursor_font;
324         color[col] = ctx->cursor_color;
325         charset[col] = ctx->cursor_charset;
326         ctx->cursor_charset = CCSET_BASIC_AMERICAN;
327         if (ch) ctx->cursor_column++;
328         return;
329     }
330     /* We have extra space at end only for null character */
331     else if (col == SCREEN_COLUMNS && ch == 0) {
332         row[col] = ch;
333         return;
334     }
335     else {
336         av_log(ctx, AV_LOG_WARNING, "Data Ignored since exceeding screen width\n");
337         return;
338     }
339 }
340
341 /**
342  * This function after validating parity bit, also remove it from data pair.
343  * The first byte doesn't pass parity, we replace it with a solid blank
344  * and process the pair.
345  * If the second byte doesn't pass parity, it returns INVALIDDATA
346  * user can ignore the whole pair and pass the other pair.
347  */
348 static int validate_cc_data_pair(uint8_t *cc_data_pair)
349 {
350     uint8_t cc_valid = (*cc_data_pair & 4) >>2;
351     uint8_t cc_type = *cc_data_pair & 3;
352
353     if (!cc_valid)
354         return AVERROR_INVALIDDATA;
355
356     // if EIA-608 data then verify parity.
357     if (cc_type==0 || cc_type==1) {
358         if (!av_parity(cc_data_pair[2])) {
359             return AVERROR_INVALIDDATA;
360         }
361         if (!av_parity(cc_data_pair[1])) {
362             cc_data_pair[1]=0x7F;
363         }
364     }
365
366     //Skip non-data
367     if ((cc_data_pair[0] == 0xFA || cc_data_pair[0] == 0xFC || cc_data_pair[0] == 0xFD)
368          && (cc_data_pair[1] & 0x7F) == 0 && (cc_data_pair[2] & 0x7F) == 0)
369         return AVERROR_PATCHWELCOME;
370
371     //skip 708 data
372     if (cc_type == 3 || cc_type == 2)
373         return AVERROR_PATCHWELCOME;
374
375     /* remove parity bit */
376     cc_data_pair[1] &= 0x7F;
377     cc_data_pair[2] &= 0x7F;
378
379     return 0;
380 }
381
382 static struct Screen *get_writing_screen(CCaptionSubContext *ctx)
383 {
384     switch (ctx->mode) {
385     case CCMODE_POPON:
386         // use Inactive screen
387         return ctx->screen + !ctx->active_screen;
388     case CCMODE_PAINTON:
389     case CCMODE_ROLLUP:
390     case CCMODE_TEXT:
391         // use active screen
392         return ctx->screen + ctx->active_screen;
393     }
394     /* It was never an option */
395     return NULL;
396 }
397
398 static void roll_up(CCaptionSubContext *ctx)
399 {
400     struct Screen *screen;
401     int i, keep_lines;
402
403     if (ctx->mode == CCMODE_TEXT)
404         return;
405
406     screen = get_writing_screen(ctx);
407
408     /* +1 signify cursor_row starts from 0
409      * Can't keep lines less then row cursor pos
410      */
411     keep_lines = FFMIN(ctx->cursor_row + 1, ctx->rollup);
412
413     for (i = 0; i < SCREEN_ROWS; i++) {
414         if (i > ctx->cursor_row - keep_lines && i <= ctx->cursor_row)
415             continue;
416         UNSET_FLAG(screen->row_used, i);
417     }
418
419     for (i = 0; i < keep_lines && screen->row_used; i++) {
420         const int i_row = ctx->cursor_row - keep_lines + i + 1;
421
422         memcpy(screen->characters[i_row], screen->characters[i_row+1], SCREEN_COLUMNS);
423         memcpy(screen->colors[i_row], screen->colors[i_row+1], SCREEN_COLUMNS);
424         memcpy(screen->fonts[i_row], screen->fonts[i_row+1], SCREEN_COLUMNS);
425         memcpy(screen->charsets[i_row], screen->charsets[i_row+1], SCREEN_COLUMNS);
426         if (CHECK_FLAG(screen->row_used, i_row + 1))
427             SET_FLAG(screen->row_used, i_row);
428     }
429
430     UNSET_FLAG(screen->row_used, ctx->cursor_row);
431 }
432
433 static int capture_screen(CCaptionSubContext *ctx)
434 {
435     int i, j, tab = 0;
436     struct Screen *screen = ctx->screen + ctx->active_screen;
437     enum cc_font prev_font = CCFONT_REGULAR;
438     enum cc_color_code prev_color = CCCOL_WHITE;
439     av_bprint_clear(&ctx->buffer);
440
441     for (i = 0; screen->row_used && i < SCREEN_ROWS; i++)
442     {
443         if (CHECK_FLAG(screen->row_used, i)) {
444             const char *row = screen->characters[i];
445             const char *charset = screen->charsets[i];
446             j = 0;
447             while (row[j] == ' ' && charset[j] == CCSET_BASIC_AMERICAN)
448                 j++;
449             if (!tab || j < tab)
450                 tab = j;
451         }
452     }
453
454     for (i = 0; screen->row_used && i < SCREEN_ROWS; i++)
455     {
456         if (CHECK_FLAG(screen->row_used, i)) {
457             const char *row = screen->characters[i];
458             const char *font = screen->fonts[i];
459             const char *color = screen->colors[i];
460             const char *charset = screen->charsets[i];
461             const char *override;
462             int x, y, seen_char = 0;
463             j = 0;
464
465             /* skip leading space */
466             while (row[j] == ' ' && charset[j] == CCSET_BASIC_AMERICAN && j < tab)
467                 j++;
468
469             x = ASS_DEFAULT_PLAYRESX * (0.1 + 0.0250 * j);
470             y = ASS_DEFAULT_PLAYRESY * (0.1 + 0.0533 * i);
471             av_bprintf(&ctx->buffer, "{\\an7}{\\pos(%d,%d)}", x, y);
472
473             for (; j < SCREEN_COLUMNS; j++) {
474                 const char *e_tag = "", *s_tag = "", *c_tag = "";
475
476                 if (row[j] == 0)
477                     break;
478
479                 if (prev_font != font[j]) {
480                     switch (prev_font) {
481                     case CCFONT_ITALICS:
482                         e_tag = "{\\i0}";
483                         break;
484                     case CCFONT_UNDERLINED:
485                         e_tag = "{\\u0}";
486                         break;
487                     case CCFONT_UNDERLINED_ITALICS:
488                         e_tag = "{\\u0}{\\i0}";
489                         break;
490                     }
491                     switch (font[j]) {
492                     case CCFONT_ITALICS:
493                         s_tag = "{\\i1}";
494                         break;
495                     case CCFONT_UNDERLINED:
496                         s_tag = "{\\u1}";
497                         break;
498                     case CCFONT_UNDERLINED_ITALICS:
499                         s_tag = "{\\u1}{\\i1}";
500                         break;
501                     }
502                 }
503                 if (prev_color != color[j]) {
504                     switch (color[j]) {
505                     case CCCOL_WHITE:
506                         c_tag = "{\\c&HFFFFFF&}";
507                         break;
508                     case CCCOL_GREEN:
509                         c_tag = "{\\c&H00FF00&}";
510                         break;
511                     case CCCOL_BLUE:
512                         c_tag = "{\\c&HFF0000&}";
513                         break;
514                     case CCCOL_CYAN:
515                         c_tag = "{\\c&HFFFF00&}";
516                         break;
517                     case CCCOL_RED:
518                         c_tag = "{\\c&H0000FF&}";
519                         break;
520                     case CCCOL_YELLOW:
521                         c_tag = "{\\c&H00FFFF&}";
522                         break;
523                     case CCCOL_MAGENTA:
524                         c_tag = "{\\c&HFF00FF&}";
525                         break;
526                     }
527                 }
528
529                 prev_font = font[j];
530                 prev_color = color[j];
531                 override = charset_overrides[(int)charset[j]][(int)row[j]];
532                 if (override) {
533                     av_bprintf(&ctx->buffer, "%s%s%s%s", e_tag, s_tag, c_tag, override);
534                     seen_char = 1;
535                 } else if (row[j] == ' ' && !seen_char) {
536                     av_bprintf(&ctx->buffer, "%s%s%s\\h", e_tag, s_tag, c_tag);
537                 } else {
538                     av_bprintf(&ctx->buffer, "%s%s%s%c", e_tag, s_tag, c_tag, row[j]);
539                     seen_char = 1;
540                 }
541
542             }
543             av_bprintf(&ctx->buffer, "\\N");
544         }
545     }
546     if (!av_bprint_is_complete(&ctx->buffer))
547         return AVERROR(ENOMEM);
548     if (screen->row_used && ctx->buffer.len >= 2) {
549         ctx->buffer.len -= 2;
550         ctx->buffer.str[ctx->buffer.len] = 0;
551     }
552     ctx->buffer_changed = 1;
553     return 0;
554 }
555
556 static int reap_screen(CCaptionSubContext *ctx, int64_t pts)
557 {
558     ctx->start_time = ctx->startv_time;
559     ctx->startv_time = pts;
560     ctx->end_time = pts;
561     return capture_screen(ctx);
562 }
563
564 static void handle_textattr(CCaptionSubContext *ctx, uint8_t hi, uint8_t lo)
565 {
566     int i = lo - 0x20;
567     struct Screen *screen = get_writing_screen(ctx);
568
569     if (i >= 32)
570         return;
571
572     ctx->cursor_color = pac2_attribs[i][0];
573     ctx->cursor_font = pac2_attribs[i][1];
574
575     SET_FLAG(screen->row_used, ctx->cursor_row);
576     write_char(ctx, screen, ' ');
577 }
578
579 static void handle_pac(CCaptionSubContext *ctx, uint8_t hi, uint8_t lo)
580 {
581     static const int8_t row_map[] = {
582         11, -1, 1, 2, 3, 4, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10
583     };
584     const int index = ( (hi<<1) & 0x0e) | ( (lo>>5) & 0x01 );
585     struct Screen *screen = get_writing_screen(ctx);
586     int indent, i;
587
588     if (row_map[index] <= 0) {
589         av_log(ctx, AV_LOG_DEBUG, "Invalid pac index encountered\n");
590         return;
591     }
592
593     lo &= 0x1f;
594
595     ctx->cursor_row = row_map[index] - 1;
596     ctx->cursor_color =  pac2_attribs[lo][0];
597     ctx->cursor_font = pac2_attribs[lo][1];
598     ctx->cursor_charset = CCSET_BASIC_AMERICAN;
599     ctx->cursor_column = 0;
600     indent = pac2_attribs[lo][2];
601     for (i = 0; i < indent; i++) {
602         write_char(ctx, screen, ' ');
603     }
604 }
605
606 /**
607  * @param pts it is required to set end time
608  */
609 static int handle_edm(CCaptionSubContext *ctx, int64_t pts)
610 {
611     struct Screen *screen = ctx->screen + ctx->active_screen;
612     int ret;
613
614     // In buffered mode, keep writing to screen until it is wiped.
615     // Before wiping the display, capture contents to emit subtitle.
616     if (!ctx->real_time)
617         ret = reap_screen(ctx, pts);
618
619     screen->row_used = 0;
620
621     // In realtime mode, emit an empty caption so the last one doesn't
622     // stay on the screen.
623     if (ctx->real_time)
624         ret = reap_screen(ctx, pts);
625
626     return ret;
627 }
628
629 static int handle_eoc(CCaptionSubContext *ctx, int64_t pts)
630 {
631     int ret;
632
633     ctx->active_screen = !ctx->active_screen;
634
635     // In buffered mode, we wait til the *next* EOC and
636     // reap what was already on the screen since the last EOC.
637     if (!ctx->real_time)
638         ret = handle_edm(ctx,pts);
639
640     ctx->cursor_column = 0;
641
642     // In realtime mode, we display the buffered contents (after
643     // flipping the buffer to active above) as soon as EOC arrives.
644     if (ctx->real_time)
645         ret = reap_screen(ctx, pts);
646
647     return ret;
648 }
649
650 static void handle_delete_end_of_row(CCaptionSubContext *ctx)
651 {
652     struct Screen *screen = get_writing_screen(ctx);
653     write_char(ctx, screen, 0);
654 }
655
656 static void handle_char(CCaptionSubContext *ctx, char hi, char lo)
657 {
658     struct Screen *screen = get_writing_screen(ctx);
659
660     SET_FLAG(screen->row_used, ctx->cursor_row);
661
662     switch (hi) {
663       case 0x11:
664         ctx->cursor_charset = CCSET_SPECIAL_AMERICAN;
665         break;
666       case 0x12:
667         if (ctx->cursor_column > 0)
668             ctx->cursor_column -= 1;
669         ctx->cursor_charset = CCSET_EXTENDED_SPANISH_FRENCH_MISC;
670         break;
671       case 0x13:
672         if (ctx->cursor_column > 0)
673             ctx->cursor_column -= 1;
674         ctx->cursor_charset = CCSET_EXTENDED_PORTUGUESE_GERMAN_DANISH;
675         break;
676       default:
677         ctx->cursor_charset = CCSET_BASIC_AMERICAN;
678         write_char(ctx, screen, hi);
679         break;
680     }
681
682     if (lo) {
683         write_char(ctx, screen, lo);
684     }
685     write_char(ctx, screen, 0);
686
687     if (ctx->mode != CCMODE_POPON)
688         ctx->screen_touched = 1;
689
690     if (lo)
691        ff_dlog(ctx, "(%c,%c)\n", hi, lo);
692     else
693        ff_dlog(ctx, "(%c)\n", hi);
694 }
695
696 static int process_cc608(CCaptionSubContext *ctx, int64_t pts, uint8_t hi, uint8_t lo)
697 {
698     int ret = 0;
699
700     if (hi == ctx->prev_cmd[0] && lo == ctx->prev_cmd[1]) {
701         return 0;
702     }
703
704     /* set prev command */
705     ctx->prev_cmd[0] = hi;
706     ctx->prev_cmd[1] = lo;
707
708     if ( (hi == 0x10 && (lo >= 0x40 && lo <= 0x5f)) ||
709        ( (hi >= 0x11 && hi <= 0x17) && (lo >= 0x40 && lo <= 0x7f) ) ) {
710         handle_pac(ctx, hi, lo);
711     } else if ( ( hi == 0x11 && lo >= 0x20 && lo <= 0x2f ) ||
712                 ( hi == 0x17 && lo >= 0x2e && lo <= 0x2f) ) {
713         handle_textattr(ctx, hi, lo);
714     } else if (hi == 0x14 || hi == 0x15 || hi == 0x1c) {
715         switch (lo) {
716         case 0x20:
717             /* resume caption loading */
718             ctx->mode = CCMODE_POPON;
719             break;
720         case 0x24:
721             handle_delete_end_of_row(ctx);
722             break;
723         case 0x25:
724         case 0x26:
725         case 0x27:
726             ctx->rollup = lo - 0x23;
727             ctx->mode = CCMODE_ROLLUP;
728             break;
729         case 0x29:
730             /* resume direct captioning */
731             ctx->mode = CCMODE_PAINTON;
732             break;
733         case 0x2b:
734             /* resume text display */
735             ctx->mode = CCMODE_TEXT;
736             break;
737         case 0x2c:
738             /* erase display memory */
739             handle_edm(ctx, pts);
740             break;
741         case 0x2d:
742             /* carriage return */
743             ff_dlog(ctx, "carriage return\n");
744             if (!ctx->real_time)
745                 ret = reap_screen(ctx, pts);
746             roll_up(ctx);
747             ctx->cursor_column = 0;
748             break;
749         case 0x2e:
750             /* erase buffered (non displayed) memory */
751             // Only in realtime mode. In buffered mode, we re-use the inactive screen
752             // for our own buffering.
753             if (ctx->real_time) {
754                 struct Screen *screen = ctx->screen + !ctx->active_screen;
755                 screen->row_used = 0;
756             }
757             break;
758         case 0x2f:
759             /* end of caption */
760             ff_dlog(ctx, "handle_eoc\n");
761             ret = handle_eoc(ctx, pts);
762             break;
763         default:
764             ff_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
765             break;
766         }
767     } else if (hi >= 0x11 && hi <= 0x13) {
768         /* Special characters */
769         handle_char(ctx, hi, lo);
770     } else if (hi >= 0x20) {
771         /* Standard characters (always in pairs) */
772         handle_char(ctx, hi, lo);
773         ctx->prev_cmd[0] = ctx->prev_cmd[1] = 0;
774     } else if (hi == 0x17 && lo >= 0x21 && lo <= 0x23) {
775         int i;
776         /* Tab offsets (spacing) */
777         for (i = 0; i < lo - 0x20; i++) {
778             handle_char(ctx, ' ', 0);
779         }
780     } else {
781         /* Ignoring all other non data code */
782         ff_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
783     }
784
785     return ret;
786 }
787
788 static int decode(AVCodecContext *avctx, void *data, int *got_sub, AVPacket *avpkt)
789 {
790     CCaptionSubContext *ctx = avctx->priv_data;
791     AVSubtitle *sub = data;
792     const int64_t start_time = sub->pts;
793     uint8_t *bptr = NULL;
794     int len = avpkt->size;
795     int ret = 0;
796     int i;
797
798     av_fast_padded_malloc(&ctx->pktbuf, &ctx->pktbuf_size, len);
799     if (!ctx->pktbuf) {
800         av_log(ctx, AV_LOG_WARNING, "Insufficient Memory of %d truncated to %d\n", len, ctx->pktbuf_size);
801         return AVERROR(ENOMEM);
802     }
803     memcpy(ctx->pktbuf, avpkt->data, len);
804     bptr = ctx->pktbuf;
805
806     for (i  = 0; i < len; i += 3) {
807         uint8_t cc_type = *(bptr + i) & 3;
808         if (validate_cc_data_pair(bptr + i))
809             continue;
810         /* ignoring data field 1 */
811         if(cc_type == 1)
812             continue;
813         else
814             ret = process_cc608(ctx, start_time, *(bptr + i + 1) & 0x7f, *(bptr + i + 2) & 0x7f);
815
816         if (ret < 0)
817             return ret;
818
819         if (!ctx->buffer_changed)
820             continue;
821         ctx->buffer_changed = 0;
822
823         if (*ctx->buffer.str || ctx->real_time)
824         {
825             ff_dlog(ctx, "cdp writing data (%s)\n",ctx->buffer.str);
826             ret = ff_ass_add_rect(sub, ctx->buffer.str, ctx->readorder++, 0, NULL, NULL);
827             if (ret < 0)
828                 return ret;
829             sub->pts = ctx->start_time;
830             if (!ctx->real_time)
831                 sub->end_display_time = av_rescale_q(ctx->end_time - ctx->start_time,
832                                                      AV_TIME_BASE_Q, ms_tb);
833             else
834                 sub->end_display_time = -1;
835             ctx->buffer_changed = 0;
836             ctx->last_real_time = sub->pts;
837             ctx->screen_touched = 0;
838         }
839     }
840
841     if (ctx->real_time && ctx->screen_touched &&
842         sub->pts > ctx->last_real_time + av_rescale_q(200, ms_tb, AV_TIME_BASE_Q)) {
843         ctx->last_real_time = sub->pts;
844         ctx->screen_touched = 0;
845
846         capture_screen(ctx);
847         ctx->buffer_changed = 0;
848
849         ret = ff_ass_add_rect(sub, ctx->buffer.str, ctx->readorder++, 0, NULL, NULL);
850         if (ret < 0)
851             return ret;
852         sub->end_display_time = -1;
853     }
854
855     *got_sub = sub->num_rects > 0;
856     return ret;
857 }
858
859 #define OFFSET(x) offsetof(CCaptionSubContext, x)
860 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
861 static const AVOption options[] = {
862     { "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 },
863     {NULL}
864 };
865
866 static const AVClass ccaption_dec_class = {
867     .class_name = "Closed caption Decoder",
868     .item_name  = av_default_item_name,
869     .option     = options,
870     .version    = LIBAVUTIL_VERSION_INT,
871 };
872
873 AVCodec ff_ccaption_decoder = {
874     .name           = "cc_dec",
875     .long_name      = NULL_IF_CONFIG_SMALL("Closed Caption (EIA-608 / CEA-708)"),
876     .type           = AVMEDIA_TYPE_SUBTITLE,
877     .id             = AV_CODEC_ID_EIA_608,
878     .priv_data_size = sizeof(CCaptionSubContext),
879     .init           = init_decoder,
880     .close          = close_decoder,
881     .flush          = flush_decoder,
882     .decode         = decode,
883     .priv_class     = &ccaption_dec_class,
884 };