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 if (w <= 0 || h <= 0)
117 bit_len = (buf_size - start) * 8;
118 init_get_bits(&gb, buf + start, bit_len);
124 if (get_bits_count(&gb) > bit_len)
127 len = decode_run_8bit(&gb, &color);
129 len = decode_run_2bit(&gb, &color);
130 len = FFMIN(len, w - x);
131 memset(d + x, color, len);
146 static void guess_palette(DVDSubContext* ctx,
147 uint32_t *rgba_palette,
148 uint32_t subtitle_color)
150 static const uint8_t level_map[4][4] = {
151 // this configuration (full range, lowest to highest) in tests
152 // seemed most common, so assume this
156 {0x00, 0x55, 0xaa, 0xff},
158 uint8_t color_used[16] = { 0 };
159 int nb_opaque_colors, i, level, j, r, g, b;
160 uint8_t *colormap = ctx->colormap, *alpha = ctx->alpha;
162 if(ctx->has_palette) {
163 for(i = 0; i < 4; i++)
164 rgba_palette[i] = (ctx->palette[colormap[i]] & 0x00ffffff)
165 | ((alpha[i] * 17U) << 24);
169 for(i = 0; i < 4; i++)
172 nb_opaque_colors = 0;
173 for(i = 0; i < 4; i++) {
174 if (alpha[i] != 0 && !color_used[colormap[i]]) {
175 color_used[colormap[i]] = 1;
180 if (nb_opaque_colors == 0)
184 memset(color_used, 0, 16);
185 for(i = 0; i < 4; i++) {
187 if (!color_used[colormap[i]]) {
188 level = level_map[nb_opaque_colors][j];
189 r = (((subtitle_color >> 16) & 0xff) * level) >> 8;
190 g = (((subtitle_color >> 8) & 0xff) * level) >> 8;
191 b = (((subtitle_color >> 0) & 0xff) * level) >> 8;
192 rgba_palette[i] = b | (g << 8) | (r << 16) | ((alpha[i] * 17) << 24);
193 color_used[colormap[i]] = (i + 1);
196 rgba_palette[i] = (rgba_palette[color_used[colormap[i]] - 1] & 0x00ffffff) |
197 ((alpha[i] * 17) << 24);
203 static void reset_rects(AVSubtitle *sub_header)
207 if (sub_header->rects) {
208 for (i = 0; i < sub_header->num_rects; i++) {
209 av_freep(&sub_header->rects[i]->pict.data[0]);
210 av_freep(&sub_header->rects[i]->pict.data[1]);
211 av_freep(&sub_header->rects[i]);
213 av_freep(&sub_header->rects);
214 sub_header->num_rects = 0;
218 #define READ_OFFSET(a) (big_offsets ? AV_RB32(a) : AV_RB16(a))
220 static int decode_dvd_subtitles(DVDSubContext *ctx, AVSubtitle *sub_header,
221 const uint8_t *buf, int buf_size)
223 int cmd_pos, pos, cmd, x1, y1, x2, y2, offset1, offset2, next_cmd_pos;
224 int big_offsets, offset_size, is_8bit = 0;
225 const uint8_t *yuv_palette = NULL;
226 uint8_t *colormap = ctx->colormap, *alpha = ctx->alpha;
234 if (AV_RB16(buf) == 0) { /* HD subpicture with 4-byte offsets */
244 cmd_pos = READ_OFFSET(buf + cmd_pos);
246 if (cmd_pos < 0 || cmd_pos > buf_size - 2 - offset_size)
247 return AVERROR(EAGAIN);
249 while (cmd_pos > 0 && cmd_pos < buf_size - 2 - offset_size) {
250 date = AV_RB16(buf + cmd_pos);
251 next_cmd_pos = READ_OFFSET(buf + cmd_pos + 2);
252 ff_dlog(NULL, "cmd_pos=0x%04x next=0x%04x date=%d\n",
253 cmd_pos, next_cmd_pos, date);
254 pos = cmd_pos + 2 + offset_size;
257 x1 = y1 = x2 = y2 = 0;
258 while (pos < buf_size) {
260 ff_dlog(NULL, "cmd=%02x\n", cmd);
263 /* menu subpicture */
268 sub_header->start_display_time = (date << 10) / 90;
272 sub_header->end_display_time = (date << 10) / 90;
276 if ((buf_size - pos) < 2)
278 colormap[3] = buf[pos] >> 4;
279 colormap[2] = buf[pos] & 0x0f;
280 colormap[1] = buf[pos + 1] >> 4;
281 colormap[0] = buf[pos + 1] & 0x0f;
286 if ((buf_size - pos) < 2)
288 alpha[3] = buf[pos] >> 4;
289 alpha[2] = buf[pos] & 0x0f;
290 alpha[1] = buf[pos + 1] >> 4;
291 alpha[0] = buf[pos + 1] & 0x0f;
293 ff_dlog(NULL, "alpha=%x%x%x%x\n", alpha[0],alpha[1],alpha[2],alpha[3]);
297 if ((buf_size - pos) < 6)
299 x1 = (buf[pos] << 4) | (buf[pos + 1] >> 4);
300 x2 = ((buf[pos + 1] & 0x0f) << 8) | buf[pos + 2];
301 y1 = (buf[pos + 3] << 4) | (buf[pos + 4] >> 4);
302 y2 = ((buf[pos + 4] & 0x0f) << 8) | buf[pos + 5];
305 ff_dlog(NULL, "x1=%d x2=%d y1=%d y2=%d\n", x1, x2, y1, y2);
309 if ((buf_size - pos) < 4)
311 offset1 = AV_RB16(buf + pos);
312 offset2 = AV_RB16(buf + pos + 2);
313 ff_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);
317 if ((buf_size - pos) < 8)
319 offset1 = AV_RB32(buf + pos);
320 offset2 = AV_RB32(buf + pos + 4);
321 ff_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);
327 if ((buf_size - pos) < 768)
329 yuv_palette = buf + pos;
333 /* HD set contrast (alpha) */
334 if ((buf_size - pos) < 256)
336 for (i = 0; i < 256; i++)
337 alpha[i] = 0xFF - buf[pos+i];
344 ff_dlog(NULL, "unrecognised subpicture command 0x%x\n", cmd);
353 /* decode the bitmap */
360 if (w > 0 && h > 0) {
361 reset_rects(sub_header);
363 sub_header->rects = av_mallocz(sizeof(*sub_header->rects));
364 if (!sub_header->rects)
366 sub_header->rects[0] = av_mallocz(sizeof(AVSubtitleRect));
367 if (!sub_header->rects[0])
369 sub_header->num_rects = 1;
370 bitmap = sub_header->rects[0]->pict.data[0] = av_malloc(w * h);
373 if (decode_rle(bitmap, w * 2, w, (h + 1) / 2,
374 buf, offset1, buf_size, is_8bit) < 0)
376 if (decode_rle(bitmap + w, w * 2, w, h / 2,
377 buf, offset2, buf_size, is_8bit) < 0)
379 sub_header->rects[0]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
380 if (!sub_header->rects[0]->pict.data[1])
385 sub_header->rects[0]->nb_colors = 256;
386 yuv_a_to_rgba(yuv_palette, alpha, (uint32_t*)sub_header->rects[0]->pict.data[1], 256);
388 sub_header->rects[0]->nb_colors = 4;
389 guess_palette(ctx, (uint32_t*)sub_header->rects[0]->pict.data[1],
392 sub_header->rects[0]->x = x1;
393 sub_header->rects[0]->y = y1;
394 sub_header->rects[0]->w = w;
395 sub_header->rects[0]->h = h;
396 sub_header->rects[0]->type = SUBTITLE_BITMAP;
397 sub_header->rects[0]->pict.linesize[0] = w;
398 sub_header->rects[0]->flags = is_menu ? AV_SUBTITLE_FLAG_FORCED : 0;
401 if (next_cmd_pos < cmd_pos) {
402 av_log(NULL, AV_LOG_ERROR, "Invalid command offset\n");
405 if (next_cmd_pos == cmd_pos)
407 cmd_pos = next_cmd_pos;
409 if (sub_header->num_rects > 0)
412 reset_rects(sub_header);
416 static int is_transp(const uint8_t *buf, int pitch, int n,
417 const uint8_t *transp_color)
420 for(i = 0; i < n; i++) {
421 if (!transp_color[*buf])
428 /* return 0 if empty rectangle, 1 if non empty */
429 static int find_smallest_bounding_rectangle(AVSubtitle *s)
431 uint8_t transp_color[256] = { 0 };
432 int y1, y2, x1, x2, y, w, h, i;
435 if (s->num_rects == 0 || !s->rects || s->rects[0]->w <= 0 || s->rects[0]->h <= 0)
438 for(i = 0; i < s->rects[0]->nb_colors; i++) {
439 if ((((uint32_t*)s->rects[0]->pict.data[1])[i] >> 24) == 0)
443 while (y1 < s->rects[0]->h && is_transp(s->rects[0]->pict.data[0] + y1 * s->rects[0]->pict.linesize[0],
444 1, s->rects[0]->w, transp_color))
446 if (y1 == s->rects[0]->h) {
447 av_freep(&s->rects[0]->pict.data[0]);
448 s->rects[0]->w = s->rects[0]->h = 0;
452 y2 = s->rects[0]->h - 1;
453 while (y2 > 0 && is_transp(s->rects[0]->pict.data[0] + y2 * s->rects[0]->pict.linesize[0], 1,
454 s->rects[0]->w, transp_color))
457 while (x1 < (s->rects[0]->w - 1) && is_transp(s->rects[0]->pict.data[0] + x1, s->rects[0]->pict.linesize[0],
458 s->rects[0]->h, transp_color))
460 x2 = s->rects[0]->w - 1;
461 while (x2 > 0 && is_transp(s->rects[0]->pict.data[0] + x2, s->rects[0]->pict.linesize[0], s->rects[0]->h,
466 bitmap = av_malloc(w * h);
469 for(y = 0; y < h; y++) {
470 memcpy(bitmap + w * y, s->rects[0]->pict.data[0] + x1 + (y1 + y) * s->rects[0]->pict.linesize[0], w);
472 av_freep(&s->rects[0]->pict.data[0]);
473 s->rects[0]->pict.data[0] = bitmap;
474 s->rects[0]->pict.linesize[0] = w;
477 s->rects[0]->x += x1;
478 s->rects[0]->y += y1;
483 #define ALPHA_MIX(A,BACK,FORE) (((255-(A)) * (BACK) + (A) * (FORE)) / 255)
484 static void ppm_save(const char *filename, uint8_t *bitmap, int w, int h,
485 uint32_t *rgba_palette)
489 int back[3] = {0, 255, 0}; /* green background */
492 f = fopen(filename, "w");
501 for(y = 0; y < h; y++) {
502 for(x = 0; x < w; x++) {
503 v = rgba_palette[bitmap[y * w + x]];
505 putc(ALPHA_MIX(alpha, back[0], (v >> 16) & 0xff), f);
506 putc(ALPHA_MIX(alpha, back[1], (v >> 8) & 0xff), f);
507 putc(ALPHA_MIX(alpha, back[2], (v >> 0) & 0xff), f);
514 static int append_to_cached_buf(AVCodecContext *avctx,
515 const uint8_t *buf, int buf_size)
517 DVDSubContext *ctx = avctx->priv_data;
519 if (ctx->buf_size >= sizeof(ctx->buf) - buf_size) {
520 av_log(avctx, AV_LOG_WARNING, "Attempt to reconstruct "
521 "too large SPU packets aborted.\n");
522 return AVERROR_INVALIDDATA;
524 memcpy(ctx->buf + ctx->buf_size, buf, buf_size);
525 ctx->buf_size += buf_size;
529 static int dvdsub_decode(AVCodecContext *avctx,
530 void *data, int *data_size,
533 DVDSubContext *ctx = avctx->priv_data;
534 const uint8_t *buf = avpkt->data;
535 int buf_size = avpkt->size;
536 AVSubtitle *sub = data;
540 int ret = append_to_cached_buf(avctx, buf, buf_size);
546 buf_size = ctx->buf_size;
549 is_menu = decode_dvd_subtitles(ctx, sub, buf, buf_size);
550 if (is_menu == AVERROR(EAGAIN)) {
552 return append_to_cached_buf(avctx, buf, buf_size);
562 if (!is_menu && find_smallest_bounding_rectangle(sub) == 0)
565 if (ctx->forced_subs_only && !(sub->rects[0]->flags & AV_SUBTITLE_FLAG_FORCED))
572 snprintf(ppm_name, sizeof(ppm_name), "/tmp/%05d.ppm", ctx->sub_id++);
573 ff_dlog(NULL, "start=%d ms end =%d ms\n",
574 sub->start_display_time,
575 sub->end_display_time);
576 ppm_save(ppm_name, sub->rects[0]->pict.data[0],
577 sub->rects[0]->w, sub->rects[0]->h, (uint32_t*) sub->rects[0]->pict.data[1]);
586 static void parse_palette(DVDSubContext *ctx, char *p)
590 ctx->has_palette = 1;
592 ctx->palette[i] = strtoul(p, &p, 16);
593 while(*p == ',' || av_isspace(*p))
598 static int parse_ifo_palette(DVDSubContext *ctx, char *p)
602 uint32_t sp_pgci, pgci, off_pgc, pgc;
603 uint8_t r, g, b, yuv[65], *buf;
604 int i, y, cb, cr, r_add, g_add, b_add;
606 const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;
608 ctx->has_palette = 0;
609 if ((ifo = fopen(p, "r")) == NULL) {
610 av_log(ctx, AV_LOG_WARNING, "Unable to open IFO file \"%s\": %s\n", p, av_err2str(AVERROR(errno)));
613 if (fread(ifostr, 12, 1, ifo) != 1 || memcmp(ifostr, "DVDVIDEO-VTS", 12)) {
614 av_log(ctx, AV_LOG_WARNING, "\"%s\" is not a proper IFO file\n", p);
615 ret = AVERROR_INVALIDDATA;
618 if (fseek(ifo, 0xCC, SEEK_SET) == -1) {
619 ret = AVERROR(errno);
622 if (fread(&sp_pgci, 4, 1, ifo) == 1) {
623 pgci = av_be2ne32(sp_pgci) * 2048;
624 if (fseek(ifo, pgci + 0x0C, SEEK_SET) == -1) {
625 ret = AVERROR(errno);
628 if (fread(&off_pgc, 4, 1, ifo) == 1) {
629 pgc = pgci + av_be2ne32(off_pgc);
630 if (fseek(ifo, pgc + 0xA4, SEEK_SET) == -1) {
631 ret = AVERROR(errno);
634 if (fread(yuv, 64, 1, ifo) == 1) {
636 for(i=0; i<16; i++) {
640 YUV_TO_RGB1_CCIR(cb, cr);
641 YUV_TO_RGB2_CCIR(r, g, b, y);
642 ctx->palette[i] = (r << 16) + (g << 8) + b;
645 ctx->has_palette = 1;
649 if (ctx->has_palette == 0) {
650 av_log(ctx, AV_LOG_WARNING, "Failed to read palette from IFO file \"%s\"\n", p);
651 ret = AVERROR_INVALIDDATA;
658 static int dvdsub_parse_extradata(AVCodecContext *avctx)
660 DVDSubContext *ctx = (DVDSubContext*) avctx->priv_data;
661 char *dataorig, *data;
664 if (!avctx->extradata || !avctx->extradata_size)
667 dataorig = data = av_malloc(avctx->extradata_size+1);
669 return AVERROR(ENOMEM);
670 memcpy(data, avctx->extradata, avctx->extradata_size);
671 data[avctx->extradata_size] = '\0';
674 int pos = strcspn(data, "\n\r");
675 if (pos==0 && *data==0)
678 if (strncmp("palette:", data, 8) == 0) {
679 parse_palette(ctx, data + 8);
680 } else if (strncmp("size:", data, 5) == 0) {
682 if (sscanf(data + 5, "%dx%d", &w, &h) == 2) {
683 ret = ff_set_dimensions(avctx, w, h);
690 data += strspn(data, "\n\r");
698 static av_cold int dvdsub_init(AVCodecContext *avctx)
700 DVDSubContext *ctx = avctx->priv_data;
703 if ((ret = dvdsub_parse_extradata(avctx)) < 0)
707 parse_ifo_palette(ctx, ctx->ifo_str);
708 if (ctx->palette_str)
709 parse_palette(ctx, ctx->palette_str);
710 if (ctx->has_palette) {
712 av_log(avctx, AV_LOG_DEBUG, "palette:");
714 av_log(avctx, AV_LOG_DEBUG, " 0x%06x", ctx->palette[i]);
715 av_log(avctx, AV_LOG_DEBUG, "\n");
721 static av_cold int dvdsub_close(AVCodecContext *avctx)
723 DVDSubContext *ctx = avctx->priv_data;
728 #define OFFSET(field) offsetof(DVDSubContext, field)
729 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
730 static const AVOption options[] = {
731 { "palette", "set the global palette", OFFSET(palette_str), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, SD },
732 { "ifo_palette", "obtain the global palette from .IFO file", OFFSET(ifo_str), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, SD },
733 { "forced_subs_only", "Only show forced subtitles", OFFSET(forced_subs_only), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, SD},
736 static const AVClass dvdsub_class = {
737 .class_name = "dvdsubdec",
738 .item_name = av_default_item_name,
740 .version = LIBAVUTIL_VERSION_INT,
743 AVCodec ff_dvdsub_decoder = {
745 .long_name = NULL_IF_CONFIG_SMALL("DVD subtitles"),
746 .type = AVMEDIA_TYPE_SUBTITLE,
747 .id = AV_CODEC_ID_DVD_SUBTITLE,
748 .priv_data_size = sizeof(DVDSubContext),
750 .decode = dvdsub_decode,
751 .close = dvdsub_close,
752 .priv_class = &dvdsub_class,