]> git.sesse.net Git - ffmpeg/blob - libavcodec/dvdsubdec.c
avcodec/dvdsubdec: Avoid branch in decode_run_8bit()
[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
22 #include "avcodec.h"
23 #include "get_bits.h"
24 #include "internal.h"
25
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"
32
33 typedef struct DVDSubContext
34 {
35   AVClass *class;
36   uint32_t palette[16];
37   char    *palette_str;
38   char    *ifo_str;
39   int      has_palette;
40   uint8_t  colormap[4];
41   uint8_t  alpha[256];
42   uint8_t  buf[0x10000];
43   int      buf_size;
44   int      forced_subs_only;
45   uint8_t  used_color[256];
46 #ifdef DEBUG
47   int sub_id;
48 #endif
49 } DVDSubContext;
50
51 static void yuv_a_to_rgba(const uint8_t *ycbcr, const uint8_t *alpha, uint32_t *rgba, int num_values)
52 {
53     const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;
54     uint8_t r, g, b;
55     int i, y, cb, cr;
56     int r_add, g_add, b_add;
57
58     for (i = num_values; i > 0; i--) {
59         y = *ycbcr++;
60         cr = *ycbcr++;
61         cb = *ycbcr++;
62         YUV_TO_RGB1_CCIR(cb, cr);
63         YUV_TO_RGB2_CCIR(r, g, b, y);
64         *rgba++ = ((unsigned)*alpha++ << 24) | (r << 16) | (g << 8) | b;
65     }
66 }
67
68 static int decode_run_2bit(GetBitContext *gb, int *color)
69 {
70     unsigned int v, t;
71
72     v = 0;
73     for (t = 1; v < t && t <= 0x40; t <<= 2)
74         v = (v << 4) | get_bits(gb, 4);
75     *color = v & 3;
76     if (v < 4) { /* Code for fill rest of line */
77         return INT_MAX;
78     }
79     return v >> 2;
80 }
81
82 static int decode_run_8bit(GetBitContext *gb, int *color)
83 {
84     int len;
85     int has_run = get_bits1(gb);
86     *color = get_bits(gb, 2 + 6*get_bits1(gb));
87     if (has_run) {
88         if (get_bits1(gb)) {
89             len = get_bits(gb, 7);
90             if (len == 0)
91                 len = INT_MAX;
92             else
93                 len += 9;
94         } else
95             len = get_bits(gb, 3) + 2;
96     } else
97         len = 1;
98     return len;
99 }
100
101 static int decode_rle(uint8_t *bitmap, int linesize, int w, int h, uint8_t used_color[256],
102                       const uint8_t *buf, int start, int buf_size, int is_8bit)
103 {
104     GetBitContext gb;
105     int bit_len;
106     int x, y, len, color;
107     uint8_t *d;
108
109     if (start >= buf_size)
110         return -1;
111
112     if (w <= 0 || h <= 0)
113         return -1;
114
115     bit_len = (buf_size - start) * 8;
116     init_get_bits(&gb, buf + start, bit_len);
117
118     x = 0;
119     y = 0;
120     d = bitmap;
121     for(;;) {
122         if (get_bits_count(&gb) > bit_len)
123             return -1;
124         if (is_8bit)
125             len = decode_run_8bit(&gb, &color);
126         else
127             len = decode_run_2bit(&gb, &color);
128         len = FFMIN(len, w - x);
129         memset(d + x, color, len);
130         used_color[color] = 1;
131         x += len;
132         if (x >= w) {
133             y++;
134             if (y >= h)
135                 break;
136             d += linesize;
137             x = 0;
138             /* byte align */
139             align_get_bits(&gb);
140         }
141     }
142     return 0;
143 }
144
145 static void guess_palette(DVDSubContext* ctx,
146                           uint32_t *rgba_palette,
147                           uint32_t subtitle_color)
148 {
149     static const uint8_t level_map[4][4] = {
150         // this configuration (full range, lowest to highest) in tests
151         // seemed most common, so assume this
152         {0xff},
153         {0x00, 0xff},
154         {0x00, 0x80, 0xff},
155         {0x00, 0x55, 0xaa, 0xff},
156     };
157     uint8_t color_used[16] = { 0 };
158     int nb_opaque_colors, i, level, j, r, g, b;
159     uint8_t *colormap = ctx->colormap, *alpha = ctx->alpha;
160
161     if(ctx->has_palette) {
162         for(i = 0; i < 4; i++)
163             rgba_palette[i] = (ctx->palette[colormap[i]] & 0x00ffffff)
164                               | ((alpha[i] * 17U) << 24);
165         return;
166     }
167
168     for(i = 0; i < 4; i++)
169         rgba_palette[i] = 0;
170
171     nb_opaque_colors = 0;
172     for(i = 0; i < 4; i++) {
173         if (alpha[i] != 0 && !color_used[colormap[i]]) {
174             color_used[colormap[i]] = 1;
175             nb_opaque_colors++;
176         }
177     }
178
179     if (nb_opaque_colors == 0)
180         return;
181
182     j = 0;
183     memset(color_used, 0, 16);
184     for(i = 0; i < 4; i++) {
185         if (alpha[i] != 0) {
186             if (!color_used[colormap[i]])  {
187                 level = level_map[nb_opaque_colors - 1][j];
188                 r = (((subtitle_color >> 16) & 0xff) * level) >> 8;
189                 g = (((subtitle_color >> 8) & 0xff) * level) >> 8;
190                 b = (((subtitle_color >> 0) & 0xff) * level) >> 8;
191                 rgba_palette[i] = b | (g << 8) | (r << 16) | ((alpha[i] * 17U) << 24);
192                 color_used[colormap[i]] = (i + 1);
193                 j++;
194             } else {
195                 rgba_palette[i] = (rgba_palette[color_used[colormap[i]] - 1] & 0x00ffffff) |
196                                     ((alpha[i] * 17U) << 24);
197             }
198         }
199     }
200 }
201
202 static void reset_rects(AVSubtitle *sub_header)
203 {
204     int i;
205
206     if (sub_header->rects) {
207         for (i = 0; i < sub_header->num_rects; i++) {
208             av_freep(&sub_header->rects[i]->data[0]);
209             av_freep(&sub_header->rects[i]->data[1]);
210             av_freep(&sub_header->rects[i]);
211         }
212         av_freep(&sub_header->rects);
213         sub_header->num_rects = 0;
214     }
215 }
216
217 #define READ_OFFSET(a) (big_offsets ? AV_RB32(a) : AV_RB16(a))
218
219 static int decode_dvd_subtitles(DVDSubContext *ctx, AVSubtitle *sub_header,
220                                 const uint8_t *buf, int buf_size)
221 {
222     int cmd_pos, pos, cmd, x1, y1, x2, y2, next_cmd_pos;
223     int big_offsets, offset_size, is_8bit = 0;
224     const uint8_t *yuv_palette = NULL;
225     uint8_t *colormap = ctx->colormap, *alpha = ctx->alpha;
226     int date;
227     int i;
228     int is_menu = 0;
229     uint32_t size;
230     int64_t offset1, offset2;
231
232     if (buf_size < 10)
233         return -1;
234
235     if (AV_RB16(buf) == 0) {   /* HD subpicture with 4-byte offsets */
236         big_offsets = 1;
237         offset_size = 4;
238         cmd_pos = 6;
239     } else {
240         big_offsets = 0;
241         offset_size = 2;
242         cmd_pos = 2;
243     }
244
245     size = READ_OFFSET(buf + (big_offsets ? 2 : 0));
246     cmd_pos = READ_OFFSET(buf + cmd_pos);
247
248     if (cmd_pos < 0 || cmd_pos > buf_size - 2 - offset_size) {
249         if (cmd_pos > size) {
250             av_log(ctx, AV_LOG_ERROR, "Discarding invalid packet\n");
251             return 0;
252         }
253         return AVERROR(EAGAIN);
254     }
255
256     while (cmd_pos > 0 && cmd_pos < buf_size - 2 - offset_size) {
257         date = AV_RB16(buf + cmd_pos);
258         next_cmd_pos = READ_OFFSET(buf + cmd_pos + 2);
259         ff_dlog(NULL, "cmd_pos=0x%04x next=0x%04x date=%d\n",
260                 cmd_pos, next_cmd_pos, date);
261         pos = cmd_pos + 2 + offset_size;
262         offset1 = -1;
263         offset2 = -1;
264         x1 = y1 = x2 = y2 = 0;
265         while (pos < buf_size) {
266             cmd = buf[pos++];
267             ff_dlog(NULL, "cmd=%02x\n", cmd);
268             switch(cmd) {
269             case 0x00:
270                 /* menu subpicture */
271                 is_menu = 1;
272                 break;
273             case 0x01:
274                 /* set start date */
275                 sub_header->start_display_time = (date << 10) / 90;
276                 break;
277             case 0x02:
278                 /* set end date */
279                 sub_header->end_display_time = (date << 10) / 90;
280                 break;
281             case 0x03:
282                 /* set colormap */
283                 if ((buf_size - pos) < 2)
284                     goto fail;
285                 colormap[3] = buf[pos] >> 4;
286                 colormap[2] = buf[pos] & 0x0f;
287                 colormap[1] = buf[pos + 1] >> 4;
288                 colormap[0] = buf[pos + 1] & 0x0f;
289                 pos += 2;
290                 break;
291             case 0x04:
292                 /* set alpha */
293                 if ((buf_size - pos) < 2)
294                     goto fail;
295                 alpha[3] = buf[pos] >> 4;
296                 alpha[2] = buf[pos] & 0x0f;
297                 alpha[1] = buf[pos + 1] >> 4;
298                 alpha[0] = buf[pos + 1] & 0x0f;
299                 pos += 2;
300                 ff_dlog(NULL, "alpha=%x%x%x%x\n", alpha[0],alpha[1],alpha[2],alpha[3]);
301                 break;
302             case 0x05:
303             case 0x85:
304                 if ((buf_size - pos) < 6)
305                     goto fail;
306                 x1 = (buf[pos] << 4) | (buf[pos + 1] >> 4);
307                 x2 = ((buf[pos + 1] & 0x0f) << 8) | buf[pos + 2];
308                 y1 = (buf[pos + 3] << 4) | (buf[pos + 4] >> 4);
309                 y2 = ((buf[pos + 4] & 0x0f) << 8) | buf[pos + 5];
310                 if (cmd & 0x80)
311                     is_8bit = 1;
312                 ff_dlog(NULL, "x1=%d x2=%d y1=%d y2=%d\n", x1, x2, y1, y2);
313                 pos += 6;
314                 break;
315             case 0x06:
316                 if ((buf_size - pos) < 4)
317                     goto fail;
318                 offset1 = AV_RB16(buf + pos);
319                 offset2 = AV_RB16(buf + pos + 2);
320                 ff_dlog(NULL, "offset1=0x%04"PRIx64" offset2=0x%04"PRIx64"\n", offset1, offset2);
321                 pos += 4;
322                 break;
323             case 0x86:
324                 if ((buf_size - pos) < 8)
325                     goto fail;
326                 offset1 = AV_RB32(buf + pos);
327                 offset2 = AV_RB32(buf + pos + 4);
328                 ff_dlog(NULL, "offset1=0x%04"PRIx64" offset2=0x%04"PRIx64"\n", offset1, offset2);
329                 pos += 8;
330                 break;
331
332             case 0x83:
333                 /* HD set palette */
334                 if ((buf_size - pos) < 768)
335                     goto fail;
336                 yuv_palette = buf + pos;
337                 pos += 768;
338                 break;
339             case 0x84:
340                 /* HD set contrast (alpha) */
341                 if ((buf_size - pos) < 256)
342                     goto fail;
343                 for (i = 0; i < 256; i++)
344                     alpha[i] = 0xFF - buf[pos+i];
345                 pos += 256;
346                 break;
347
348             case 0xff:
349                 goto the_end;
350             default:
351                 ff_dlog(NULL, "unrecognised subpicture command 0x%x\n", cmd);
352                 goto the_end;
353             }
354         }
355     the_end:
356         if (offset1 >= buf_size || offset2 >= buf_size)
357             goto fail;
358
359         if (offset1 >= 0 && offset2 >= 0) {
360             int w, h;
361             uint8_t *bitmap;
362
363             /* decode the bitmap */
364             w = x2 - x1 + 1;
365             if (w < 0)
366                 w = 0;
367             h = y2 - y1 + 1;
368             if (h < 0)
369                 h = 0;
370             if (w > 0 && h > 1) {
371                 reset_rects(sub_header);
372                 memset(ctx->used_color, 0, sizeof(ctx->used_color));
373                 sub_header->rects = av_mallocz(sizeof(*sub_header->rects));
374                 if (!sub_header->rects)
375                     goto fail;
376                 sub_header->rects[0] = av_mallocz(sizeof(AVSubtitleRect));
377                 if (!sub_header->rects[0])
378                     goto fail;
379                 sub_header->num_rects = 1;
380                 bitmap = sub_header->rects[0]->data[0] = av_malloc(w * h);
381                 if (!bitmap)
382                     goto fail;
383                 if (decode_rle(bitmap, w * 2, w, (h + 1) / 2, ctx->used_color,
384                                buf, offset1, buf_size, is_8bit) < 0)
385                     goto fail;
386                 if (decode_rle(bitmap + w, w * 2, w, h / 2, ctx->used_color,
387                                buf, offset2, buf_size, is_8bit) < 0)
388                     goto fail;
389                 sub_header->rects[0]->data[1] = av_mallocz(AVPALETTE_SIZE);
390                 if (!sub_header->rects[0]->data[1])
391                     goto fail;
392                 if (is_8bit) {
393                     if (!yuv_palette)
394                         goto fail;
395                     sub_header->rects[0]->nb_colors = 256;
396                     yuv_a_to_rgba(yuv_palette, alpha,
397                                   (uint32_t *)sub_header->rects[0]->data[1],
398                                   256);
399                 } else {
400                     sub_header->rects[0]->nb_colors = 4;
401                     guess_palette(ctx, (uint32_t*)sub_header->rects[0]->data[1],
402                                   0xffff00);
403                 }
404                 sub_header->rects[0]->x = x1;
405                 sub_header->rects[0]->y = y1;
406                 sub_header->rects[0]->w = w;
407                 sub_header->rects[0]->h = h;
408                 sub_header->rects[0]->type = SUBTITLE_BITMAP;
409                 sub_header->rects[0]->linesize[0] = w;
410                 sub_header->rects[0]->flags = is_menu ? AV_SUBTITLE_FLAG_FORCED : 0;
411
412 #if FF_API_AVPICTURE
413 FF_DISABLE_DEPRECATION_WARNINGS
414                 for (i = 0; i < 4; i++) {
415                     sub_header->rects[0]->pict.data[i] = sub_header->rects[0]->data[i];
416                     sub_header->rects[0]->pict.linesize[i] = sub_header->rects[0]->linesize[i];
417                 }
418 FF_ENABLE_DEPRECATION_WARNINGS
419 #endif
420             }
421         }
422         if (next_cmd_pos < cmd_pos) {
423             av_log(ctx, AV_LOG_ERROR, "Invalid command offset\n");
424             break;
425         }
426         if (next_cmd_pos == cmd_pos)
427             break;
428         cmd_pos = next_cmd_pos;
429     }
430     if (sub_header->num_rects > 0)
431         return is_menu;
432  fail:
433     reset_rects(sub_header);
434     return -1;
435 }
436
437 static int is_transp(const uint8_t *buf, int pitch, int n,
438                      const uint8_t *transp_color)
439 {
440     int i;
441     for(i = 0; i < n; i++) {
442         if (!transp_color[*buf])
443             return 0;
444         buf += pitch;
445     }
446     return 1;
447 }
448
449 /* return 0 if empty rectangle, 1 if non empty */
450 static int find_smallest_bounding_rectangle(DVDSubContext *ctx, AVSubtitle *s)
451 {
452     uint8_t transp_color[256] = { 0 };
453     int y1, y2, x1, x2, y, w, h, i;
454     uint8_t *bitmap;
455     int transparent = 1;
456
457     if (s->num_rects == 0 || !s->rects || s->rects[0]->w <= 0 || s->rects[0]->h <= 0)
458         return 0;
459
460     for(i = 0; i < s->rects[0]->nb_colors; i++) {
461         if ((((uint32_t *)s->rects[0]->data[1])[i] >> 24) == 0) {
462             transp_color[i] = 1;
463         } else if (ctx->used_color[i])
464             transparent = 0;
465     }
466     if (transparent)
467         return 0;
468     y1 = 0;
469     while (y1 < s->rects[0]->h && is_transp(s->rects[0]->data[0] + y1 * s->rects[0]->linesize[0],
470                                   1, s->rects[0]->w, transp_color))
471         y1++;
472     if (y1 == s->rects[0]->h) {
473         av_freep(&s->rects[0]->data[0]);
474         s->rects[0]->w = s->rects[0]->h = 0;
475         return 0;
476     }
477
478     y2 = s->rects[0]->h - 1;
479     while (y2 > 0 && is_transp(s->rects[0]->data[0] + y2 * s->rects[0]->linesize[0], 1,
480                                s->rects[0]->w, transp_color))
481         y2--;
482     x1 = 0;
483     while (x1 < (s->rects[0]->w - 1) && is_transp(s->rects[0]->data[0] + x1, s->rects[0]->linesize[0],
484                                         s->rects[0]->h, transp_color))
485         x1++;
486     x2 = s->rects[0]->w - 1;
487     while (x2 > 0 && is_transp(s->rects[0]->data[0] + x2, s->rects[0]->linesize[0], s->rects[0]->h,
488                                   transp_color))
489         x2--;
490     w = x2 - x1 + 1;
491     h = y2 - y1 + 1;
492     bitmap = av_malloc(w * h);
493     if (!bitmap)
494         return 1;
495     for(y = 0; y < h; y++) {
496         memcpy(bitmap + w * y, s->rects[0]->data[0] + x1 + (y1 + y) * s->rects[0]->linesize[0], w);
497     }
498     av_freep(&s->rects[0]->data[0]);
499     s->rects[0]->data[0] = bitmap;
500     s->rects[0]->linesize[0] = w;
501     s->rects[0]->w = w;
502     s->rects[0]->h = h;
503     s->rects[0]->x += x1;
504     s->rects[0]->y += y1;
505
506 #if FF_API_AVPICTURE
507 FF_DISABLE_DEPRECATION_WARNINGS
508     for (i = 0; i < 4; i++) {
509         s->rects[0]->pict.data[i] = s->rects[0]->data[i];
510         s->rects[0]->pict.linesize[i] = s->rects[0]->linesize[i];
511     }
512 FF_ENABLE_DEPRECATION_WARNINGS
513 #endif
514
515     return 1;
516 }
517
518 #ifdef DEBUG
519 #define ALPHA_MIX(A,BACK,FORE) (((255-(A)) * (BACK) + (A) * (FORE)) / 255)
520 static void ppm_save(const char *filename, uint8_t *bitmap, int w, int h,
521                      uint32_t *rgba_palette)
522 {
523     int x, y, alpha;
524     uint32_t v;
525     int back[3] = {0, 255, 0};  /* green background */
526     FILE *f;
527
528     f = fopen(filename, "w");
529     if (!f) {
530         perror(filename);
531         return;
532     }
533     fprintf(f, "P6\n"
534             "%d %d\n"
535             "%d\n",
536             w, h, 255);
537     for(y = 0; y < h; y++) {
538         for(x = 0; x < w; x++) {
539             v = rgba_palette[bitmap[y * w + x]];
540             alpha = v >> 24;
541             putc(ALPHA_MIX(alpha, back[0], (v >> 16) & 0xff), f);
542             putc(ALPHA_MIX(alpha, back[1], (v >> 8) & 0xff), f);
543             putc(ALPHA_MIX(alpha, back[2], (v >> 0) & 0xff), f);
544         }
545     }
546     fclose(f);
547 }
548 #endif
549
550 static int append_to_cached_buf(AVCodecContext *avctx,
551                                 const uint8_t *buf, int buf_size)
552 {
553     DVDSubContext *ctx = avctx->priv_data;
554
555     av_assert0(buf_size >= 0 && ctx->buf_size <= sizeof(ctx->buf));
556     if (buf_size >= sizeof(ctx->buf) - ctx->buf_size) {
557         av_log(avctx, AV_LOG_WARNING, "Attempt to reconstruct "
558                "too large SPU packets aborted.\n");
559         ctx->buf_size = 0;
560         return AVERROR_INVALIDDATA;
561     }
562     memcpy(ctx->buf + ctx->buf_size, buf, buf_size);
563     ctx->buf_size += buf_size;
564     return 0;
565 }
566
567 static int dvdsub_decode(AVCodecContext *avctx,
568                          void *data, int *data_size,
569                          AVPacket *avpkt)
570 {
571     DVDSubContext *ctx = avctx->priv_data;
572     const uint8_t *buf = avpkt->data;
573     int buf_size = avpkt->size;
574     AVSubtitle *sub = data;
575     int appended = 0;
576     int is_menu;
577
578     if (ctx->buf_size) {
579         int ret = append_to_cached_buf(avctx, buf, buf_size);
580         if (ret < 0) {
581             *data_size = 0;
582             return ret;
583         }
584         buf = ctx->buf;
585         buf_size = ctx->buf_size;
586         appended = 1;
587     }
588
589     is_menu = decode_dvd_subtitles(ctx, sub, buf, buf_size);
590     if (is_menu == AVERROR(EAGAIN)) {
591         *data_size = 0;
592         return appended ? 0 : append_to_cached_buf(avctx, buf, buf_size);
593     }
594
595     if (is_menu < 0) {
596     no_subtitle:
597         reset_rects(sub);
598         *data_size = 0;
599
600         return buf_size;
601     }
602     if (!is_menu && find_smallest_bounding_rectangle(ctx, sub) == 0)
603         goto no_subtitle;
604
605     if (ctx->forced_subs_only && !(sub->rects[0]->flags & AV_SUBTITLE_FLAG_FORCED))
606         goto no_subtitle;
607
608 #if defined(DEBUG)
609     {
610     char ppm_name[32];
611
612     snprintf(ppm_name, sizeof(ppm_name), "/tmp/%05d.ppm", ctx->sub_id++);
613     ff_dlog(NULL, "start=%d ms end =%d ms\n",
614             sub->start_display_time,
615             sub->end_display_time);
616     ppm_save(ppm_name, sub->rects[0]->data[0],
617              sub->rects[0]->w, sub->rects[0]->h, (uint32_t*) sub->rects[0]->data[1]);
618     }
619 #endif
620
621     ctx->buf_size = 0;
622     *data_size = 1;
623     return buf_size;
624 }
625
626 static void parse_palette(DVDSubContext *ctx, char *p)
627 {
628     int i;
629
630     ctx->has_palette = 1;
631     for(i=0;i<16;i++) {
632         ctx->palette[i] = strtoul(p, &p, 16);
633         while(*p == ',' || av_isspace(*p))
634             p++;
635     }
636 }
637
638 static int parse_ifo_palette(DVDSubContext *ctx, char *p)
639 {
640     FILE *ifo;
641     char ifostr[12];
642     uint32_t sp_pgci, pgci, off_pgc, pgc;
643     uint8_t r, g, b, yuv[65], *buf;
644     int i, y, cb, cr, r_add, g_add, b_add;
645     int ret = 0;
646     const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;
647
648     ctx->has_palette = 0;
649     if ((ifo = fopen(p, "r")) == NULL) {
650         av_log(ctx, AV_LOG_WARNING, "Unable to open IFO file \"%s\": %s\n", p, av_err2str(AVERROR(errno)));
651         return AVERROR_EOF;
652     }
653     if (fread(ifostr, 12, 1, ifo) != 1 || memcmp(ifostr, "DVDVIDEO-VTS", 12)) {
654         av_log(ctx, AV_LOG_WARNING, "\"%s\" is not a proper IFO file\n", p);
655         ret = AVERROR_INVALIDDATA;
656         goto end;
657     }
658     if (fseek(ifo, 0xCC, SEEK_SET) == -1) {
659         ret = AVERROR(errno);
660         goto end;
661     }
662     if (fread(&sp_pgci, 4, 1, ifo) == 1) {
663         pgci = av_be2ne32(sp_pgci) * 2048;
664         if (fseek(ifo, pgci + 0x0C, SEEK_SET) == -1) {
665             ret = AVERROR(errno);
666             goto end;
667         }
668         if (fread(&off_pgc, 4, 1, ifo) == 1) {
669             pgc = pgci + av_be2ne32(off_pgc);
670             if (fseek(ifo, pgc + 0xA4, SEEK_SET) == -1) {
671                 ret = AVERROR(errno);
672                 goto end;
673             }
674             if (fread(yuv, 64, 1, ifo) == 1) {
675                 buf = yuv;
676                 for(i=0; i<16; i++) {
677                     y  = *++buf;
678                     cr = *++buf;
679                     cb = *++buf;
680                     YUV_TO_RGB1_CCIR(cb, cr);
681                     YUV_TO_RGB2_CCIR(r, g, b, y);
682                     ctx->palette[i] = (r << 16) + (g << 8) + b;
683                     buf++;
684                 }
685                 ctx->has_palette = 1;
686             }
687         }
688     }
689     if (ctx->has_palette == 0) {
690         av_log(ctx, AV_LOG_WARNING, "Failed to read palette from IFO file \"%s\"\n", p);
691         ret = AVERROR_INVALIDDATA;
692     }
693 end:
694     fclose(ifo);
695     return ret;
696 }
697
698 static int dvdsub_parse_extradata(AVCodecContext *avctx)
699 {
700     DVDSubContext *ctx = (DVDSubContext*) avctx->priv_data;
701     char *dataorig, *data;
702     int ret = 1;
703
704     if (!avctx->extradata || !avctx->extradata_size)
705         return 1;
706
707     dataorig = data = av_malloc(avctx->extradata_size+1);
708     if (!data)
709         return AVERROR(ENOMEM);
710     memcpy(data, avctx->extradata, avctx->extradata_size);
711     data[avctx->extradata_size] = '\0';
712
713     for(;;) {
714         int pos = strcspn(data, "\n\r");
715         if (pos==0 && *data==0)
716             break;
717
718         if (strncmp("palette:", data, 8) == 0) {
719             parse_palette(ctx, data + 8);
720         } else if (strncmp("size:", data, 5) == 0) {
721             int w, h;
722             if (sscanf(data + 5, "%dx%d", &w, &h) == 2) {
723                ret = ff_set_dimensions(avctx, w, h);
724                if (ret < 0)
725                    goto fail;
726             }
727         }
728
729         data += pos;
730         data += strspn(data, "\n\r");
731     }
732
733 fail:
734     av_free(dataorig);
735     return ret;
736 }
737
738 static av_cold int dvdsub_init(AVCodecContext *avctx)
739 {
740     DVDSubContext *ctx = avctx->priv_data;
741     int ret;
742
743     if ((ret = dvdsub_parse_extradata(avctx)) < 0)
744         return ret;
745
746     if (ctx->ifo_str)
747         parse_ifo_palette(ctx, ctx->ifo_str);
748     if (ctx->palette_str)
749         parse_palette(ctx, ctx->palette_str);
750     if (ctx->has_palette) {
751         int i;
752         av_log(avctx, AV_LOG_DEBUG, "palette:");
753         for(i=0;i<16;i++)
754             av_log(avctx, AV_LOG_DEBUG, " 0x%06"PRIx32, ctx->palette[i]);
755         av_log(avctx, AV_LOG_DEBUG, "\n");
756     }
757
758     return 1;
759 }
760
761 static void dvdsub_flush(AVCodecContext *avctx)
762 {
763     DVDSubContext *ctx = avctx->priv_data;
764     ctx->buf_size = 0;
765 }
766
767 static av_cold int dvdsub_close(AVCodecContext *avctx)
768 {
769     dvdsub_flush(avctx);
770     return 0;
771 }
772
773 #define OFFSET(field) offsetof(DVDSubContext, field)
774 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
775 static const AVOption options[] = {
776     { "palette", "set the global palette", OFFSET(palette_str), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, SD },
777     { "ifo_palette", "obtain the global palette from .IFO file", OFFSET(ifo_str), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, SD },
778     { "forced_subs_only", "Only show forced subtitles", OFFSET(forced_subs_only), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, SD},
779     { NULL }
780 };
781 static const AVClass dvdsub_class = {
782     .class_name = "dvdsubdec",
783     .item_name  = av_default_item_name,
784     .option     = options,
785     .version    = LIBAVUTIL_VERSION_INT,
786 };
787
788 AVCodec ff_dvdsub_decoder = {
789     .name           = "dvdsub",
790     .long_name      = NULL_IF_CONFIG_SMALL("DVD subtitles"),
791     .type           = AVMEDIA_TYPE_SUBTITLE,
792     .id             = AV_CODEC_ID_DVD_SUBTITLE,
793     .priv_data_size = sizeof(DVDSubContext),
794     .init           = dvdsub_init,
795     .decode         = dvdsub_decode,
796     .flush          = dvdsub_flush,
797     .close          = dvdsub_close,
798     .priv_class     = &dvdsub_class,
799 };