2 * DVD subtitle decoding
3 * Copyright (c) 2005 Fabrice Bellard
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
26 #include "libavutil/attributes.h"
27 #include "libavutil/colorspace.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/bswap.h"
33 typedef struct DVDSubContext
50 static void yuv_a_to_rgba(const uint8_t *ycbcr, const uint8_t *alpha, uint32_t *rgba, int num_values)
52 const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;
55 int r_add, g_add, b_add;
57 for (i = num_values; i > 0; i--) {
61 YUV_TO_RGB1_CCIR(cb, cr);
62 YUV_TO_RGB2_CCIR(r, g, b, y);
63 *rgba++ = (*alpha++ << 24) | (r << 16) | (g << 8) | b;
67 static int decode_run_2bit(GetBitContext *gb, int *color)
72 for (t = 1; v < t && t <= 0x40; t <<= 2)
73 v = (v << 4) | get_bits(gb, 4);
75 if (v < 4) { /* Code for fill rest of line */
81 static int decode_run_8bit(GetBitContext *gb, int *color)
84 int has_run = get_bits1(gb);
86 *color = get_bits(gb, 8);
88 *color = get_bits(gb, 2);
91 len = get_bits(gb, 7);
97 len = get_bits(gb, 3) + 2;
103 static int decode_rle(uint8_t *bitmap, int linesize, int w, int h,
104 const uint8_t *buf, int start, int buf_size, int is_8bit)
108 int x, y, len, color;
111 if (start >= buf_size)
114 bit_len = (buf_size - start) * 8;
115 init_get_bits(&gb, buf + start, bit_len);
121 if (get_bits_count(&gb) > bit_len)
124 len = decode_run_8bit(&gb, &color);
126 len = decode_run_2bit(&gb, &color);
127 len = FFMIN(len, w - x);
128 memset(d + x, color, len);
143 static void guess_palette(DVDSubContext* ctx,
144 uint32_t *rgba_palette,
145 uint32_t subtitle_color)
147 static const uint8_t level_map[4][4] = {
148 // this configuration (full range, lowest to highest) in tests
149 // seemed most common, so assume this
153 {0x00, 0x55, 0xaa, 0xff},
155 uint8_t color_used[16] = { 0 };
156 int nb_opaque_colors, i, level, j, r, g, b;
157 uint8_t *colormap = ctx->colormap, *alpha = ctx->alpha;
159 if(ctx->has_palette) {
160 for(i = 0; i < 4; i++)
161 rgba_palette[i] = (ctx->palette[colormap[i]] & 0x00ffffff)
162 | ((alpha[i] * 17U) << 24);
166 for(i = 0; i < 4; i++)
169 nb_opaque_colors = 0;
170 for(i = 0; i < 4; i++) {
171 if (alpha[i] != 0 && !color_used[colormap[i]]) {
172 color_used[colormap[i]] = 1;
177 if (nb_opaque_colors == 0)
181 memset(color_used, 0, 16);
182 for(i = 0; i < 4; i++) {
184 if (!color_used[colormap[i]]) {
185 level = level_map[nb_opaque_colors][j];
186 r = (((subtitle_color >> 16) & 0xff) * level) >> 8;
187 g = (((subtitle_color >> 8) & 0xff) * level) >> 8;
188 b = (((subtitle_color >> 0) & 0xff) * level) >> 8;
189 rgba_palette[i] = b | (g << 8) | (r << 16) | ((alpha[i] * 17) << 24);
190 color_used[colormap[i]] = (i + 1);
193 rgba_palette[i] = (rgba_palette[color_used[colormap[i]] - 1] & 0x00ffffff) |
194 ((alpha[i] * 17) << 24);
200 static void reset_rects(AVSubtitle *sub_header)
204 if (sub_header->rects) {
205 for (i = 0; i < sub_header->num_rects; i++) {
206 av_freep(&sub_header->rects[i]->pict.data[0]);
207 av_freep(&sub_header->rects[i]->pict.data[1]);
208 av_freep(&sub_header->rects[i]);
210 av_freep(&sub_header->rects);
211 sub_header->num_rects = 0;
215 #define READ_OFFSET(a) (big_offsets ? AV_RB32(a) : AV_RB16(a))
217 static int decode_dvd_subtitles(DVDSubContext *ctx, AVSubtitle *sub_header,
218 const uint8_t *buf, int buf_size)
220 int cmd_pos, pos, cmd, x1, y1, x2, y2, offset1, offset2, next_cmd_pos;
221 int big_offsets, offset_size, is_8bit = 0;
222 const uint8_t *yuv_palette = NULL;
223 uint8_t *colormap = ctx->colormap, *alpha = ctx->alpha;
231 if (AV_RB16(buf) == 0) { /* HD subpicture with 4-byte offsets */
241 cmd_pos = READ_OFFSET(buf + cmd_pos);
243 if (cmd_pos < 0 || cmd_pos > buf_size - 2 - offset_size)
244 return AVERROR(EAGAIN);
246 while (cmd_pos > 0 && cmd_pos < buf_size - 2 - offset_size) {
247 date = AV_RB16(buf + cmd_pos);
248 next_cmd_pos = READ_OFFSET(buf + cmd_pos + 2);
249 av_dlog(NULL, "cmd_pos=0x%04x next=0x%04x date=%d\n",
250 cmd_pos, next_cmd_pos, date);
251 pos = cmd_pos + 2 + offset_size;
254 x1 = y1 = x2 = y2 = 0;
255 while (pos < buf_size) {
257 av_dlog(NULL, "cmd=%02x\n", cmd);
260 /* menu subpicture */
265 sub_header->start_display_time = (date << 10) / 90;
269 sub_header->end_display_time = (date << 10) / 90;
273 if ((buf_size - pos) < 2)
275 colormap[3] = buf[pos] >> 4;
276 colormap[2] = buf[pos] & 0x0f;
277 colormap[1] = buf[pos + 1] >> 4;
278 colormap[0] = buf[pos + 1] & 0x0f;
283 if ((buf_size - pos) < 2)
285 alpha[3] = buf[pos] >> 4;
286 alpha[2] = buf[pos] & 0x0f;
287 alpha[1] = buf[pos + 1] >> 4;
288 alpha[0] = buf[pos + 1] & 0x0f;
290 av_dlog(NULL, "alpha=%x%x%x%x\n", alpha[0],alpha[1],alpha[2],alpha[3]);
294 if ((buf_size - pos) < 6)
296 x1 = (buf[pos] << 4) | (buf[pos + 1] >> 4);
297 x2 = ((buf[pos + 1] & 0x0f) << 8) | buf[pos + 2];
298 y1 = (buf[pos + 3] << 4) | (buf[pos + 4] >> 4);
299 y2 = ((buf[pos + 4] & 0x0f) << 8) | buf[pos + 5];
302 av_dlog(NULL, "x1=%d x2=%d y1=%d y2=%d\n", x1, x2, y1, y2);
306 if ((buf_size - pos) < 4)
308 offset1 = AV_RB16(buf + pos);
309 offset2 = AV_RB16(buf + pos + 2);
310 av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);
314 if ((buf_size - pos) < 8)
316 offset1 = AV_RB32(buf + pos);
317 offset2 = AV_RB32(buf + pos + 4);
318 av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);
324 if ((buf_size - pos) < 768)
326 yuv_palette = buf + pos;
330 /* HD set contrast (alpha) */
331 if ((buf_size - pos) < 256)
333 for (i = 0; i < 256; i++)
334 alpha[i] = 0xFF - buf[pos+i];
341 av_dlog(NULL, "unrecognised subpicture command 0x%x\n", cmd);
350 /* decode the bitmap */
357 if (w > 0 && h > 0) {
358 reset_rects(sub_header);
360 bitmap = av_malloc(w * h);
361 sub_header->rects = av_mallocz(sizeof(*sub_header->rects));
362 sub_header->rects[0] = av_mallocz(sizeof(AVSubtitleRect));
363 sub_header->num_rects = 1;
364 sub_header->rects[0]->pict.data[0] = bitmap;
365 if (decode_rle(bitmap, w * 2, w, (h + 1) / 2,
366 buf, offset1, buf_size, is_8bit) < 0)
368 if (decode_rle(bitmap + w, w * 2, w, h / 2,
369 buf, offset2, buf_size, is_8bit) < 0)
371 sub_header->rects[0]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
375 sub_header->rects[0]->nb_colors = 256;
376 yuv_a_to_rgba(yuv_palette, alpha, (uint32_t*)sub_header->rects[0]->pict.data[1], 256);
378 sub_header->rects[0]->nb_colors = 4;
379 guess_palette(ctx, (uint32_t*)sub_header->rects[0]->pict.data[1],
382 sub_header->rects[0]->x = x1;
383 sub_header->rects[0]->y = y1;
384 sub_header->rects[0]->w = w;
385 sub_header->rects[0]->h = h;
386 sub_header->rects[0]->type = SUBTITLE_BITMAP;
387 sub_header->rects[0]->pict.linesize[0] = w;
388 sub_header->rects[0]->flags = is_menu ? AV_SUBTITLE_FLAG_FORCED : 0;
391 if (next_cmd_pos < cmd_pos) {
392 av_log(NULL, AV_LOG_ERROR, "Invalid command offset\n");
395 if (next_cmd_pos == cmd_pos)
397 cmd_pos = next_cmd_pos;
399 if (sub_header->num_rects > 0)
402 reset_rects(sub_header);
406 static int is_transp(const uint8_t *buf, int pitch, int n,
407 const uint8_t *transp_color)
410 for(i = 0; i < n; i++) {
411 if (!transp_color[*buf])
418 /* return 0 if empty rectangle, 1 if non empty */
419 static int find_smallest_bounding_rectangle(AVSubtitle *s)
421 uint8_t transp_color[256] = { 0 };
422 int y1, y2, x1, x2, y, w, h, i;
425 if (s->num_rects == 0 || !s->rects || s->rects[0]->w <= 0 || s->rects[0]->h <= 0)
428 for(i = 0; i < s->rects[0]->nb_colors; i++) {
429 if ((((uint32_t*)s->rects[0]->pict.data[1])[i] >> 24) == 0)
433 while (y1 < s->rects[0]->h && is_transp(s->rects[0]->pict.data[0] + y1 * s->rects[0]->pict.linesize[0],
434 1, s->rects[0]->w, transp_color))
436 if (y1 == s->rects[0]->h) {
437 av_freep(&s->rects[0]->pict.data[0]);
438 s->rects[0]->w = s->rects[0]->h = 0;
442 y2 = s->rects[0]->h - 1;
443 while (y2 > 0 && is_transp(s->rects[0]->pict.data[0] + y2 * s->rects[0]->pict.linesize[0], 1,
444 s->rects[0]->w, transp_color))
447 while (x1 < (s->rects[0]->w - 1) && is_transp(s->rects[0]->pict.data[0] + x1, s->rects[0]->pict.linesize[0],
448 s->rects[0]->h, transp_color))
450 x2 = s->rects[0]->w - 1;
451 while (x2 > 0 && is_transp(s->rects[0]->pict.data[0] + x2, s->rects[0]->pict.linesize[0], s->rects[0]->h,
456 bitmap = av_malloc(w * h);
459 for(y = 0; y < h; y++) {
460 memcpy(bitmap + w * y, s->rects[0]->pict.data[0] + x1 + (y1 + y) * s->rects[0]->pict.linesize[0], w);
462 av_freep(&s->rects[0]->pict.data[0]);
463 s->rects[0]->pict.data[0] = bitmap;
464 s->rects[0]->pict.linesize[0] = w;
467 s->rects[0]->x += x1;
468 s->rects[0]->y += y1;
473 #define ALPHA_MIX(A,BACK,FORE) (((255-(A)) * (BACK) + (A) * (FORE)) / 255)
474 static void ppm_save(const char *filename, uint8_t *bitmap, int w, int h,
475 uint32_t *rgba_palette)
479 int back[3] = {0, 255, 0}; /* green background */
482 f = fopen(filename, "w");
491 for(y = 0; y < h; y++) {
492 for(x = 0; x < w; x++) {
493 v = rgba_palette[bitmap[y * w + x]];
495 putc(ALPHA_MIX(alpha, back[0], (v >> 16) & 0xff), f);
496 putc(ALPHA_MIX(alpha, back[1], (v >> 8) & 0xff), f);
497 putc(ALPHA_MIX(alpha, back[2], (v >> 0) & 0xff), f);
504 static int append_to_cached_buf(AVCodecContext *avctx,
505 const uint8_t *buf, int buf_size)
507 DVDSubContext *ctx = avctx->priv_data;
509 if (ctx->buf_size > 0xffff - buf_size) {
510 av_log(avctx, AV_LOG_WARNING, "Attempt to reconstruct "
511 "too large SPU packets aborted.\n");
513 return AVERROR_INVALIDDATA;
515 ctx->buf = av_realloc(ctx->buf, ctx->buf_size + buf_size);
517 return AVERROR(ENOMEM);
518 memcpy(ctx->buf + ctx->buf_size, buf, buf_size);
519 ctx->buf_size += buf_size;
523 static int dvdsub_decode(AVCodecContext *avctx,
524 void *data, int *data_size,
527 DVDSubContext *ctx = avctx->priv_data;
528 const uint8_t *buf = avpkt->data;
529 int buf_size = avpkt->size;
530 AVSubtitle *sub = data;
534 int ret = append_to_cached_buf(avctx, buf, buf_size);
540 buf_size = ctx->buf_size;
543 is_menu = decode_dvd_subtitles(ctx, sub, buf, buf_size);
544 if (is_menu == AVERROR(EAGAIN)) {
546 return append_to_cached_buf(avctx, buf, buf_size);
556 if (!is_menu && find_smallest_bounding_rectangle(sub) == 0)
559 if (ctx->forced_subs_only && !(sub->rects[0]->flags & AV_SUBTITLE_FLAG_FORCED))
566 snprintf(ppm_name, sizeof(ppm_name), "/tmp/%05d.ppm", ctx->sub_id++);
567 av_dlog(NULL, "start=%d ms end =%d ms\n",
568 sub->start_display_time,
569 sub->end_display_time);
570 ppm_save(ppm_name, sub->rects[0]->pict.data[0],
571 sub->rects[0]->w, sub->rects[0]->h, (uint32_t*) sub->rects[0]->pict.data[1]);
581 static void parse_palette(DVDSubContext *ctx, char *p)
585 ctx->has_palette = 1;
587 ctx->palette[i] = strtoul(p, &p, 16);
588 while(*p == ',' || av_isspace(*p))
593 static int parse_ifo_palette(DVDSubContext *ctx, char *p)
597 uint32_t sp_pgci, pgci, off_pgc, pgc;
598 uint8_t r, g, b, yuv[65], *buf;
599 int i, y, cb, cr, r_add, g_add, b_add;
601 const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;
603 ctx->has_palette = 0;
604 if ((ifo = fopen(p, "r")) == NULL) {
605 av_log(ctx, AV_LOG_WARNING, "Unable to open IFO file \"%s\": %s\n", p, av_err2str(AVERROR(errno)));
608 if (fread(ifostr, 12, 1, ifo) != 1 || memcmp(ifostr, "DVDVIDEO-VTS", 12)) {
609 av_log(ctx, AV_LOG_WARNING, "\"%s\" is not a proper IFO file\n", p);
610 ret = AVERROR_INVALIDDATA;
613 if (fseek(ifo, 0xCC, SEEK_SET) == -1) {
614 ret = AVERROR(errno);
617 if (fread(&sp_pgci, 4, 1, ifo) == 1) {
618 pgci = av_be2ne32(sp_pgci) * 2048;
619 if (fseek(ifo, pgci + 0x0C, SEEK_SET) == -1) {
620 ret = AVERROR(errno);
623 if (fread(&off_pgc, 4, 1, ifo) == 1) {
624 pgc = pgci + av_be2ne32(off_pgc);
625 if (fseek(ifo, pgc + 0xA4, SEEK_SET) == -1) {
626 ret = AVERROR(errno);
629 if (fread(yuv, 64, 1, ifo) == 1) {
631 for(i=0; i<16; i++) {
635 YUV_TO_RGB1_CCIR(cb, cr);
636 YUV_TO_RGB2_CCIR(r, g, b, y);
637 ctx->palette[i] = (r << 16) + (g << 8) + b;
640 ctx->has_palette = 1;
644 if (ctx->has_palette == 0) {
645 av_log(ctx, AV_LOG_WARNING, "Failed to read palette from IFO file \"%s\"\n", p);
646 ret = AVERROR_INVALIDDATA;
653 static int dvdsub_parse_extradata(AVCodecContext *avctx)
655 DVDSubContext *ctx = (DVDSubContext*) avctx->priv_data;
656 char *dataorig, *data;
659 if (!avctx->extradata || !avctx->extradata_size)
662 dataorig = data = av_malloc(avctx->extradata_size+1);
664 return AVERROR(ENOMEM);
665 memcpy(data, avctx->extradata, avctx->extradata_size);
666 data[avctx->extradata_size] = '\0';
669 int pos = strcspn(data, "\n\r");
670 if (pos==0 && *data==0)
673 if (strncmp("palette:", data, 8) == 0) {
674 parse_palette(ctx, data + 8);
675 } else if (strncmp("size:", data, 5) == 0) {
677 if (sscanf(data + 5, "%dx%d", &w, &h) == 2) {
678 ret = ff_set_dimensions(avctx, w, h);
685 data += strspn(data, "\n\r");
693 static av_cold int dvdsub_init(AVCodecContext *avctx)
695 DVDSubContext *ctx = avctx->priv_data;
698 if ((ret = dvdsub_parse_extradata(avctx)) < 0)
702 parse_ifo_palette(ctx, ctx->ifo_str);
703 if (ctx->palette_str)
704 parse_palette(ctx, ctx->palette_str);
705 if (ctx->has_palette) {
707 av_log(avctx, AV_LOG_DEBUG, "palette:");
709 av_log(avctx, AV_LOG_DEBUG, " 0x%06x", ctx->palette[i]);
710 av_log(avctx, AV_LOG_DEBUG, "\n");
716 static av_cold int dvdsub_close(AVCodecContext *avctx)
718 DVDSubContext *ctx = avctx->priv_data;
724 #define OFFSET(field) offsetof(DVDSubContext, field)
725 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
726 static const AVOption options[] = {
727 { "palette", "set the global palette", OFFSET(palette_str), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, SD },
728 { "ifo_palette", "obtain the global palette from .IFO file", OFFSET(ifo_str), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, SD },
729 { "forced_subs_only", "Only show forced subtitles", OFFSET(forced_subs_only), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, SD},
732 static const AVClass dvdsub_class = {
733 .class_name = "dvdsubdec",
734 .item_name = av_default_item_name,
736 .version = LIBAVUTIL_VERSION_INT,
739 AVCodec ff_dvdsub_decoder = {
741 .long_name = NULL_IF_CONFIG_SMALL("DVD subtitles"),
742 .type = AVMEDIA_TYPE_SUBTITLE,
743 .id = AV_CODEC_ID_DVD_SUBTITLE,
744 .priv_data_size = sizeof(DVDSubContext),
746 .decode = dvdsub_decode,
747 .close = dvdsub_close,
748 .priv_class = &dvdsub_class,