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 ass_tb = {1, 100};
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 */
251 } CCaptionSubContext;
254 static av_cold int init_decoder(AVCodecContext *avctx)
257 CCaptionSubContext *ctx = avctx->priv_data;
259 av_bprint_init(&ctx->buffer, 0, AV_BPRINT_SIZE_UNLIMITED);
260 /* taking by default roll up to 2 */
261 ctx->mode = CCMODE_ROLLUP;
263 ret = ff_ass_subtitle_header(avctx, "Monospace",
264 ASS_DEFAULT_FONT_SIZE,
266 ASS_DEFAULT_BACK_COLOR,
269 ASS_DEFAULT_UNDERLINE,
271 ASS_DEFAULT_ALIGNMENT);
275 /* allocate pkt buffer */
276 ctx->pktbuf = av_buffer_alloc(128);
278 ret = AVERROR(ENOMEM);
283 static av_cold int close_decoder(AVCodecContext *avctx)
285 CCaptionSubContext *ctx = avctx->priv_data;
286 av_bprint_finalize(&ctx->buffer, NULL);
287 av_buffer_unref(&ctx->pktbuf);
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;
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 av_bprint_clear(&ctx->buffer);
313 * @param ctx closed caption context just to print log
315 static int write_char(CCaptionSubContext *ctx, struct Screen *screen, char ch)
317 uint8_t col = ctx->cursor_column;
318 char *row = screen->characters[ctx->cursor_row];
319 char *font = screen->fonts[ctx->cursor_row];
320 char *charset = screen->charsets[ctx->cursor_row];
322 if (col < SCREEN_COLUMNS) {
324 font[col] = ctx->cursor_font;
325 charset[col] = ctx->cursor_charset;
326 ctx->cursor_charset = CCSET_BASIC_AMERICAN;
327 if (ch) ctx->cursor_column++;
330 /* We have extra space at end only for null character */
331 else if (col == SCREEN_COLUMNS && ch == 0) {
336 av_log(ctx, AV_LOG_WARNING, "Data Ignored since exceeding screen width\n");
337 return AVERROR_INVALIDDATA;
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.
348 static int validate_cc_data_pair(uint8_t *cc_data_pair)
350 uint8_t cc_valid = (*cc_data_pair & 4) >>2;
351 uint8_t cc_type = *cc_data_pair & 3;
354 return AVERROR_INVALIDDATA;
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;
361 if (!av_parity(cc_data_pair[1])) {
362 cc_data_pair[1]=0x7F;
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;
372 if (cc_type == 3 || cc_type == 2)
373 return AVERROR_PATCHWELCOME;
375 /* remove parity bit */
376 cc_data_pair[1] &= 0x7F;
377 cc_data_pair[2] &= 0x7F;
382 static struct Screen *get_writing_screen(CCaptionSubContext *ctx)
386 // use Inactive screen
387 return ctx->screen + !ctx->active_screen;
392 return ctx->screen + ctx->active_screen;
394 /* It was never an option */
398 static void roll_up(CCaptionSubContext *ctx)
400 struct Screen *screen;
403 if (ctx->mode == CCMODE_TEXT)
406 screen = get_writing_screen(ctx);
408 /* +1 signify cursor_row starts from 0
409 * Can't keep lines less then row cursor pos
411 keep_lines = FFMIN(ctx->cursor_row + 1, ctx->rollup);
413 for (i = 0; i < SCREEN_ROWS; i++) {
414 if (i > ctx->cursor_row - keep_lines && i <= ctx->cursor_row)
416 UNSET_FLAG(screen->row_used, i);
419 for (i = 0; i < keep_lines && screen->row_used; i++) {
420 const int i_row = ctx->cursor_row - keep_lines + i + 1;
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);
430 UNSET_FLAG(screen->row_used, ctx->cursor_row);
433 static int capture_screen(CCaptionSubContext *ctx)
436 struct Screen *screen = ctx->screen + ctx->active_screen;
437 enum cc_font prev_font = CCFONT_REGULAR;
438 av_bprint_clear(&ctx->buffer);
440 for (i = 0; screen->row_used && i < SCREEN_ROWS; i++)
442 if (CHECK_FLAG(screen->row_used, i)) {
443 const char *row = screen->characters[i];
444 const char *font = screen->fonts[i];
445 const char *charset = screen->charsets[i];
446 const char *override;
449 /* skip leading space */
450 while (row[j] == ' ' && charset[j] == CCSET_BASIC_AMERICAN)
453 for (; j < SCREEN_COLUMNS; j++) {
454 const char *e_tag = "", *s_tag = "";
459 if (prev_font != font[j]) {
464 case CCFONT_UNDERLINED:
467 case CCFONT_UNDERLINED_ITALICS:
468 e_tag = "{\\u0}{\\i0}";
475 case CCFONT_UNDERLINED:
478 case CCFONT_UNDERLINED_ITALICS:
479 s_tag = "{\\u1}{\\i1}";
484 override = charset_overrides[(int)charset[j]][(int)row[j]];
486 av_bprintf(&ctx->buffer, "%s%s%s", e_tag, s_tag, override);
488 av_bprintf(&ctx->buffer, "%s%s%c", e_tag, s_tag, row[j]);
491 av_bprintf(&ctx->buffer, "\\N");
494 if (!av_bprint_is_complete(&ctx->buffer))
495 return AVERROR(ENOMEM);
496 if (screen->row_used && ctx->buffer.len >= 2) {
497 ctx->buffer.len -= 2;
498 ctx->buffer.str[ctx->buffer.len] = 0;
500 ctx->buffer_changed = 1;
504 static int reap_screen(CCaptionSubContext *ctx, int64_t pts)
506 ctx->start_time = ctx->startv_time;
507 ctx->startv_time = pts;
509 return capture_screen(ctx);
512 static void handle_textattr(CCaptionSubContext *ctx, uint8_t hi, uint8_t lo)
515 struct Screen *screen = get_writing_screen(ctx);
520 ctx->cursor_color = pac2_attribs[i][0];
521 ctx->cursor_font = pac2_attribs[i][1];
523 SET_FLAG(screen->row_used, ctx->cursor_row);
524 write_char(ctx, screen, ' ');
527 static void handle_pac(CCaptionSubContext *ctx, uint8_t hi, uint8_t lo)
529 static const int8_t row_map[] = {
530 11, -1, 1, 2, 3, 4, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10
532 const int index = ( (hi<<1) & 0x0e) | ( (lo>>5) & 0x01 );
533 struct Screen *screen = get_writing_screen(ctx);
536 if (row_map[index] <= 0) {
537 av_log(ctx, AV_LOG_DEBUG, "Invalid pac index encountered\n");
543 ctx->cursor_row = row_map[index] - 1;
544 ctx->cursor_color = pac2_attribs[lo][0];
545 ctx->cursor_font = pac2_attribs[lo][1];
546 ctx->cursor_charset = CCSET_BASIC_AMERICAN;
547 ctx->cursor_column = 0;
548 indent = pac2_attribs[lo][2];
549 for (i = 0; i < indent; i++) {
550 write_char(ctx, screen, ' ');
555 * @param pts it is required to set end time
557 static void handle_edm(CCaptionSubContext *ctx, int64_t pts)
559 struct Screen *screen = ctx->screen + ctx->active_screen;
561 // In buffered mode, keep writing to screen until it is wiped.
562 // Before wiping the display, capture contents to emit subtitle.
564 reap_screen(ctx, pts);
566 screen->row_used = 0;
568 // In realtime mode, emit an empty caption so the last one doesn't
569 // stay on the screen.
571 reap_screen(ctx, pts);
574 static void handle_eoc(CCaptionSubContext *ctx, int64_t pts)
576 // In buffered mode, we wait til the *next* EOC and
577 // reap what was already on the screen since the last EOC.
581 ctx->active_screen = !ctx->active_screen;
582 ctx->cursor_column = 0;
584 // In realtime mode, we display the buffered contents (after
585 // flipping the buffer to active above) as soon as EOC arrives.
587 reap_screen(ctx, pts);
590 static void handle_delete_end_of_row(CCaptionSubContext *ctx, char hi, char lo)
592 struct Screen *screen = get_writing_screen(ctx);
593 write_char(ctx, screen, 0);
596 static void handle_char(CCaptionSubContext *ctx, char hi, char lo, int64_t pts)
598 struct Screen *screen = get_writing_screen(ctx);
600 SET_FLAG(screen->row_used, ctx->cursor_row);
604 ctx->cursor_charset = CCSET_SPECIAL_AMERICAN;
607 if (ctx->cursor_column > 0)
608 ctx->cursor_column -= 1;
609 ctx->cursor_charset = CCSET_EXTENDED_SPANISH_FRENCH_MISC;
612 if (ctx->cursor_column > 0)
613 ctx->cursor_column -= 1;
614 ctx->cursor_charset = CCSET_EXTENDED_PORTUGUESE_GERMAN_DANISH;
617 ctx->cursor_charset = CCSET_BASIC_AMERICAN;
618 write_char(ctx, screen, hi);
623 write_char(ctx, screen, lo);
625 write_char(ctx, screen, 0);
627 if (ctx->mode != CCMODE_POPON)
628 ctx->screen_touched = 1;
631 ff_dlog(ctx, "(%c,%c)\n", hi, lo);
633 ff_dlog(ctx, "(%c)\n", hi);
636 static void process_cc608(CCaptionSubContext *ctx, int64_t pts, uint8_t hi, uint8_t lo)
638 if (hi == ctx->prev_cmd[0] && lo == ctx->prev_cmd[1]) {
639 /* ignore redundant command */
643 /* set prev command */
644 ctx->prev_cmd[0] = hi;
645 ctx->prev_cmd[1] = lo;
647 if ( (hi == 0x10 && (lo >= 0x40 && lo <= 0x5f)) ||
648 ( (hi >= 0x11 && hi <= 0x17) && (lo >= 0x40 && lo <= 0x7f) ) ) {
649 handle_pac(ctx, hi, lo);
650 } else if ( ( hi == 0x11 && lo >= 0x20 && lo <= 0x2f ) ||
651 ( hi == 0x17 && lo >= 0x2e && lo <= 0x2f) ) {
652 handle_textattr(ctx, hi, lo);
653 } else if (hi == 0x14 || hi == 0x15 || hi == 0x1c) {
656 /* resume caption loading */
657 ctx->mode = CCMODE_POPON;
660 handle_delete_end_of_row(ctx, hi, lo);
665 ctx->rollup = lo - 0x23;
666 ctx->mode = CCMODE_ROLLUP;
669 /* resume direct captioning */
670 ctx->mode = CCMODE_PAINTON;
673 /* resume text display */
674 ctx->mode = CCMODE_TEXT;
677 /* erase display memory */
678 handle_edm(ctx, pts);
681 /* carriage return */
682 ff_dlog(ctx, "carriage return\n");
684 reap_screen(ctx, pts);
686 ctx->cursor_column = 0;
689 /* erase buffered (non displayed) memory */
690 // Only in realtime mode. In buffered mode, we re-use the inactive screen
691 // for our own buffering.
692 if (ctx->real_time) {
693 struct Screen *screen = ctx->screen + !ctx->active_screen;
694 screen->row_used = 0;
699 ff_dlog(ctx, "handle_eoc\n");
700 handle_eoc(ctx, pts);
703 ff_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
706 } else if (hi >= 0x11 && hi <= 0x13) {
707 /* Special characters */
708 handle_char(ctx, hi, lo, pts);
709 } else if (hi >= 0x20) {
710 /* Standard characters (always in pairs) */
711 handle_char(ctx, hi, lo, pts);
712 ctx->prev_cmd[0] = ctx->prev_cmd[1] = 0;
714 /* Ignoring all other non data code */
715 ff_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
719 static int decode(AVCodecContext *avctx, void *data, int *got_sub, AVPacket *avpkt)
721 CCaptionSubContext *ctx = avctx->priv_data;
722 AVSubtitle *sub = data;
723 uint8_t *bptr = NULL;
724 int len = avpkt->size;
728 if (ctx->pktbuf->size < len) {
729 ret = av_buffer_realloc(&ctx->pktbuf, len);
731 av_log(ctx, AV_LOG_WARNING, "Insufficient Memory of %d truncated to %d\n", len, ctx->pktbuf->size);
732 len = ctx->pktbuf->size;
736 memcpy(ctx->pktbuf->data, avpkt->data, len);
737 bptr = ctx->pktbuf->data;
739 for (i = 0; i < len; i += 3) {
740 uint8_t cc_type = *(bptr + i) & 3;
741 if (validate_cc_data_pair(bptr + i))
743 /* ignoring data field 1 */
747 process_cc608(ctx, avpkt->pts, *(bptr + i + 1) & 0x7f, *(bptr + i + 2) & 0x7f);
749 if (!ctx->buffer_changed)
751 ctx->buffer_changed = 0;
753 if (*ctx->buffer.str || ctx->real_time)
755 int64_t sub_pts = ctx->real_time ? avpkt->pts : ctx->start_time;
756 int start_time = av_rescale_q(sub_pts, avctx->time_base, ass_tb);
758 if (!ctx->real_time) {
759 int end_time = av_rescale_q(ctx->end_time, avctx->time_base, ass_tb);
760 duration = end_time - start_time;
762 ff_dlog(ctx, "cdp writing data (%s)\n",ctx->buffer.str);
763 ret = ff_ass_add_rect_bprint(sub, &ctx->buffer, start_time, duration);
766 sub->pts = av_rescale_q(sub_pts, avctx->time_base, AV_TIME_BASE_Q);
767 ctx->buffer_changed = 0;
768 ctx->last_real_time = avpkt->pts;
769 ctx->screen_touched = 0;
773 if (ctx->real_time && ctx->screen_touched &&
774 avpkt->pts > ctx->last_real_time + av_rescale_q(20, ass_tb, avctx->time_base)) {
776 ctx->last_real_time = avpkt->pts;
777 ctx->screen_touched = 0;
780 ctx->buffer_changed = 0;
782 start_time = av_rescale_q(avpkt->pts, avctx->time_base, ass_tb);
783 ret = ff_ass_add_rect_bprint(sub, &ctx->buffer, start_time, -1);
786 sub->pts = av_rescale_q(avpkt->pts, avctx->time_base, AV_TIME_BASE_Q);
789 *got_sub = sub->num_rects > 0;
793 #define OFFSET(x) offsetof(CCaptionSubContext, x)
794 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
795 static const AVOption options[] = {
796 { "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 },
800 static const AVClass ccaption_dec_class = {
801 .class_name = "Closed caption Decoder",
802 .item_name = av_default_item_name,
804 .version = LIBAVUTIL_VERSION_INT,
807 AVCodec ff_ccaption_decoder = {
809 .long_name = NULL_IF_CONFIG_SMALL("Closed Caption (EIA-608 / CEA-708) Decoder"),
810 .type = AVMEDIA_TYPE_SUBTITLE,
811 .id = AV_CODEC_ID_EIA_608,
812 .priv_data_size = sizeof(CCaptionSubContext),
813 .init = init_decoder,
814 .close = close_decoder,
815 .flush = flush_decoder,
817 .priv_class = &ccaption_dec_class,