]> git.sesse.net Git - ffmpeg/blob - libavcodec/dvdsubdec.c
Merge commit 'ffba2053edfc177d217bf4a95edf51cd0fc40753'
[ffmpeg] / libavcodec / dvdsubdec.c
1 /*
2  * DVD subtitle decoding
3  * Copyright (c) 2005 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21 #include "avcodec.h"
22 #include "get_bits.h"
23 #include "dsputil.h"
24 #include "libavutil/attributes.h"
25 #include "libavutil/colorspace.h"
26 #include "libavutil/opt.h"
27 #include "libavutil/imgutils.h"
28 #include "libavutil/avstring.h"
29
30 //#define DEBUG
31
32 typedef struct DVDSubContext
33 {
34   AVClass *class;
35   uint32_t palette[16];
36   char    *palette_str;
37   int      has_palette;
38   uint8_t  colormap[4];
39   uint8_t  alpha[256];
40 } DVDSubContext;
41
42 static void yuv_a_to_rgba(const uint8_t *ycbcr, const uint8_t *alpha, uint32_t *rgba, int num_values)
43 {
44     const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
45     uint8_t r, g, b;
46     int i, y, cb, cr;
47     int r_add, g_add, b_add;
48
49     for (i = num_values; i > 0; i--) {
50         y = *ycbcr++;
51         cr = *ycbcr++;
52         cb = *ycbcr++;
53         YUV_TO_RGB1_CCIR(cb, cr);
54         YUV_TO_RGB2_CCIR(r, g, b, y);
55         *rgba++ = (*alpha++ << 24) | (r << 16) | (g << 8) | b;
56     }
57 }
58
59 static int decode_run_2bit(GetBitContext *gb, int *color)
60 {
61     unsigned int v, t;
62
63     v = 0;
64     for (t = 1; v < t && t <= 0x40; t <<= 2)
65         v = (v << 4) | get_bits(gb, 4);
66     *color = v & 3;
67     if (v < 4) { /* Code for fill rest of line */
68         return INT_MAX;
69     }
70     return v >> 2;
71 }
72
73 static int decode_run_8bit(GetBitContext *gb, int *color)
74 {
75     int len;
76     int has_run = get_bits1(gb);
77     if (get_bits1(gb))
78         *color = get_bits(gb, 8);
79     else
80         *color = get_bits(gb, 2);
81     if (has_run) {
82         if (get_bits1(gb)) {
83             len = get_bits(gb, 7);
84             if (len == 0)
85                 len = INT_MAX;
86             else
87                 len += 9;
88         } else
89             len = get_bits(gb, 3) + 2;
90     } else
91         len = 1;
92     return len;
93 }
94
95 static int decode_rle(uint8_t *bitmap, int linesize, int w, int h,
96                       const uint8_t *buf, int start, int buf_size, int is_8bit)
97 {
98     GetBitContext gb;
99     int bit_len;
100     int x, y, len, color;
101     uint8_t *d;
102
103     bit_len = (buf_size - start) * 8;
104     init_get_bits(&gb, buf + start, bit_len);
105
106     x = 0;
107     y = 0;
108     d = bitmap;
109     for(;;) {
110         if (get_bits_count(&gb) > bit_len)
111             return -1;
112         if (is_8bit)
113             len = decode_run_8bit(&gb, &color);
114         else
115             len = decode_run_2bit(&gb, &color);
116         len = FFMIN(len, w - x);
117         memset(d + x, color, len);
118         x += len;
119         if (x >= w) {
120             y++;
121             if (y >= h)
122                 break;
123             d += linesize;
124             x = 0;
125             /* byte align */
126             align_get_bits(&gb);
127         }
128     }
129     return 0;
130 }
131
132 static void guess_palette(DVDSubContext* ctx,
133                           uint32_t *rgba_palette,
134                           uint32_t subtitle_color)
135 {
136     static const uint8_t level_map[4][4] = {
137         // this configuration (full range, lowest to highest) in tests
138         // seemed most common, so assume this
139         {0xff},
140         {0x00, 0xff},
141         {0x00, 0x80, 0xff},
142         {0x00, 0x55, 0xaa, 0xff},
143     };
144     uint8_t color_used[16] = { 0 };
145     int nb_opaque_colors, i, level, j, r, g, b;
146     uint8_t *colormap = ctx->colormap, *alpha = ctx->alpha;
147
148     if(ctx->has_palette) {
149         for(i = 0; i < 4; i++)
150             rgba_palette[i] = (ctx->palette[colormap[i]] & 0x00ffffff)
151                               | ((alpha[i] * 17U) << 24);
152         return;
153     }
154
155     for(i = 0; i < 4; i++)
156         rgba_palette[i] = 0;
157
158     nb_opaque_colors = 0;
159     for(i = 0; i < 4; i++) {
160         if (alpha[i] != 0 && !color_used[colormap[i]]) {
161             color_used[colormap[i]] = 1;
162             nb_opaque_colors++;
163         }
164     }
165
166     if (nb_opaque_colors == 0)
167         return;
168
169     j = 0;
170     memset(color_used, 0, 16);
171     for(i = 0; i < 4; i++) {
172         if (alpha[i] != 0) {
173             if (!color_used[colormap[i]])  {
174                 level = level_map[nb_opaque_colors][j];
175                 r = (((subtitle_color >> 16) & 0xff) * level) >> 8;
176                 g = (((subtitle_color >> 8) & 0xff) * level) >> 8;
177                 b = (((subtitle_color >> 0) & 0xff) * level) >> 8;
178                 rgba_palette[i] = b | (g << 8) | (r << 16) | ((alpha[i] * 17) << 24);
179                 color_used[colormap[i]] = (i + 1);
180                 j++;
181             } else {
182                 rgba_palette[i] = (rgba_palette[color_used[colormap[i]] - 1] & 0x00ffffff) |
183                                     ((alpha[i] * 17) << 24);
184             }
185         }
186     }
187 }
188
189 #define READ_OFFSET(a) (big_offsets ? AV_RB32(a) : AV_RB16(a))
190
191 static int decode_dvd_subtitles(DVDSubContext *ctx, AVSubtitle *sub_header,
192                                 const uint8_t *buf, int buf_size)
193 {
194     int cmd_pos, pos, cmd, x1, y1, x2, y2, offset1, offset2, next_cmd_pos;
195     int big_offsets, offset_size, is_8bit = 0;
196     const uint8_t *yuv_palette = 0;
197     uint8_t *colormap = ctx->colormap, *alpha = ctx->alpha;
198     int date;
199     int i;
200     int is_menu = 0;
201
202     if (buf_size < 10)
203         return -1;
204
205     if (AV_RB16(buf) == 0) {   /* HD subpicture with 4-byte offsets */
206         big_offsets = 1;
207         offset_size = 4;
208         cmd_pos = 6;
209     } else {
210         big_offsets = 0;
211         offset_size = 2;
212         cmd_pos = 2;
213     }
214
215     cmd_pos = READ_OFFSET(buf + cmd_pos);
216
217     while (cmd_pos > 0 && cmd_pos < buf_size - 2 - offset_size) {
218         date = AV_RB16(buf + cmd_pos);
219         next_cmd_pos = READ_OFFSET(buf + cmd_pos + 2);
220         av_dlog(NULL, "cmd_pos=0x%04x next=0x%04x date=%d\n",
221                 cmd_pos, next_cmd_pos, date);
222         pos = cmd_pos + 2 + offset_size;
223         offset1 = -1;
224         offset2 = -1;
225         x1 = y1 = x2 = y2 = 0;
226         while (pos < buf_size) {
227             cmd = buf[pos++];
228             av_dlog(NULL, "cmd=%02x\n", cmd);
229             switch(cmd) {
230             case 0x00:
231                 /* menu subpicture */
232                 is_menu = 1;
233                 break;
234             case 0x01:
235                 /* set start date */
236                 sub_header->start_display_time = (date << 10) / 90;
237                 break;
238             case 0x02:
239                 /* set end date */
240                 sub_header->end_display_time = (date << 10) / 90;
241                 break;
242             case 0x03:
243                 /* set colormap */
244                 if ((buf_size - pos) < 2)
245                     goto fail;
246                 colormap[3] = buf[pos] >> 4;
247                 colormap[2] = buf[pos] & 0x0f;
248                 colormap[1] = buf[pos + 1] >> 4;
249                 colormap[0] = buf[pos + 1] & 0x0f;
250                 pos += 2;
251                 break;
252             case 0x04:
253                 /* set alpha */
254                 if ((buf_size - pos) < 2)
255                     goto fail;
256                 alpha[3] = buf[pos] >> 4;
257                 alpha[2] = buf[pos] & 0x0f;
258                 alpha[1] = buf[pos + 1] >> 4;
259                 alpha[0] = buf[pos + 1] & 0x0f;
260                 pos += 2;
261             av_dlog(NULL, "alpha=%x%x%x%x\n", alpha[0],alpha[1],alpha[2],alpha[3]);
262                 break;
263             case 0x05:
264             case 0x85:
265                 if ((buf_size - pos) < 6)
266                     goto fail;
267                 x1 = (buf[pos] << 4) | (buf[pos + 1] >> 4);
268                 x2 = ((buf[pos + 1] & 0x0f) << 8) | buf[pos + 2];
269                 y1 = (buf[pos + 3] << 4) | (buf[pos + 4] >> 4);
270                 y2 = ((buf[pos + 4] & 0x0f) << 8) | buf[pos + 5];
271                 if (cmd & 0x80)
272                     is_8bit = 1;
273                 av_dlog(NULL, "x1=%d x2=%d y1=%d y2=%d\n", x1, x2, y1, y2);
274                 pos += 6;
275                 break;
276             case 0x06:
277                 if ((buf_size - pos) < 4)
278                     goto fail;
279                 offset1 = AV_RB16(buf + pos);
280                 offset2 = AV_RB16(buf + pos + 2);
281                 av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);
282                 pos += 4;
283                 break;
284             case 0x86:
285                 if ((buf_size - pos) < 8)
286                     goto fail;
287                 offset1 = AV_RB32(buf + pos);
288                 offset2 = AV_RB32(buf + pos + 4);
289                 av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);
290                 pos += 8;
291                 break;
292
293             case 0x83:
294                 /* HD set palette */
295                 if ((buf_size - pos) < 768)
296                     goto fail;
297                 yuv_palette = buf + pos;
298                 pos += 768;
299                 break;
300             case 0x84:
301                 /* HD set contrast (alpha) */
302                 if ((buf_size - pos) < 256)
303                     goto fail;
304                 for (i = 0; i < 256; i++)
305                     alpha[i] = 0xFF - buf[pos+i];
306                 pos += 256;
307                 break;
308
309             case 0xff:
310                 goto the_end;
311             default:
312                 av_dlog(NULL, "unrecognised subpicture command 0x%x\n", cmd);
313                 goto the_end;
314             }
315         }
316     the_end:
317         if (offset1 >= 0) {
318             int w, h;
319             uint8_t *bitmap;
320
321             /* decode the bitmap */
322             w = x2 - x1 + 1;
323             if (w < 0)
324                 w = 0;
325             h = y2 - y1;
326             if (h < 0)
327                 h = 0;
328             if (w > 0 && h > 0) {
329                 if (sub_header->rects != NULL) {
330                     for (i = 0; i < sub_header->num_rects; i++) {
331                         av_freep(&sub_header->rects[i]->pict.data[0]);
332                         av_freep(&sub_header->rects[i]->pict.data[1]);
333                         av_freep(&sub_header->rects[i]);
334                     }
335                     av_freep(&sub_header->rects);
336                     sub_header->num_rects = 0;
337                 }
338
339                 bitmap = av_malloc(w * h);
340                 sub_header->rects = av_mallocz(sizeof(*sub_header->rects));
341                 sub_header->rects[0] = av_mallocz(sizeof(AVSubtitleRect));
342                 sub_header->num_rects = 1;
343                 sub_header->rects[0]->pict.data[0] = bitmap;
344                 decode_rle(bitmap, w * 2, w, (h + 1) / 2,
345                            buf, offset1, buf_size, is_8bit);
346                 decode_rle(bitmap + w, w * 2, w, h / 2,
347                            buf, offset2, buf_size, is_8bit);
348                 sub_header->rects[0]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
349                 if (is_8bit) {
350                     if (yuv_palette == 0)
351                         goto fail;
352                     sub_header->rects[0]->nb_colors = 256;
353                     yuv_a_to_rgba(yuv_palette, alpha, (uint32_t*)sub_header->rects[0]->pict.data[1], 256);
354                 } else {
355                     sub_header->rects[0]->nb_colors = 4;
356                     guess_palette(ctx, (uint32_t*)sub_header->rects[0]->pict.data[1],
357                                   0xffff00);
358                 }
359                 sub_header->rects[0]->x = x1;
360                 sub_header->rects[0]->y = y1;
361                 sub_header->rects[0]->w = w;
362                 sub_header->rects[0]->h = h;
363                 sub_header->rects[0]->type = SUBTITLE_BITMAP;
364                 sub_header->rects[0]->pict.linesize[0] = w;
365                 sub_header->rects[0]->flags = is_menu ? AV_SUBTITLE_FLAG_FORCED : 0;
366             }
367         }
368         if (next_cmd_pos < cmd_pos) {
369             av_log(NULL, AV_LOG_ERROR, "Invalid command offset\n");
370             break;
371         }
372         if (next_cmd_pos == cmd_pos)
373             break;
374         cmd_pos = next_cmd_pos;
375     }
376     if (sub_header->num_rects > 0)
377         return is_menu;
378  fail:
379     if (sub_header->rects != NULL) {
380         for (i = 0; i < sub_header->num_rects; i++) {
381             av_freep(&sub_header->rects[i]->pict.data[0]);
382             av_freep(&sub_header->rects[i]->pict.data[1]);
383             av_freep(&sub_header->rects[i]);
384         }
385         av_freep(&sub_header->rects);
386         sub_header->num_rects = 0;
387     }
388     return -1;
389 }
390
391 static int is_transp(const uint8_t *buf, int pitch, int n,
392                      const uint8_t *transp_color)
393 {
394     int i;
395     for(i = 0; i < n; i++) {
396         if (!transp_color[*buf])
397             return 0;
398         buf += pitch;
399     }
400     return 1;
401 }
402
403 /* return 0 if empty rectangle, 1 if non empty */
404 static int find_smallest_bounding_rectangle(AVSubtitle *s)
405 {
406     uint8_t transp_color[256] = { 0 };
407     int y1, y2, x1, x2, y, w, h, i;
408     uint8_t *bitmap;
409
410     if (s->num_rects == 0 || s->rects == NULL || s->rects[0]->w <= 0 || s->rects[0]->h <= 0)
411         return 0;
412
413     for(i = 0; i < s->rects[0]->nb_colors; i++) {
414         if ((((uint32_t*)s->rects[0]->pict.data[1])[i] >> 24) == 0)
415             transp_color[i] = 1;
416     }
417     y1 = 0;
418     while (y1 < s->rects[0]->h && is_transp(s->rects[0]->pict.data[0] + y1 * s->rects[0]->pict.linesize[0],
419                                   1, s->rects[0]->w, transp_color))
420         y1++;
421     if (y1 == s->rects[0]->h) {
422         av_freep(&s->rects[0]->pict.data[0]);
423         s->rects[0]->w = s->rects[0]->h = 0;
424         return 0;
425     }
426
427     y2 = s->rects[0]->h - 1;
428     while (y2 > 0 && is_transp(s->rects[0]->pict.data[0] + y2 * s->rects[0]->pict.linesize[0], 1,
429                                s->rects[0]->w, transp_color))
430         y2--;
431     x1 = 0;
432     while (x1 < (s->rects[0]->w - 1) && is_transp(s->rects[0]->pict.data[0] + x1, s->rects[0]->pict.linesize[0],
433                                         s->rects[0]->h, transp_color))
434         x1++;
435     x2 = s->rects[0]->w - 1;
436     while (x2 > 0 && is_transp(s->rects[0]->pict.data[0] + x2, s->rects[0]->pict.linesize[0], s->rects[0]->h,
437                                   transp_color))
438         x2--;
439     w = x2 - x1 + 1;
440     h = y2 - y1 + 1;
441     bitmap = av_malloc(w * h);
442     if (!bitmap)
443         return 1;
444     for(y = 0; y < h; y++) {
445         memcpy(bitmap + w * y, s->rects[0]->pict.data[0] + x1 + (y1 + y) * s->rects[0]->pict.linesize[0], w);
446     }
447     av_freep(&s->rects[0]->pict.data[0]);
448     s->rects[0]->pict.data[0] = bitmap;
449     s->rects[0]->pict.linesize[0] = w;
450     s->rects[0]->w = w;
451     s->rects[0]->h = h;
452     s->rects[0]->x += x1;
453     s->rects[0]->y += y1;
454     return 1;
455 }
456
457 #ifdef DEBUG
458 #undef fprintf
459 #undef perror
460 #undef exit
461 static void ppm_save(const char *filename, uint8_t *bitmap, int w, int h,
462                      uint32_t *rgba_palette)
463 {
464     int x, y, v;
465     FILE *f;
466
467     f = fopen(filename, "w");
468     if (!f) {
469         perror(filename);
470         exit(1);
471     }
472     fprintf(f, "P6\n"
473             "%d %d\n"
474             "%d\n",
475             w, h, 255);
476     for(y = 0; y < h; y++) {
477         for(x = 0; x < w; x++) {
478             v = rgba_palette[bitmap[y * w + x]];
479             putc((v >> 16) & 0xff, f);
480             putc((v >> 8) & 0xff, f);
481             putc((v >> 0) & 0xff, f);
482         }
483     }
484     fclose(f);
485 }
486 #endif
487
488 static int dvdsub_decode(AVCodecContext *avctx,
489                          void *data, int *data_size,
490                          AVPacket *avpkt)
491 {
492     DVDSubContext *ctx = avctx->priv_data;
493     const uint8_t *buf = avpkt->data;
494     int buf_size = avpkt->size;
495     AVSubtitle *sub = data;
496     int is_menu;
497
498     is_menu = decode_dvd_subtitles(ctx, sub, buf, buf_size);
499
500     if (is_menu < 0) {
501     no_subtitle:
502         *data_size = 0;
503
504         return buf_size;
505     }
506     if (!is_menu && find_smallest_bounding_rectangle(sub) == 0)
507         goto no_subtitle;
508
509 #if defined(DEBUG)
510     av_dlog(NULL, "start=%d ms end =%d ms\n",
511             sub->start_display_time,
512             sub->end_display_time);
513     ppm_save("/tmp/a.ppm", sub->rects[0]->pict.data[0],
514              sub->rects[0]->w, sub->rects[0]->h, sub->rects[0]->pict.data[1]);
515 #endif
516
517     *data_size = 1;
518     return buf_size;
519 }
520
521 static void parse_palette(DVDSubContext *ctx, char *p)
522 {
523     int i;
524
525     ctx->has_palette = 1;
526     for(i=0;i<16;i++) {
527         ctx->palette[i] = strtoul(p, &p, 16);
528         while(*p == ',' || av_isspace(*p))
529             p++;
530     }
531 }
532
533 static int dvdsub_parse_extradata(AVCodecContext *avctx)
534 {
535     DVDSubContext *ctx = (DVDSubContext*) avctx->priv_data;
536     char *dataorig, *data;
537
538     if (!avctx->extradata || !avctx->extradata_size)
539         return 1;
540
541     dataorig = data = av_malloc(avctx->extradata_size+1);
542     if (!data)
543         return AVERROR(ENOMEM);
544     memcpy(data, avctx->extradata, avctx->extradata_size);
545     data[avctx->extradata_size] = '\0';
546
547     for(;;) {
548         int pos = strcspn(data, "\n\r");
549         if (pos==0 && *data==0)
550             break;
551
552         if (strncmp("palette:", data, 8) == 0) {
553             parse_palette(ctx, data + 8);
554         } else if (strncmp("size:", data, 5) == 0) {
555             int w, h;
556             if (sscanf(data + 5, "%dx%d", &w, &h) == 2 &&
557                 av_image_check_size(w, h, 0, avctx) >= 0)
558                 avcodec_set_dimensions(avctx, w, h);
559         }
560
561         data += pos;
562         data += strspn(data, "\n\r");
563     }
564
565     av_free(dataorig);
566     return 1;
567 }
568
569 static av_cold int dvdsub_init(AVCodecContext *avctx)
570 {
571     DVDSubContext *ctx = avctx->priv_data;
572     int ret;
573
574     if ((ret = dvdsub_parse_extradata(avctx)) < 0)
575         return ret;
576
577     if (ctx->palette_str)
578         parse_palette(ctx, ctx->palette_str);
579     if (ctx->has_palette) {
580         int i;
581         av_log(avctx, AV_LOG_DEBUG, "palette:");
582         for(i=0;i<16;i++)
583             av_log(avctx, AV_LOG_DEBUG, " 0x%06x", ctx->palette[i]);
584         av_log(avctx, AV_LOG_DEBUG, "\n");
585     }
586
587     return 1;
588 }
589
590 #define OFFSET(field) offsetof(DVDSubContext, field)
591 #define VD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
592 static const AVOption options[] = {
593     { "palette", "set the global palette", OFFSET(palette_str), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
594     { NULL }
595 };
596 static const AVClass class = {
597     .class_name = "dvdsubdec",
598     .item_name  = av_default_item_name,
599     .option     = options,
600     .version    = LIBAVUTIL_VERSION_INT,
601 };
602
603 AVCodec ff_dvdsub_decoder = {
604     .name           = "dvdsub",
605     .type           = AVMEDIA_TYPE_SUBTITLE,
606     .id             = AV_CODEC_ID_DVD_SUBTITLE,
607     .priv_data_size = sizeof(DVDSubContext),
608     .init           = dvdsub_init,
609     .decode         = dvdsub_decode,
610     .long_name      = NULL_IF_CONFIG_SMALL("DVD subtitles"),
611     .priv_class     = &class,
612 };