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,
66 static const unsigned char pac2_attribs[32][3] = // Color, font, ident
68 { CCCOL_WHITE, CCFONT_REGULAR, 0 }, // 0x40 || 0x60
69 { CCCOL_WHITE, CCFONT_UNDERLINED, 0 }, // 0x41 || 0x61
70 { CCCOL_GREEN, CCFONT_REGULAR, 0 }, // 0x42 || 0x62
71 { CCCOL_GREEN, CCFONT_UNDERLINED, 0 }, // 0x43 || 0x63
72 { CCCOL_BLUE, CCFONT_REGULAR, 0 }, // 0x44 || 0x64
73 { CCCOL_BLUE, CCFONT_UNDERLINED, 0 }, // 0x45 || 0x65
74 { CCCOL_CYAN, CCFONT_REGULAR, 0 }, // 0x46 || 0x66
75 { CCCOL_CYAN, CCFONT_UNDERLINED, 0 }, // 0x47 || 0x67
76 { CCCOL_RED, CCFONT_REGULAR, 0 }, // 0x48 || 0x68
77 { CCCOL_RED, CCFONT_UNDERLINED, 0 }, // 0x49 || 0x69
78 { CCCOL_YELLOW, CCFONT_REGULAR, 0 }, // 0x4a || 0x6a
79 { CCCOL_YELLOW, CCFONT_UNDERLINED, 0 }, // 0x4b || 0x6b
80 { CCCOL_MAGENTA, CCFONT_REGULAR, 0 }, // 0x4c || 0x6c
81 { CCCOL_MAGENTA, CCFONT_UNDERLINED, 0 }, // 0x4d || 0x6d
82 { CCCOL_WHITE, CCFONT_ITALICS, 0 }, // 0x4e || 0x6e
83 { CCCOL_WHITE, CCFONT_UNDERLINED_ITALICS, 0 }, // 0x4f || 0x6f
84 { CCCOL_WHITE, CCFONT_REGULAR, 0 }, // 0x50 || 0x70
85 { CCCOL_WHITE, CCFONT_UNDERLINED, 0 }, // 0x51 || 0x71
86 { CCCOL_WHITE, CCFONT_REGULAR, 4 }, // 0x52 || 0x72
87 { CCCOL_WHITE, CCFONT_UNDERLINED, 4 }, // 0x53 || 0x73
88 { CCCOL_WHITE, CCFONT_REGULAR, 8 }, // 0x54 || 0x74
89 { CCCOL_WHITE, CCFONT_UNDERLINED, 8 }, // 0x55 || 0x75
90 { CCCOL_WHITE, CCFONT_REGULAR, 12 }, // 0x56 || 0x76
91 { CCCOL_WHITE, CCFONT_UNDERLINED, 12 }, // 0x57 || 0x77
92 { CCCOL_WHITE, CCFONT_REGULAR, 16 }, // 0x58 || 0x78
93 { CCCOL_WHITE, CCFONT_UNDERLINED, 16 }, // 0x59 || 0x79
94 { CCCOL_WHITE, CCFONT_REGULAR, 20 }, // 0x5a || 0x7a
95 { CCCOL_WHITE, CCFONT_UNDERLINED, 20 }, // 0x5b || 0x7b
96 { CCCOL_WHITE, CCFONT_REGULAR, 24 }, // 0x5c || 0x7c
97 { CCCOL_WHITE, CCFONT_UNDERLINED, 24 }, // 0x5d || 0x7d
98 { CCCOL_WHITE, CCFONT_REGULAR, 28 }, // 0x5e || 0x7e
99 { CCCOL_WHITE, CCFONT_UNDERLINED, 28 } // 0x5f || 0x7f
100 /* total 32 entries */
104 /* +1 is used to compensate null character of string */
105 uint8_t characters[SCREEN_ROWS][SCREEN_COLUMNS+1];
106 uint8_t colors[SCREEN_ROWS][SCREEN_COLUMNS+1];
107 uint8_t fonts[SCREEN_ROWS][SCREEN_COLUMNS+1];
109 * Bitmask of used rows; if a bit is not set, the
110 * corresponding row is not used.
111 * for setting row 1 use row | (1 << 0)
112 * for setting row 15 use row | (1 << 14)
117 typedef struct CCaptionSubContext {
119 struct Screen screen[2];
122 uint8_t cursor_column;
123 uint8_t cursor_color;
130 /* visible screen time */
134 /* buffer to store pkt data */
136 } CCaptionSubContext;
139 static av_cold int init_decoder(AVCodecContext *avctx)
142 CCaptionSubContext *ctx = avctx->priv_data;
144 av_bprint_init(&ctx->buffer, 0, AV_BPRINT_SIZE_UNLIMITED);
145 /* taking by default roll up to 2 */
146 ctx->mode = CCMODE_ROLLUP;
148 ret = ff_ass_subtitle_header(avctx, "Monospace",
149 ASS_DEFAULT_FONT_SIZE,
151 ASS_DEFAULT_BACK_COLOR,
154 ASS_DEFAULT_UNDERLINE,
156 ASS_DEFAULT_ALIGNMENT);
160 /* allocate pkt buffer */
161 ctx->pktbuf = av_buffer_alloc(128);
163 ret = AVERROR(ENOMEM);
168 static av_cold int close_decoder(AVCodecContext *avctx)
170 CCaptionSubContext *ctx = avctx->priv_data;
171 av_bprint_finalize(&ctx->buffer, NULL);
172 av_buffer_unref(&ctx->pktbuf);
177 * @param ctx closed caption context just to print log
179 static int write_char(CCaptionSubContext *ctx, struct Screen *screen, char ch)
181 uint8_t col = ctx->cursor_column;
182 char *row = screen->characters[ctx->cursor_row];
183 char *font = screen->fonts[ctx->cursor_row];
185 if (col < SCREEN_COLUMNS) {
187 font[col] = ctx->cursor_font;
188 if (ch) ctx->cursor_column++;
191 /* We have extra space at end only for null character */
192 else if (col == SCREEN_COLUMNS && ch == 0) {
197 av_log(ctx, AV_LOG_WARNING, "Data Ignored since exceeding screen width\n");
198 return AVERROR_INVALIDDATA;
203 * This function after validating parity bit, also remove it from data pair.
204 * The first byte doesn't pass parity, we replace it with a solid blank
205 * and process the pair.
206 * If the second byte doesn't pass parity, it returns INVALIDDATA
207 * user can ignore the whole pair and pass the other pair.
209 static int validate_cc_data_pair(uint8_t *cc_data_pair)
211 uint8_t cc_valid = (*cc_data_pair & 4) >>2;
212 uint8_t cc_type = *cc_data_pair & 3;
215 return AVERROR_INVALIDDATA;
217 // if EIA-608 data then verify parity.
218 if (cc_type==0 || cc_type==1) {
219 if (!av_parity(cc_data_pair[2])) {
220 return AVERROR_INVALIDDATA;
222 if (!av_parity(cc_data_pair[1])) {
223 cc_data_pair[1]=0x7F;
228 if ((cc_data_pair[0] == 0xFA || cc_data_pair[0] == 0xFC || cc_data_pair[0] == 0xFD)
229 && (cc_data_pair[1] & 0x7F) == 0 && (cc_data_pair[2] & 0x7F) == 0)
230 return AVERROR_PATCHWELCOME;
233 if (cc_type == 3 || cc_type == 2)
234 return AVERROR_PATCHWELCOME;
236 /* remove parity bit */
237 cc_data_pair[1] &= 0x7F;
238 cc_data_pair[2] &= 0x7F;
243 static struct Screen *get_writing_screen(CCaptionSubContext *ctx)
247 // use Inactive screen
248 return ctx->screen + !ctx->active_screen;
253 return ctx->screen + ctx->active_screen;
255 /* It was never an option */
259 static void roll_up(CCaptionSubContext *ctx)
261 struct Screen *screen;
264 if (ctx->mode == CCMODE_TEXT)
267 screen = get_writing_screen(ctx);
269 /* +1 signify cursor_row starts from 0
270 * Can't keep lines less then row cursor pos
272 keep_lines = FFMIN(ctx->cursor_row + 1, ctx->rollup);
274 for (i = 0; i < ctx->cursor_row - keep_lines; i++)
275 UNSET_FLAG(screen->row_used, i);
278 for (i = 0; i < keep_lines && screen->row_used; i++) {
279 const int i_row = ctx->cursor_row - keep_lines + i + 1;
281 memcpy(screen->characters[i_row], screen->characters[i_row+1], SCREEN_COLUMNS);
282 memcpy(screen->colors[i_row], screen->colors[i_row+1], SCREEN_COLUMNS);
283 memcpy(screen->fonts[i_row], screen->fonts[i_row+1], SCREEN_COLUMNS);
284 if (CHECK_FLAG(screen->row_used, i_row + 1))
285 SET_FLAG(screen->row_used, i_row);
288 UNSET_FLAG(screen->row_used, ctx->cursor_row);
291 static int capture_screen(CCaptionSubContext *ctx)
294 struct Screen *screen = ctx->screen + ctx->active_screen;
295 enum cc_font prev_font = CCFONT_REGULAR;
296 av_bprint_clear(&ctx->buffer);
298 for (i = 0; screen->row_used && i < SCREEN_ROWS; i++)
300 if (CHECK_FLAG(screen->row_used, i)) {
301 const char *row = screen->characters[i];
302 const char *font = screen->fonts[i];
305 /* skip leading space */
306 while (row[j] == ' ')
309 for (; j < SCREEN_COLUMNS; j++) {
310 const char *e_tag = "", *s_tag = "";
315 if (prev_font != font[j]) {
320 case CCFONT_UNDERLINED:
323 case CCFONT_UNDERLINED_ITALICS:
324 e_tag = "{\\u0}{\\i0}";
331 case CCFONT_UNDERLINED:
334 case CCFONT_UNDERLINED_ITALICS:
335 s_tag = "{\\u1}{\\i1}";
340 av_bprintf(&ctx->buffer, "%s%s%c", e_tag, s_tag, row[j]);
342 av_bprintf(&ctx->buffer, "\\N");
345 if (!av_bprint_is_complete(&ctx->buffer))
346 return AVERROR(ENOMEM);
347 if (screen->row_used && ctx->buffer.len >= 2) {
348 ctx->buffer.len -= 2;
349 ctx->buffer.str[ctx->buffer.len] = 0;
351 ctx->buffer_changed = 1;
355 static int reap_screen(CCaptionSubContext *ctx, int64_t pts)
357 ctx->start_time = ctx->startv_time;
358 ctx->startv_time = pts;
360 return capture_screen(ctx);
363 static void handle_textattr(CCaptionSubContext *ctx, uint8_t hi, uint8_t lo)
366 struct Screen *screen = get_writing_screen(ctx);
371 ctx->cursor_color = pac2_attribs[i][0];
372 ctx->cursor_font = pac2_attribs[i][1];
374 SET_FLAG(screen->row_used, ctx->cursor_row);
375 write_char(ctx, screen, ' ');
378 static void handle_pac(CCaptionSubContext *ctx, uint8_t hi, uint8_t lo)
380 static const int8_t row_map[] = {
381 11, -1, 1, 2, 3, 4, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10
383 const int index = ( (hi<<1) & 0x0e) | ( (lo>>5) & 0x01 );
384 struct Screen *screen = get_writing_screen(ctx);
387 if (row_map[index] <= 0) {
388 av_log(ctx, AV_LOG_DEBUG, "Invalid pac index encountered\n");
394 ctx->cursor_row = row_map[index] - 1;
395 ctx->cursor_color = pac2_attribs[lo][0];
396 ctx->cursor_font = pac2_attribs[lo][1];
397 ctx->cursor_column = 0;
398 indent = pac2_attribs[lo][2];
399 for (i = 0; i < indent; i++) {
400 write_char(ctx, screen, ' ');
405 * @param pts it is required to set end time
407 static void handle_edm(CCaptionSubContext *ctx, int64_t pts)
409 struct Screen *screen = ctx->screen + ctx->active_screen;
411 reap_screen(ctx, pts);
412 screen->row_used = 0;
415 static void handle_eoc(CCaptionSubContext *ctx, int64_t pts)
418 ctx->active_screen = !ctx->active_screen;
419 ctx->cursor_column = 0;
422 static void handle_delete_end_of_row(CCaptionSubContext *ctx, char hi, char lo)
424 struct Screen *screen = get_writing_screen(ctx);
425 write_char(ctx, screen, 0);
428 static void handle_char(CCaptionSubContext *ctx, char hi, char lo, int64_t pts)
430 struct Screen *screen = get_writing_screen(ctx);
432 SET_FLAG(screen->row_used, ctx->cursor_row);
434 write_char(ctx, screen, hi);
437 write_char(ctx, screen, lo);
439 write_char(ctx, screen, 0);
441 /* reset prev command since character can repeat */
442 ctx->prev_cmd[0] = 0;
443 ctx->prev_cmd[1] = 0;
445 ff_dlog(ctx, "(%c,%c)\n", hi, lo);
447 ff_dlog(ctx, "(%c)\n", hi);
450 static void process_cc608(CCaptionSubContext *ctx, int64_t pts, uint8_t hi, uint8_t lo)
452 if (hi == ctx->prev_cmd[0] && lo == ctx->prev_cmd[1]) {
453 /* ignore redundant command */
454 } else if ( (hi == 0x10 && (lo >= 0x40 && lo <= 0x5f)) ||
455 ( (hi >= 0x11 && hi <= 0x17) && (lo >= 0x40 && lo <= 0x7f) ) ) {
456 handle_pac(ctx, hi, lo);
457 } else if ( ( hi == 0x11 && lo >= 0x20 && lo <= 0x2f ) ||
458 ( hi == 0x17 && lo >= 0x2e && lo <= 0x2f) ) {
459 handle_textattr(ctx, hi, lo);
460 } else if (hi == 0x14 || hi == 0x15 || hi == 0x1c) {
463 /* resume caption loading */
464 ctx->mode = CCMODE_POPON;
467 handle_delete_end_of_row(ctx, hi, lo);
472 ctx->rollup = lo - 0x23;
473 ctx->mode = CCMODE_ROLLUP;
476 /* resume direct captioning */
477 ctx->mode = CCMODE_PAINTON;
480 /* resume text display */
481 ctx->mode = CCMODE_TEXT;
484 /* erase display memory */
485 handle_edm(ctx, pts);
488 /* carriage return */
489 ff_dlog(ctx, "carriage return\n");
490 reap_screen(ctx, pts);
492 ctx->cursor_column = 0;
496 ff_dlog(ctx, "handle_eoc\n");
497 handle_eoc(ctx, pts);
500 ff_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
503 } else if (hi >= 0x20) {
504 /* Standard characters (always in pairs) */
505 handle_char(ctx, hi, lo, pts);
507 /* Ignoring all other non data code */
508 ff_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);
511 /* set prev command */
512 ctx->prev_cmd[0] = hi;
513 ctx->prev_cmd[1] = lo;
516 static int decode(AVCodecContext *avctx, void *data, int *got_sub, AVPacket *avpkt)
518 CCaptionSubContext *ctx = avctx->priv_data;
519 AVSubtitle *sub = data;
520 uint8_t *bptr = NULL;
521 int len = avpkt->size;
525 if (ctx->pktbuf->size < len) {
526 ret = av_buffer_realloc(&ctx->pktbuf, len);
528 av_log(ctx, AV_LOG_WARNING, "Insufficient Memory of %d truncated to %d\n", len, ctx->pktbuf->size);
529 len = ctx->pktbuf->size;
533 memcpy(ctx->pktbuf->data, avpkt->data, len);
534 bptr = ctx->pktbuf->data;
536 for (i = 0; i < len; i += 3) {
537 uint8_t cc_type = *(bptr + i) & 3;
538 if (validate_cc_data_pair(bptr + i))
540 /* ignoring data field 1 */
544 process_cc608(ctx, avpkt->pts, *(bptr + i + 1) & 0x7f, *(bptr + i + 2) & 0x7f);
545 if (ctx->buffer_changed && *ctx->buffer.str)
547 int start_time = av_rescale_q(ctx->start_time, avctx->time_base, ass_tb);
548 int end_time = av_rescale_q(ctx->end_time, avctx->time_base, ass_tb);
549 ff_dlog(ctx, "cdp writing data (%s)\n",ctx->buffer.str);
550 ret = ff_ass_add_rect_bprint(sub, &ctx->buffer, start_time, end_time - start_time);
553 sub->pts = av_rescale_q(ctx->start_time, avctx->time_base, AV_TIME_BASE_Q);
554 ctx->buffer_changed = 0;
558 *got_sub = sub->num_rects > 0;
562 static const AVOption options[] = {
566 static const AVClass ccaption_dec_class = {
567 .class_name = "Closed caption Decoder",
568 .item_name = av_default_item_name,
570 .version = LIBAVUTIL_VERSION_INT,
573 AVCodec ff_ccaption_decoder = {
575 .long_name = NULL_IF_CONFIG_SMALL("Closed Caption (EIA-608 / CEA-708) Decoder"),
576 .type = AVMEDIA_TYPE_SUBTITLE,
577 .id = AV_CODEC_ID_EIA_608,
578 .priv_data_size = sizeof(CCaptionSubContext),
579 .init = init_decoder,
580 .close = close_decoder,
582 .priv_class = &ccaption_dec_class,