2 * Closed Caption Decoding
3 * Copyright (c) 2015 Anshul Maheshwari
5 * This file is part of FFmpeg.
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.
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.
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
24 #include "libavutil/opt.h"
26 #define SCREEN_ROWS 15
27 #define SCREEN_COLUMNS 32
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)) )
33 static const AVRational ms_tb = {1, 1000};
37 * 1) handle font and color completely
63 CCFONT_UNDERLINED_ITALICS,
68 CCSET_SPECIAL_AMERICAN,
69 CCSET_EXTENDED_SPANISH_FRENCH_MISC,
70 CCSET_EXTENDED_PORTUGUESE_GERMAN_DANISH,
73 static const char *charset_overrides[4][128] =
75 [CCSET_BASIC_AMERICAN] = {
88 [CCSET_SPECIAL_AMERICAN] = {
106 [CCSET_EXTENDED_SPANISH_FRENCH_MISC] = {
140 [CCSET_EXTENDED_PORTUGUESE_GERMAN_DANISH] = {
176 static const unsigned char pac2_attribs[32][3] = // Color, font, ident
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 */
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];
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)
228 typedef struct CCaptionSubContext {
231 struct Screen screen[2];
234 uint8_t cursor_column;
235 uint8_t cursor_color;
237 uint8_t cursor_charset;
243 /* visible screen time */
247 int64_t last_real_time;
249 /* buffer to store pkt data */
253 } CCaptionSubContext;
256 static av_cold int init_decoder(AVCodecContext *avctx)
259 CCaptionSubContext *ctx = avctx->priv_data;
261 av_bprint_init(&ctx->buffer, 0, AV_BPRINT_SIZE_UNLIMITED);
262 /* taking by default roll up to 2 */
263 ctx->mode = CCMODE_ROLLUP;
265 ctx->cursor_row = 10;
266 ret = ff_ass_subtitle_header(avctx, "Monospace",
267 ASS_DEFAULT_FONT_SIZE,
269 ASS_DEFAULT_BACK_COLOR,
272 ASS_DEFAULT_UNDERLINE,
274 ASS_DEFAULT_ALIGNMENT);
282 static av_cold int close_decoder(AVCodecContext *avctx)
284 CCaptionSubContext *ctx = avctx->priv_data;
285 av_bprint_finalize(&ctx->buffer, NULL);
286 av_freep(&ctx->pktbuf);
287 ctx->pktbuf_size = 0;
291 static void flush_decoder(AVCodecContext *avctx)
293 CCaptionSubContext *ctx = avctx->priv_data;
294 ctx->screen[0].row_used = 0;
295 ctx->screen[1].row_used = 0;
296 ctx->prev_cmd[0] = 0;
297 ctx->prev_cmd[1] = 0;
298 ctx->mode = CCMODE_ROLLUP;
300 ctx->cursor_row = 10;
301 ctx->cursor_column = 0;
302 ctx->cursor_font = 0;
303 ctx->cursor_color = 0;
304 ctx->cursor_charset = 0;
305 ctx->active_screen = 0;
306 ctx->last_real_time = 0;
307 ctx->screen_touched = 0;
308 ctx->buffer_changed = 0;
309 if (!(avctx->flags2 & AV_CODEC_FLAG2_RO_FLUSH_NOOP))
311 av_bprint_clear(&ctx->buffer);
315 * @param ctx closed caption context just to print log
317 static void write_char(CCaptionSubContext *ctx, struct Screen *screen, char ch)
319 uint8_t col = ctx->cursor_column;
320 char *row = screen->characters[ctx->cursor_row];
321 char *font = screen->fonts[ctx->cursor_row];
322 char *charset = screen->charsets[ctx->cursor_row];
324 if (col < SCREEN_COLUMNS) {
326 font[col] = ctx->cursor_font;
327 charset[col] = ctx->cursor_charset;
328 ctx->cursor_charset = CCSET_BASIC_AMERICAN;
329 if (ch) ctx->cursor_column++;
332 /* We have extra space at end only for null character */
333 else if (col == SCREEN_COLUMNS && ch == 0) {
338 av_log(ctx, AV_LOG_WARNING, "Data Ignored since exceeding screen width\n");
344 * This function after validating parity bit, also remove it from data pair.
345 * The first byte doesn't pass parity, we replace it with a solid blank
346 * and process the pair.
347 * If the second byte doesn't pass parity, it returns INVALIDDATA
348 * user can ignore the whole pair and pass the other pair.
350 static int validate_cc_data_pair(uint8_t *cc_data_pair)
352 uint8_t cc_valid = (*cc_data_pair & 4) >>2;
353 uint8_t cc_type = *cc_data_pair & 3;
356 return AVERROR_INVALIDDATA;
358 // if EIA-608 data then verify parity.
359 if (cc_type==0 || cc_type==1) {
360 if (!av_parity(cc_data_pair[2])) {
361 return AVERROR_INVALIDDATA;
363 if (!av_parity(cc_data_pair[1])) {
364 cc_data_pair[1]=0x7F;
369 if ((cc_data_pair[0] == 0xFA || cc_data_pair[0] == 0xFC || cc_data_pair[0] == 0xFD)
370 && (cc_data_pair[1] & 0x7F) == 0 && (cc_data_pair[2] & 0x7F) == 0)
371 return AVERROR_PATCHWELCOME;
374 if (cc_type == 3 || cc_type == 2)
375 return AVERROR_PATCHWELCOME;
377 /* remove parity bit */
378 cc_data_pair[1] &= 0x7F;
379 cc_data_pair[2] &= 0x7F;
384 static struct Screen *get_writing_screen(CCaptionSubContext *ctx)
388 // use Inactive screen
389 return ctx->screen + !ctx->active_screen;
394 return ctx->screen + ctx->active_screen;
396 /* It was never an option */
400 static void roll_up(CCaptionSubContext *ctx)
402 struct Screen *screen;
405 if (ctx->mode == CCMODE_TEXT)
408 screen = get_writing_screen(ctx);
410 /* +1 signify cursor_row starts from 0
411 * Can't keep lines less then row cursor pos
413 keep_lines = FFMIN(ctx->cursor_row + 1, ctx->rollup);
415 for (i = 0; i < SCREEN_ROWS; i++) {
416 if (i > ctx->cursor_row - keep_lines && i <= ctx->cursor_row)
418 UNSET_FLAG(screen->row_used, i);
421 for (i = 0; i < keep_lines && screen->row_used; i++) {
422 const int i_row = ctx->cursor_row - keep_lines + i + 1;
424 memcpy(screen->characters[i_row], screen->characters[i_row+1], SCREEN_COLUMNS);
425 memcpy(screen->colors[i_row], screen->colors[i_row+1], SCREEN_COLUMNS);
426 memcpy(screen->fonts[i_row], screen->fonts[i_row+1], SCREEN_COLUMNS);
427 memcpy(screen->charsets[i_row], screen->charsets[i_row+1], SCREEN_COLUMNS);
428 if (CHECK_FLAG(screen->row_used, i_row + 1))
429 SET_FLAG(screen->row_used, i_row);
432 UNSET_FLAG(screen->row_used, ctx->cursor_row);
435 static int capture_screen(CCaptionSubContext *ctx)
438 struct Screen *screen = ctx->screen + ctx->active_screen;
439 enum cc_font prev_font = CCFONT_REGULAR;
440 av_bprint_clear(&ctx->buffer);
442 for (i = 0; screen->row_used && i < SCREEN_ROWS; i++)
444 if (CHECK_FLAG(screen->row_used, i)) {
445 const char *row = screen->characters[i];
446 const char *charset = screen->charsets[i];
448 while (row[j] == ' ' && charset[j] == CCSET_BASIC_AMERICAN)
455 for (i = 0; screen->row_used && i < SCREEN_ROWS; i++)
457 if (CHECK_FLAG(screen->row_used, i)) {
458 const char *row = screen->characters[i];
459 const char *font = screen->fonts[i];
460 const char *charset = screen->charsets[i];
461 const char *override;
462 int x, y, seen_char = 0;
465 /* skip leading space */
466 while (row[j] == ' ' && charset[j] == CCSET_BASIC_AMERICAN && j < tab)
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);
473 for (; j < SCREEN_COLUMNS; j++) {
474 const char *e_tag = "", *s_tag = "";
479 if (prev_font != font[j]) {
484 case CCFONT_UNDERLINED:
487 case CCFONT_UNDERLINED_ITALICS:
488 e_tag = "{\\u0}{\\i0}";
495 case CCFONT_UNDERLINED:
498 case CCFONT_UNDERLINED_ITALICS:
499 s_tag = "{\\u1}{\\i1}";
504 override = charset_overrides[(int)charset[j]][(int)row[j]];
506 av_bprintf(&ctx->buffer, "%s%s%s", e_tag, s_tag, override);
508 } else if (row[j] == ' ' && !seen_char) {
509 av_bprintf(&ctx->buffer, "%s%s\\h", e_tag, s_tag);
511 av_bprintf(&ctx->buffer, "%s%s%c", e_tag, s_tag, row[j]);
516 av_bprintf(&ctx->buffer, "\\N");
519 if (!av_bprint_is_complete(&ctx->buffer))
520 return AVERROR(ENOMEM);
521 if (screen->row_used && ctx->buffer.len >= 2) {
522 ctx->buffer.len -= 2;
523 ctx->buffer.str[ctx->buffer.len] = 0;
525 ctx->buffer_changed = 1;
529 static int reap_screen(CCaptionSubContext *ctx, int64_t pts)
531 ctx->start_time = ctx->startv_time;
532 ctx->startv_time = pts;
534 return capture_screen(ctx);
537 static void handle_textattr(CCaptionSubContext *ctx, uint8_t hi, uint8_t lo)
540 struct Screen *screen = get_writing_screen(ctx);
545 ctx->cursor_color = pac2_attribs[i][0];
546 ctx->cursor_font = pac2_attribs[i][1];
548 SET_FLAG(screen->row_used, ctx->cursor_row);
549 write_char(ctx, screen, ' ');
552 static void handle_pac(CCaptionSubContext *ctx, uint8_t hi, uint8_t lo)
554 static const int8_t row_map[] = {
555 11, -1, 1, 2, 3, 4, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10
557 const int index = ( (hi<<1) & 0x0e) | ( (lo>>5) & 0x01 );
558 struct Screen *screen = get_writing_screen(ctx);
561 if (row_map[index] <= 0) {
562 av_log(ctx, AV_LOG_DEBUG, "Invalid pac index encountered\n");
568 ctx->cursor_row = row_map[index] - 1;
569 ctx->cursor_color = pac2_attribs[lo][0];
570 ctx->cursor_font = pac2_attribs[lo][1];
571 ctx->cursor_charset = CCSET_BASIC_AMERICAN;
572 ctx->cursor_column = 0;
573 indent = pac2_attribs[lo][2];
574 for (i = 0; i < indent; i++) {
575 write_char(ctx, screen, ' ');
580 * @param pts it is required to set end time
582 static void handle_edm(CCaptionSubContext *ctx, int64_t pts)
584 struct Screen *screen = ctx->screen + ctx->active_screen;
586 // In buffered mode, keep writing to screen until it is wiped.
587 // Before wiping the display, capture contents to emit subtitle.
589 reap_screen(ctx, pts);
591 screen->row_used = 0;
593 // In realtime mode, emit an empty caption so the last one doesn't
594 // stay on the screen.
596 reap_screen(ctx, pts);
599 static void handle_eoc(CCaptionSubContext *ctx, int64_t pts)
601 // In buffered mode, we wait til the *next* EOC and
602 // reap what was already on the screen since the last EOC.
606 ctx->active_screen = !ctx->active_screen;
607 ctx->cursor_column = 0;
609 // In realtime mode, we display the buffered contents (after
610 // flipping the buffer to active above) as soon as EOC arrives.
612 reap_screen(ctx, pts);
615 static void handle_delete_end_of_row(CCaptionSubContext *ctx, char hi, char lo)
617 struct Screen *screen = get_writing_screen(ctx);
618 write_char(ctx, screen, 0);
621 static void handle_char(CCaptionSubContext *ctx, char hi, char lo, int64_t pts)
623 struct Screen *screen = get_writing_screen(ctx);
625 SET_FLAG(screen->row_used, ctx->cursor_row);
629 ctx->cursor_charset = CCSET_SPECIAL_AMERICAN;
632 if (ctx->cursor_column > 0)
633 ctx->cursor_column -= 1;
634 ctx->cursor_charset = CCSET_EXTENDED_SPANISH_FRENCH_MISC;
637 if (ctx->cursor_column > 0)
638 ctx->cursor_column -= 1;
639 ctx->cursor_charset = CCSET_EXTENDED_PORTUGUESE_GERMAN_DANISH;
642 ctx->cursor_charset = CCSET_BASIC_AMERICAN;
643 write_char(ctx, screen, hi);
648 write_char(ctx, screen, lo);
650 write_char(ctx, screen, 0);
652 if (ctx->mode != CCMODE_POPON)
653 ctx->screen_touched = 1;
656 ff_dlog(ctx, "(%c,%c)\n", hi, lo);
658 ff_dlog(ctx, "(%c)\n", hi);
661 static void process_cc608(CCaptionSubContext *ctx, int64_t pts, uint8_t hi, uint8_t lo)
663 if (hi == ctx->prev_cmd[0] && lo == ctx->prev_cmd[1]) {
664 /* ignore redundant command */
668 /* set prev command */
669 ctx->prev_cmd[0] = hi;
670 ctx->prev_cmd[1] = lo;
672 if ( (hi == 0x10 && (lo >= 0x40 && lo <= 0x5f)) ||
673 ( (hi >= 0x11 && hi <= 0x17) && (lo >= 0x40 && lo <= 0x7f) ) ) {
674 handle_pac(ctx, hi, lo);
675 } else if ( ( hi == 0x11 && lo >= 0x20 && lo <= 0x2f ) ||
676 ( hi == 0x17 && lo >= 0x2e && lo <= 0x2f) ) {
677 handle_textattr(ctx, hi, lo);
678 } else if (hi == 0x14 || hi == 0x15 || hi == 0x1c) {
681 /* resume caption loading */
682 ctx->mode = CCMODE_POPON;
685 handle_delete_end_of_row(ctx, hi, lo);
690 ctx->rollup = lo - 0x23;
691 ctx->mode = CCMODE_ROLLUP;
694 /* resume direct captioning */
695 ctx->mode = CCMODE_PAINTON;
698 /* resume text display */
699 ctx->mode = CCMODE_TEXT;
702 /* erase display memory */
703 handle_edm(ctx, pts);
706 /* carriage return */
707 ff_dlog(ctx, "carriage return\n");
709 reap_screen(ctx, pts);
711 ctx->cursor_column = 0;
714 /* erase buffered (non displayed) memory */
715 // Only in realtime mode. In buffered mode, we re-use the inactive screen
716 // for our own buffering.
717 if (ctx->real_time) {
718 struct Screen *screen = ctx->screen + !ctx->active_screen;
719 screen->row_used = 0;
724 ff_dlog(ctx, "handle_eoc\n");
725 handle_eoc(ctx, pts);
728 ff_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
731 } else if (hi >= 0x11 && hi <= 0x13) {
732 /* Special characters */
733 handle_char(ctx, hi, lo, pts);
734 } else if (hi >= 0x20) {
735 /* Standard characters (always in pairs) */
736 handle_char(ctx, hi, lo, pts);
737 ctx->prev_cmd[0] = ctx->prev_cmd[1] = 0;
738 } else if (hi == 0x17 && lo >= 0x21 && lo <= 0x23) {
740 /* Tab offsets (spacing) */
741 for (i = 0; i < lo - 0x20; i++) {
742 handle_char(ctx, ' ', 0, pts);
745 /* Ignoring all other non data code */
746 ff_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
750 static int decode(AVCodecContext *avctx, void *data, int *got_sub, AVPacket *avpkt)
752 CCaptionSubContext *ctx = avctx->priv_data;
753 AVSubtitle *sub = data;
754 const int64_t start_time = sub->pts;
755 uint8_t *bptr = NULL;
756 int len = avpkt->size;
760 av_fast_padded_malloc(&ctx->pktbuf, &ctx->pktbuf_size, len);
762 av_log(ctx, AV_LOG_WARNING, "Insufficient Memory of %d truncated to %d\n", len, ctx->pktbuf_size);
763 return AVERROR(ENOMEM);
765 memcpy(ctx->pktbuf, avpkt->data, len);
768 for (i = 0; i < len; i += 3) {
769 uint8_t cc_type = *(bptr + i) & 3;
770 if (validate_cc_data_pair(bptr + i))
772 /* ignoring data field 1 */
776 process_cc608(ctx, start_time, *(bptr + i + 1) & 0x7f, *(bptr + i + 2) & 0x7f);
778 if (!ctx->buffer_changed)
780 ctx->buffer_changed = 0;
782 if (*ctx->buffer.str || ctx->real_time)
784 ff_dlog(ctx, "cdp writing data (%s)\n",ctx->buffer.str);
785 ret = ff_ass_add_rect(sub, ctx->buffer.str, ctx->readorder++, 0, NULL, NULL);
788 sub->pts = ctx->start_time;
790 sub->end_display_time = av_rescale_q(ctx->end_time - ctx->start_time,
791 AV_TIME_BASE_Q, ms_tb);
793 sub->end_display_time = -1;
794 ctx->buffer_changed = 0;
795 ctx->last_real_time = sub->pts;
796 ctx->screen_touched = 0;
800 if (ctx->real_time && ctx->screen_touched &&
801 sub->pts > ctx->last_real_time + av_rescale_q(200, ms_tb, AV_TIME_BASE_Q)) {
802 ctx->last_real_time = sub->pts;
803 ctx->screen_touched = 0;
806 ctx->buffer_changed = 0;
808 ret = ff_ass_add_rect(sub, ctx->buffer.str, ctx->readorder++, 0, NULL, NULL);
811 sub->end_display_time = -1;
814 *got_sub = sub->num_rects > 0;
818 #define OFFSET(x) offsetof(CCaptionSubContext, x)
819 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
820 static const AVOption options[] = {
821 { "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 },
825 static const AVClass ccaption_dec_class = {
826 .class_name = "Closed caption Decoder",
827 .item_name = av_default_item_name,
829 .version = LIBAVUTIL_VERSION_INT,
832 AVCodec ff_ccaption_decoder = {
834 .long_name = NULL_IF_CONFIG_SMALL("Closed Caption (EIA-608 / CEA-708)"),
835 .type = AVMEDIA_TYPE_SUBTITLE,
836 .id = AV_CODEC_ID_EIA_608,
837 .priv_data_size = sizeof(CCaptionSubContext),
838 .init = init_decoder,
839 .close = close_decoder,
840 .flush = flush_decoder,
842 .priv_class = &ccaption_dec_class,