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