]> git.sesse.net Git - ffmpeg/blob - libavcodec/dvbsubdec.c
Merge commit '5cc0057f4910c8c72421b812c8f337ef6c43696c'
[ffmpeg] / libavcodec / dvbsubdec.c
1 /*
2  * DVB subtitle decoding
3  * Copyright (c) 2005 Ian Caulfield
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 "bytestream.h"
25 #include "internal.h"
26 #include "libavutil/colorspace.h"
27 #include "libavutil/opt.h"
28
29 #define DVBSUB_PAGE_SEGMENT     0x10
30 #define DVBSUB_REGION_SEGMENT   0x11
31 #define DVBSUB_CLUT_SEGMENT     0x12
32 #define DVBSUB_OBJECT_SEGMENT   0x13
33 #define DVBSUB_DISPLAYDEFINITION_SEGMENT 0x14
34 #define DVBSUB_DISPLAY_SEGMENT  0x80
35
36 #define cm (ff_crop_tab + MAX_NEG_CROP)
37
38 #ifdef DEBUG
39 static void png_save(const char *filename, uint32_t *bitmap, int w, int h)
40 {
41     int x, y, v;
42     FILE *f;
43     char fname[40], fname2[40];
44     char command[1024];
45
46     snprintf(fname, sizeof(fname), "%s.ppm", filename);
47
48     f = fopen(fname, "w");
49     if (!f) {
50         perror(fname);
51         return;
52     }
53     fprintf(f, "P6\n"
54             "%d %d\n"
55             "%d\n",
56             w, h, 255);
57     for(y = 0; y < h; y++) {
58         for(x = 0; x < w; x++) {
59             v = bitmap[y * w + x];
60             putc((v >> 16) & 0xff, f);
61             putc((v >> 8) & 0xff, f);
62             putc((v >> 0) & 0xff, f);
63         }
64     }
65     fclose(f);
66
67
68     snprintf(fname2, sizeof(fname2), "%s-a.pgm", filename);
69
70     f = fopen(fname2, "w");
71     if (!f) {
72         perror(fname2);
73         return;
74     }
75     fprintf(f, "P5\n"
76             "%d %d\n"
77             "%d\n",
78             w, h, 255);
79     for(y = 0; y < h; y++) {
80         for(x = 0; x < w; x++) {
81             v = bitmap[y * w + x];
82             putc((v >> 24) & 0xff, f);
83         }
84     }
85     fclose(f);
86
87     snprintf(command, sizeof(command), "pnmtopng -alpha %s %s > %s.png 2> /dev/null", fname2, fname, filename);
88     system(command);
89
90     snprintf(command, sizeof(command), "rm %s %s", fname, fname2);
91     system(command);
92 }
93 #endif
94
95 #define RGBA(r,g,b,a) (((unsigned)(a) << 24) | ((r) << 16) | ((g) << 8) | (b))
96
97 typedef struct DVBSubCLUT {
98     int id;
99     int version;
100
101     uint32_t clut4[4];
102     uint32_t clut16[16];
103     uint32_t clut256[256];
104
105     struct DVBSubCLUT *next;
106 } DVBSubCLUT;
107
108 static DVBSubCLUT default_clut;
109
110 typedef struct DVBSubObjectDisplay {
111     int object_id;
112     int region_id;
113
114     int x_pos;
115     int y_pos;
116
117     int fgcolor;
118     int bgcolor;
119
120     struct DVBSubObjectDisplay *region_list_next;
121     struct DVBSubObjectDisplay *object_list_next;
122 } DVBSubObjectDisplay;
123
124 typedef struct DVBSubObject {
125     int id;
126     int version;
127
128     int type;
129
130     DVBSubObjectDisplay *display_list;
131
132     struct DVBSubObject *next;
133 } DVBSubObject;
134
135 typedef struct DVBSubRegionDisplay {
136     int region_id;
137
138     int x_pos;
139     int y_pos;
140
141     struct DVBSubRegionDisplay *next;
142 } DVBSubRegionDisplay;
143
144 typedef struct DVBSubRegion {
145     int id;
146     int version;
147
148     int width;
149     int height;
150     int depth;
151
152     int clut;
153     int bgcolor;
154
155     uint8_t *pbuf;
156     int buf_size;
157     int dirty;
158
159     DVBSubObjectDisplay *display_list;
160
161     struct DVBSubRegion *next;
162 } DVBSubRegion;
163
164 typedef struct DVBSubDisplayDefinition {
165     int version;
166
167     int x;
168     int y;
169     int width;
170     int height;
171 } DVBSubDisplayDefinition;
172
173 typedef struct DVBSubContext {
174     AVClass *class;
175     int composition_id;
176     int ancillary_id;
177
178     int version;
179     int time_out;
180     int compute_edt; /**< if 1 end display time calculated using pts
181                           if 0 (Default) calculated using time out */
182     int compute_clut;
183     int substream;
184     int64_t prev_start;
185     DVBSubRegion *region_list;
186     DVBSubCLUT   *clut_list;
187     DVBSubObject *object_list;
188
189     DVBSubRegionDisplay *display_list;
190     DVBSubDisplayDefinition *display_definition;
191 } DVBSubContext;
192
193
194 static DVBSubObject* get_object(DVBSubContext *ctx, int object_id)
195 {
196     DVBSubObject *ptr = ctx->object_list;
197
198     while (ptr && ptr->id != object_id) {
199         ptr = ptr->next;
200     }
201
202     return ptr;
203 }
204
205 static DVBSubCLUT* get_clut(DVBSubContext *ctx, int clut_id)
206 {
207     DVBSubCLUT *ptr = ctx->clut_list;
208
209     while (ptr && ptr->id != clut_id) {
210         ptr = ptr->next;
211     }
212
213     return ptr;
214 }
215
216 static DVBSubRegion* get_region(DVBSubContext *ctx, int region_id)
217 {
218     DVBSubRegion *ptr = ctx->region_list;
219
220     while (ptr && ptr->id != region_id) {
221         ptr = ptr->next;
222     }
223
224     return ptr;
225 }
226
227 static void delete_region_display_list(DVBSubContext *ctx, DVBSubRegion *region)
228 {
229     DVBSubObject *object, *obj2, **obj2_ptr;
230     DVBSubObjectDisplay *display, *obj_disp, **obj_disp_ptr;
231
232     while (region->display_list) {
233         display = region->display_list;
234
235         object = get_object(ctx, display->object_id);
236
237         if (object) {
238             obj_disp_ptr = &object->display_list;
239             obj_disp = *obj_disp_ptr;
240
241             while (obj_disp && obj_disp != display) {
242                 obj_disp_ptr = &obj_disp->object_list_next;
243                 obj_disp = *obj_disp_ptr;
244             }
245
246             if (obj_disp) {
247                 *obj_disp_ptr = obj_disp->object_list_next;
248
249                 if (!object->display_list) {
250                     obj2_ptr = &ctx->object_list;
251                     obj2 = *obj2_ptr;
252
253                     while (obj2 != object) {
254                         av_assert0(obj2);
255                         obj2_ptr = &obj2->next;
256                         obj2 = *obj2_ptr;
257                     }
258
259                     *obj2_ptr = obj2->next;
260
261                     av_freep(&obj2);
262                 }
263             }
264         }
265
266         region->display_list = display->region_list_next;
267
268         av_freep(&display);
269     }
270
271 }
272
273 static void delete_cluts(DVBSubContext *ctx)
274 {
275     while (ctx->clut_list) {
276         DVBSubCLUT *clut = ctx->clut_list;
277
278         ctx->clut_list = clut->next;
279
280         av_freep(&clut);
281     }
282 }
283
284 static void delete_objects(DVBSubContext *ctx)
285 {
286     while (ctx->object_list) {
287         DVBSubObject *object = ctx->object_list;
288
289         ctx->object_list = object->next;
290
291         av_freep(&object);
292     }
293 }
294
295 static void delete_regions(DVBSubContext *ctx)
296 {
297     while (ctx->region_list) {
298         DVBSubRegion *region = ctx->region_list;
299
300         ctx->region_list = region->next;
301
302         delete_region_display_list(ctx, region);
303
304         av_freep(&region->pbuf);
305         av_freep(&region);
306     }
307 }
308
309 static av_cold int dvbsub_init_decoder(AVCodecContext *avctx)
310 {
311     int i, r, g, b, a = 0;
312     DVBSubContext *ctx = avctx->priv_data;
313
314     if (ctx->substream < 0) {
315         ctx->composition_id = -1;
316         ctx->ancillary_id   = -1;
317     } else if (!avctx->extradata || (avctx->extradata_size < 4) || ((avctx->extradata_size % 5 != 0) && (avctx->extradata_size != 4))) {
318         av_log(avctx, AV_LOG_WARNING, "Invalid DVB subtitles stream extradata!\n");
319         ctx->composition_id = -1;
320         ctx->ancillary_id   = -1;
321     } else {
322         if (avctx->extradata_size > 5*ctx->substream + 2) {
323             ctx->composition_id = AV_RB16(avctx->extradata + 5*ctx->substream);
324             ctx->ancillary_id   = AV_RB16(avctx->extradata + 5*ctx->substream + 2);
325         } else {
326             av_log(avctx, AV_LOG_WARNING, "Selected DVB subtitles sub-stream %d is not available\n", ctx->substream);
327             ctx->composition_id = AV_RB16(avctx->extradata);
328             ctx->ancillary_id   = AV_RB16(avctx->extradata + 2);
329         }
330     }
331
332     ctx->version = -1;
333     ctx->prev_start = AV_NOPTS_VALUE;
334
335     default_clut.id = -1;
336     default_clut.next = NULL;
337
338     default_clut.clut4[0] = RGBA(  0,   0,   0,   0);
339     default_clut.clut4[1] = RGBA(255, 255, 255, 255);
340     default_clut.clut4[2] = RGBA(  0,   0,   0, 255);
341     default_clut.clut4[3] = RGBA(127, 127, 127, 255);
342
343     default_clut.clut16[0] = RGBA(  0,   0,   0,   0);
344     for (i = 1; i < 16; i++) {
345         if (i < 8) {
346             r = (i & 1) ? 255 : 0;
347             g = (i & 2) ? 255 : 0;
348             b = (i & 4) ? 255 : 0;
349         } else {
350             r = (i & 1) ? 127 : 0;
351             g = (i & 2) ? 127 : 0;
352             b = (i & 4) ? 127 : 0;
353         }
354         default_clut.clut16[i] = RGBA(r, g, b, 255);
355     }
356
357     default_clut.clut256[0] = RGBA(  0,   0,   0,   0);
358     for (i = 1; i < 256; i++) {
359         if (i < 8) {
360             r = (i & 1) ? 255 : 0;
361             g = (i & 2) ? 255 : 0;
362             b = (i & 4) ? 255 : 0;
363             a = 63;
364         } else {
365             switch (i & 0x88) {
366             case 0x00:
367                 r = ((i & 1) ? 85 : 0) + ((i & 0x10) ? 170 : 0);
368                 g = ((i & 2) ? 85 : 0) + ((i & 0x20) ? 170 : 0);
369                 b = ((i & 4) ? 85 : 0) + ((i & 0x40) ? 170 : 0);
370                 a = 255;
371                 break;
372             case 0x08:
373                 r = ((i & 1) ? 85 : 0) + ((i & 0x10) ? 170 : 0);
374                 g = ((i & 2) ? 85 : 0) + ((i & 0x20) ? 170 : 0);
375                 b = ((i & 4) ? 85 : 0) + ((i & 0x40) ? 170 : 0);
376                 a = 127;
377                 break;
378             case 0x80:
379                 r = 127 + ((i & 1) ? 43 : 0) + ((i & 0x10) ? 85 : 0);
380                 g = 127 + ((i & 2) ? 43 : 0) + ((i & 0x20) ? 85 : 0);
381                 b = 127 + ((i & 4) ? 43 : 0) + ((i & 0x40) ? 85 : 0);
382                 a = 255;
383                 break;
384             case 0x88:
385                 r = ((i & 1) ? 43 : 0) + ((i & 0x10) ? 85 : 0);
386                 g = ((i & 2) ? 43 : 0) + ((i & 0x20) ? 85 : 0);
387                 b = ((i & 4) ? 43 : 0) + ((i & 0x40) ? 85 : 0);
388                 a = 255;
389                 break;
390             }
391         }
392         default_clut.clut256[i] = RGBA(r, g, b, a);
393     }
394
395     return 0;
396 }
397
398 static av_cold int dvbsub_close_decoder(AVCodecContext *avctx)
399 {
400     DVBSubContext *ctx = avctx->priv_data;
401     DVBSubRegionDisplay *display;
402
403     delete_regions(ctx);
404
405     delete_objects(ctx);
406
407     delete_cluts(ctx);
408
409     av_freep(&ctx->display_definition);
410
411     while (ctx->display_list) {
412         display = ctx->display_list;
413         ctx->display_list = display->next;
414
415         av_freep(&display);
416     }
417
418     return 0;
419 }
420
421 static int dvbsub_read_2bit_string(AVCodecContext *avctx,
422                                    uint8_t *destbuf, int dbuf_len,
423                                    const uint8_t **srcbuf, int buf_size,
424                                    int non_mod, uint8_t *map_table, int x_pos)
425 {
426     GetBitContext gb;
427
428     int bits;
429     int run_length;
430     int pixels_read = x_pos;
431
432     init_get_bits(&gb, *srcbuf, buf_size << 3);
433
434     destbuf += x_pos;
435
436     while (get_bits_count(&gb) < buf_size << 3 && pixels_read < dbuf_len) {
437         bits = get_bits(&gb, 2);
438
439         if (bits) {
440             if (non_mod != 1 || bits != 1) {
441                 if (map_table)
442                     *destbuf++ = map_table[bits];
443                 else
444                     *destbuf++ = bits;
445             }
446             pixels_read++;
447         } else {
448             bits = get_bits1(&gb);
449             if (bits == 1) {
450                 run_length = get_bits(&gb, 3) + 3;
451                 bits = get_bits(&gb, 2);
452
453                 if (non_mod == 1 && bits == 1)
454                     pixels_read += run_length;
455                 else {
456                     if (map_table)
457                         bits = map_table[bits];
458                     while (run_length-- > 0 && pixels_read < dbuf_len) {
459                         *destbuf++ = bits;
460                         pixels_read++;
461                     }
462                 }
463             } else {
464                 bits = get_bits1(&gb);
465                 if (bits == 0) {
466                     bits = get_bits(&gb, 2);
467                     if (bits == 2) {
468                         run_length = get_bits(&gb, 4) + 12;
469                         bits = get_bits(&gb, 2);
470
471                         if (non_mod == 1 && bits == 1)
472                             pixels_read += run_length;
473                         else {
474                             if (map_table)
475                                 bits = map_table[bits];
476                             while (run_length-- > 0 && pixels_read < dbuf_len) {
477                                 *destbuf++ = bits;
478                                 pixels_read++;
479                             }
480                         }
481                     } else if (bits == 3) {
482                         run_length = get_bits(&gb, 8) + 29;
483                         bits = get_bits(&gb, 2);
484
485                         if (non_mod == 1 && bits == 1)
486                             pixels_read += run_length;
487                         else {
488                             if (map_table)
489                                 bits = map_table[bits];
490                             while (run_length-- > 0 && pixels_read < dbuf_len) {
491                                 *destbuf++ = bits;
492                                 pixels_read++;
493                             }
494                         }
495                     } else if (bits == 1) {
496                         if (map_table)
497                             bits = map_table[0];
498                         else
499                             bits = 0;
500                         run_length = 2;
501                         while (run_length-- > 0 && pixels_read < dbuf_len) {
502                             *destbuf++ = bits;
503                             pixels_read++;
504                         }
505                     } else {
506                         (*srcbuf) += (get_bits_count(&gb) + 7) >> 3;
507                         return pixels_read;
508                     }
509                 } else {
510                     if (map_table)
511                         bits = map_table[0];
512                     else
513                         bits = 0;
514                     *destbuf++ = bits;
515                     pixels_read++;
516                 }
517             }
518         }
519     }
520
521     if (get_bits(&gb, 6))
522         av_log(avctx, AV_LOG_ERROR, "line overflow\n");
523
524     (*srcbuf) += (get_bits_count(&gb) + 7) >> 3;
525
526     return pixels_read;
527 }
528
529 static int dvbsub_read_4bit_string(AVCodecContext *avctx, uint8_t *destbuf, int dbuf_len,
530                                    const uint8_t **srcbuf, int buf_size,
531                                    int non_mod, uint8_t *map_table, int x_pos)
532 {
533     GetBitContext gb;
534
535     int bits;
536     int run_length;
537     int pixels_read = x_pos;
538
539     init_get_bits(&gb, *srcbuf, buf_size << 3);
540
541     destbuf += x_pos;
542
543     while (get_bits_count(&gb) < buf_size << 3 && pixels_read < dbuf_len) {
544         bits = get_bits(&gb, 4);
545
546         if (bits) {
547             if (non_mod != 1 || bits != 1) {
548                 if (map_table)
549                     *destbuf++ = map_table[bits];
550                 else
551                     *destbuf++ = bits;
552             }
553             pixels_read++;
554         } else {
555             bits = get_bits1(&gb);
556             if (bits == 0) {
557                 run_length = get_bits(&gb, 3);
558
559                 if (run_length == 0) {
560                     (*srcbuf) += (get_bits_count(&gb) + 7) >> 3;
561                     return pixels_read;
562                 }
563
564                 run_length += 2;
565
566                 if (map_table)
567                     bits = map_table[0];
568                 else
569                     bits = 0;
570
571                 while (run_length-- > 0 && pixels_read < dbuf_len) {
572                     *destbuf++ = bits;
573                     pixels_read++;
574                 }
575             } else {
576                 bits = get_bits1(&gb);
577                 if (bits == 0) {
578                     run_length = get_bits(&gb, 2) + 4;
579                     bits = get_bits(&gb, 4);
580
581                     if (non_mod == 1 && bits == 1)
582                         pixels_read += run_length;
583                     else {
584                         if (map_table)
585                             bits = map_table[bits];
586                         while (run_length-- > 0 && pixels_read < dbuf_len) {
587                             *destbuf++ = bits;
588                             pixels_read++;
589                         }
590                     }
591                 } else {
592                     bits = get_bits(&gb, 2);
593                     if (bits == 2) {
594                         run_length = get_bits(&gb, 4) + 9;
595                         bits = get_bits(&gb, 4);
596
597                         if (non_mod == 1 && bits == 1)
598                             pixels_read += run_length;
599                         else {
600                             if (map_table)
601                                 bits = map_table[bits];
602                             while (run_length-- > 0 && pixels_read < dbuf_len) {
603                                 *destbuf++ = bits;
604                                 pixels_read++;
605                             }
606                         }
607                     } else if (bits == 3) {
608                         run_length = get_bits(&gb, 8) + 25;
609                         bits = get_bits(&gb, 4);
610
611                         if (non_mod == 1 && bits == 1)
612                             pixels_read += run_length;
613                         else {
614                             if (map_table)
615                                 bits = map_table[bits];
616                             while (run_length-- > 0 && pixels_read < dbuf_len) {
617                                 *destbuf++ = bits;
618                                 pixels_read++;
619                             }
620                         }
621                     } else if (bits == 1) {
622                         if (map_table)
623                             bits = map_table[0];
624                         else
625                             bits = 0;
626                         run_length = 2;
627                         while (run_length-- > 0 && pixels_read < dbuf_len) {
628                             *destbuf++ = bits;
629                             pixels_read++;
630                         }
631                     } else {
632                         if (map_table)
633                             bits = map_table[0];
634                         else
635                             bits = 0;
636                         *destbuf++ = bits;
637                         pixels_read ++;
638                     }
639                 }
640             }
641         }
642     }
643
644     if (get_bits(&gb, 8))
645         av_log(avctx, AV_LOG_ERROR, "line overflow\n");
646
647     (*srcbuf) += (get_bits_count(&gb) + 7) >> 3;
648
649     return pixels_read;
650 }
651
652 static int dvbsub_read_8bit_string(AVCodecContext *avctx,
653                                    uint8_t *destbuf, int dbuf_len,
654                                     const uint8_t **srcbuf, int buf_size,
655                                     int non_mod, uint8_t *map_table, int x_pos)
656 {
657     const uint8_t *sbuf_end = (*srcbuf) + buf_size;
658     int bits;
659     int run_length;
660     int pixels_read = x_pos;
661
662     destbuf += x_pos;
663
664     while (*srcbuf < sbuf_end && pixels_read < dbuf_len) {
665         bits = *(*srcbuf)++;
666
667         if (bits) {
668             if (non_mod != 1 || bits != 1) {
669                 if (map_table)
670                     *destbuf++ = map_table[bits];
671                 else
672                     *destbuf++ = bits;
673             }
674             pixels_read++;
675         } else {
676             bits = *(*srcbuf)++;
677             run_length = bits & 0x7f;
678             if ((bits & 0x80) == 0) {
679                 if (run_length == 0) {
680                     return pixels_read;
681                 }
682
683                 bits = 0;
684             } else {
685                 bits = *(*srcbuf)++;
686             }
687             if (non_mod == 1 && bits == 1)
688                 pixels_read += run_length;
689             else {
690                 if (map_table)
691                     bits = map_table[bits];
692                 while (run_length-- > 0 && pixels_read < dbuf_len) {
693                     *destbuf++ = bits;
694                     pixels_read++;
695                 }
696             }
697         }
698     }
699
700     if (*(*srcbuf)++)
701         av_log(avctx, AV_LOG_ERROR, "line overflow\n");
702
703     return pixels_read;
704 }
705
706 static void compute_default_clut(AVSubtitleRect *rect, int w, int h)
707 {
708     uint8_t list[256] = {0};
709     uint8_t list_inv[256];
710     int counttab[256] = {0};
711     int count, i, x, y;
712
713 #define V(x,y) rect->data[0][(x) + (y)*rect->linesize[0]]
714     for (y = 0; y<h; y++) {
715         for (x = 0; x<w; x++) {
716             int v = V(x,y) + 1;
717             int vl = x     ? V(x-1,y) + 1 : 0;
718             int vr = x+1<w ? V(x+1,y) + 1 : 0;
719             int vt = y     ? V(x,y-1) + 1 : 0;
720             int vb = y+1<h ? V(x,y+1) + 1 : 0;
721             counttab[v-1] += !!((v!=vl) + (v!=vr) + (v!=vt) + (v!=vb));
722         }
723     }
724 #define L(x,y) list[ rect->data[0][(x) + (y)*rect->linesize[0]] ]
725
726     for (i = 0; i<256; i++) {
727         int scoretab[256] = {0};
728         int bestscore = 0;
729         int bestv = 0;
730         for (y = 0; y<h; y++) {
731             for (x = 0; x<w; x++) {
732                 int v = rect->data[0][x + y*rect->linesize[0]];
733                 int l_m = list[v];
734                 int l_l = x     ? L(x-1, y) : 1;
735                 int l_r = x+1<w ? L(x+1, y) : 1;
736                 int l_t = y     ? L(x, y-1) : 1;
737                 int l_b = y+1<h ? L(x, y+1) : 1;
738                 int score;
739                 if (l_m)
740                     continue;
741                 scoretab[v] += l_l + l_r + l_t + l_b;
742                 score = 1024LL*scoretab[v] / counttab[v];
743                 if (score > bestscore) {
744                     bestscore = score;
745                     bestv = v;
746                 }
747             }
748         }
749         if (!bestscore)
750             break;
751         list    [ bestv ] = 1;
752         list_inv[     i ] = bestv;
753     }
754
755     count = FFMAX(i - 1, 1);
756     for (i--; i>=0; i--) {
757         int v = i*255/count;
758         AV_WN32(rect->data[1] + 4*list_inv[i], RGBA(v/2,v,v/2,v));
759     }
760 }
761
762
763 static int save_subtitle_set(AVCodecContext *avctx, AVSubtitle *sub, int *got_output)
764 {
765     DVBSubContext *ctx = avctx->priv_data;
766     DVBSubRegionDisplay *display;
767     DVBSubDisplayDefinition *display_def = ctx->display_definition;
768     DVBSubRegion *region;
769     AVSubtitleRect *rect;
770     DVBSubCLUT *clut;
771     uint32_t *clut_table;
772     int i;
773     int offset_x=0, offset_y=0;
774     int ret = 0;
775
776
777     if (display_def) {
778         offset_x = display_def->x;
779         offset_y = display_def->y;
780     }
781
782     /* Not touching AVSubtitles again*/
783     if(sub->num_rects) {
784         avpriv_request_sample(ctx, "Different Version of Segment asked Twice");
785         return AVERROR_PATCHWELCOME;
786     }
787     for (display = ctx->display_list; display; display = display->next) {
788         region = get_region(ctx, display->region_id);
789         if (region && region->dirty)
790             sub->num_rects++;
791     }
792
793     if(ctx->compute_edt == 0) {
794         sub->end_display_time = ctx->time_out * 1000;
795         *got_output = 1;
796     } else if (ctx->prev_start != AV_NOPTS_VALUE) {
797         sub->end_display_time = av_rescale_q((sub->pts - ctx->prev_start ), AV_TIME_BASE_Q, (AVRational){ 1, 1000 }) - 1;
798         *got_output = 1;
799     }
800     if (sub->num_rects > 0) {
801
802         sub->rects = av_mallocz_array(sizeof(*sub->rects), sub->num_rects);
803         if (!sub->rects) {
804             ret = AVERROR(ENOMEM);
805             goto fail;
806         }
807
808         for(i=0; i<sub->num_rects; i++)
809             sub->rects[i] = av_mallocz(sizeof(*sub->rects[i]));
810
811         i = 0;
812
813         for (display = ctx->display_list; display; display = display->next) {
814             region = get_region(ctx, display->region_id);
815
816             if (!region)
817                 continue;
818
819             if (!region->dirty)
820                 continue;
821
822             rect = sub->rects[i];
823             rect->x = display->x_pos + offset_x;
824             rect->y = display->y_pos + offset_y;
825             rect->w = region->width;
826             rect->h = region->height;
827             rect->nb_colors = (1 << region->depth);
828             rect->type      = SUBTITLE_BITMAP;
829             rect->linesize[0] = region->width;
830
831             clut = get_clut(ctx, region->clut);
832
833             if (!clut)
834                 clut = &default_clut;
835
836             switch (region->depth) {
837             case 2:
838                 clut_table = clut->clut4;
839                 break;
840             case 8:
841                 clut_table = clut->clut256;
842                 break;
843             case 4:
844             default:
845                 clut_table = clut->clut16;
846                 break;
847             }
848
849             rect->data[1] = av_mallocz(AVPALETTE_SIZE);
850             if (!rect->data[1]) {
851                 ret = AVERROR(ENOMEM);
852                 goto fail;
853             }
854             memcpy(rect->data[1], clut_table, (1 << region->depth) * sizeof(uint32_t));
855
856             rect->data[0] = av_malloc(region->buf_size);
857             if (!rect->data[0]) {
858                 ret = AVERROR(ENOMEM);
859                 goto fail;
860             }
861
862             memcpy(rect->data[0], region->pbuf, region->buf_size);
863
864             if ((clut == &default_clut && ctx->compute_clut == -1) || ctx->compute_clut == 1)
865                 compute_default_clut(rect, rect->w, rect->h);
866
867 #if FF_API_AVPICTURE
868 FF_DISABLE_DEPRECATION_WARNINGS
869 {
870             int j;
871             for (j = 0; j < 4; j++) {
872                 rect->pict.data[j] = rect->data[j];
873                 rect->pict.linesize[j] = rect->linesize[j];
874             }
875 }
876 FF_ENABLE_DEPRECATION_WARNINGS
877 #endif
878
879             i++;
880         }
881     }
882
883     return 0;
884 fail:
885     if (sub->rects) {
886         for(i=0; i<sub->num_rects; i++) {
887             rect = sub->rects[i];
888             if (rect) {
889                 av_freep(&rect->data[0]);
890                 av_freep(&rect->data[1]);
891             }
892             av_freep(&sub->rects[i]);
893         }
894         av_freep(&sub->rects);
895     }
896     sub->num_rects = 0;
897     return ret;
898 }
899
900 static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDisplay *display,
901                                           const uint8_t *buf, int buf_size, int top_bottom, int non_mod)
902 {
903     DVBSubContext *ctx = avctx->priv_data;
904
905     DVBSubRegion *region = get_region(ctx, display->region_id);
906     const uint8_t *buf_end = buf + buf_size;
907     uint8_t *pbuf;
908     int x_pos, y_pos;
909     int i;
910
911     uint8_t map2to4[] = { 0x0,  0x7,  0x8,  0xf};
912     uint8_t map2to8[] = {0x00, 0x77, 0x88, 0xff};
913     uint8_t map4to8[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
914                          0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};
915     uint8_t *map_table;
916
917 #if 0
918     ff_dlog(avctx, "DVB pixel block size %d, %s field:\n", buf_size,
919             top_bottom ? "bottom" : "top");
920
921     for (i = 0; i < buf_size; i++) {
922         if (i % 16 == 0)
923             ff_dlog(avctx, "0x%8p: ", buf+i);
924
925         ff_dlog(avctx, "%02x ", buf[i]);
926         if (i % 16 == 15)
927             ff_dlog(avctx, "\n");
928     }
929
930     if (i % 16)
931         ff_dlog(avctx, "\n");
932 #endif
933
934     if (!region)
935         return;
936
937     pbuf = region->pbuf;
938     region->dirty = 1;
939
940     x_pos = display->x_pos;
941     y_pos = display->y_pos;
942
943     y_pos += top_bottom;
944
945     while (buf < buf_end) {
946         if ((*buf!=0xf0 && x_pos >= region->width) || y_pos >= region->height) {
947             av_log(avctx, AV_LOG_ERROR, "Invalid object location! %d-%d %d-%d %02x\n", x_pos, region->width, y_pos, region->height, *buf);
948             return;
949         }
950
951         switch (*buf++) {
952         case 0x10:
953             if (region->depth == 8)
954                 map_table = map2to8;
955             else if (region->depth == 4)
956                 map_table = map2to4;
957             else
958                 map_table = NULL;
959
960             x_pos = dvbsub_read_2bit_string(avctx, pbuf + (y_pos * region->width),
961                                             region->width, &buf, buf_end - buf,
962                                             non_mod, map_table, x_pos);
963             break;
964         case 0x11:
965             if (region->depth < 4) {
966                 av_log(avctx, AV_LOG_ERROR, "4-bit pixel string in %d-bit region!\n", region->depth);
967                 return;
968             }
969
970             if (region->depth == 8)
971                 map_table = map4to8;
972             else
973                 map_table = NULL;
974
975             x_pos = dvbsub_read_4bit_string(avctx, pbuf + (y_pos * region->width),
976                                             region->width, &buf, buf_end - buf,
977                                             non_mod, map_table, x_pos);
978             break;
979         case 0x12:
980             if (region->depth < 8) {
981                 av_log(avctx, AV_LOG_ERROR, "8-bit pixel string in %d-bit region!\n", region->depth);
982                 return;
983             }
984
985             x_pos = dvbsub_read_8bit_string(avctx, pbuf + (y_pos * region->width),
986                                             region->width, &buf, buf_end - buf,
987                                             non_mod, NULL, x_pos);
988             break;
989
990         case 0x20:
991             map2to4[0] = (*buf) >> 4;
992             map2to4[1] = (*buf++) & 0xf;
993             map2to4[2] = (*buf) >> 4;
994             map2to4[3] = (*buf++) & 0xf;
995             break;
996         case 0x21:
997             for (i = 0; i < 4; i++)
998                 map2to8[i] = *buf++;
999             break;
1000         case 0x22:
1001             for (i = 0; i < 16; i++)
1002                 map4to8[i] = *buf++;
1003             break;
1004
1005         case 0xf0:
1006             x_pos = display->x_pos;
1007             y_pos += 2;
1008             break;
1009         default:
1010             av_log(avctx, AV_LOG_INFO, "Unknown/unsupported pixel block 0x%x\n", *(buf-1));
1011         }
1012     }
1013
1014 }
1015
1016 static int dvbsub_parse_object_segment(AVCodecContext *avctx,
1017                                        const uint8_t *buf, int buf_size)
1018 {
1019     DVBSubContext *ctx = avctx->priv_data;
1020
1021     const uint8_t *buf_end = buf + buf_size;
1022     int object_id;
1023     DVBSubObject *object;
1024     DVBSubObjectDisplay *display;
1025     int top_field_len, bottom_field_len;
1026
1027     int coding_method, non_modifying_color;
1028
1029     object_id = AV_RB16(buf);
1030     buf += 2;
1031
1032     object = get_object(ctx, object_id);
1033
1034     if (!object)
1035         return AVERROR_INVALIDDATA;
1036
1037     coding_method = ((*buf) >> 2) & 3;
1038     non_modifying_color = ((*buf++) >> 1) & 1;
1039
1040     if (coding_method == 0) {
1041         top_field_len = AV_RB16(buf);
1042         buf += 2;
1043         bottom_field_len = AV_RB16(buf);
1044         buf += 2;
1045
1046         if (buf + top_field_len + bottom_field_len > buf_end) {
1047             av_log(avctx, AV_LOG_ERROR, "Field data size %d+%d too large\n", top_field_len, bottom_field_len);
1048             return AVERROR_INVALIDDATA;
1049         }
1050
1051         for (display = object->display_list; display; display = display->object_list_next) {
1052             const uint8_t *block = buf;
1053             int bfl = bottom_field_len;
1054
1055             dvbsub_parse_pixel_data_block(avctx, display, block, top_field_len, 0,
1056                                             non_modifying_color);
1057
1058             if (bottom_field_len > 0)
1059                 block = buf + top_field_len;
1060             else
1061                 bfl = top_field_len;
1062
1063             dvbsub_parse_pixel_data_block(avctx, display, block, bfl, 1,
1064                                             non_modifying_color);
1065         }
1066
1067 /*  } else if (coding_method == 1) {*/
1068
1069     } else {
1070         av_log(avctx, AV_LOG_ERROR, "Unknown object coding %d\n", coding_method);
1071     }
1072
1073     return 0;
1074 }
1075
1076 static int dvbsub_parse_clut_segment(AVCodecContext *avctx,
1077                                      const uint8_t *buf, int buf_size)
1078 {
1079     DVBSubContext *ctx = avctx->priv_data;
1080
1081     const uint8_t *buf_end = buf + buf_size;
1082     int i, clut_id;
1083     int version;
1084     DVBSubCLUT *clut;
1085     int entry_id, depth , full_range;
1086     int y, cr, cb, alpha;
1087     int r, g, b, r_add, g_add, b_add;
1088
1089     ff_dlog(avctx, "DVB clut packet:\n");
1090
1091     for (i=0; i < buf_size; i++) {
1092         ff_dlog(avctx, "%02x ", buf[i]);
1093         if (i % 16 == 15)
1094             ff_dlog(avctx, "\n");
1095     }
1096
1097     if (i % 16)
1098         ff_dlog(avctx, "\n");
1099
1100     clut_id = *buf++;
1101     version = ((*buf)>>4)&15;
1102     buf += 1;
1103
1104     clut = get_clut(ctx, clut_id);
1105
1106     if (!clut) {
1107         clut = av_malloc(sizeof(DVBSubCLUT));
1108         if (!clut)
1109             return AVERROR(ENOMEM);
1110
1111         memcpy(clut, &default_clut, sizeof(DVBSubCLUT));
1112
1113         clut->id = clut_id;
1114         clut->version = -1;
1115
1116         clut->next = ctx->clut_list;
1117         ctx->clut_list = clut;
1118     }
1119
1120     if (clut->version != version) {
1121
1122     clut->version = version;
1123
1124     while (buf + 4 < buf_end) {
1125         entry_id = *buf++;
1126
1127         depth = (*buf) & 0xe0;
1128
1129         if (depth == 0) {
1130             av_log(avctx, AV_LOG_ERROR, "Invalid clut depth 0x%x!\n", *buf);
1131         }
1132
1133         full_range = (*buf++) & 1;
1134
1135         if (full_range) {
1136             y = *buf++;
1137             cr = *buf++;
1138             cb = *buf++;
1139             alpha = *buf++;
1140         } else {
1141             y = buf[0] & 0xfc;
1142             cr = (((buf[0] & 3) << 2) | ((buf[1] >> 6) & 3)) << 4;
1143             cb = (buf[1] << 2) & 0xf0;
1144             alpha = (buf[1] << 6) & 0xc0;
1145
1146             buf += 2;
1147         }
1148
1149         if (y == 0)
1150             alpha = 0xff;
1151
1152         YUV_TO_RGB1_CCIR(cb, cr);
1153         YUV_TO_RGB2_CCIR(r, g, b, y);
1154
1155         ff_dlog(avctx, "clut %d := (%d,%d,%d,%d)\n", entry_id, r, g, b, alpha);
1156         if (!!(depth & 0x80) + !!(depth & 0x40) + !!(depth & 0x20) > 1) {
1157             ff_dlog(avctx, "More than one bit level marked: %x\n", depth);
1158             if (avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL)
1159                 return AVERROR_INVALIDDATA;
1160         }
1161
1162         if (depth & 0x80)
1163             clut->clut4[entry_id] = RGBA(r,g,b,255 - alpha);
1164         else if (depth & 0x40)
1165             clut->clut16[entry_id] = RGBA(r,g,b,255 - alpha);
1166         else if (depth & 0x20)
1167             clut->clut256[entry_id] = RGBA(r,g,b,255 - alpha);
1168     }
1169     }
1170
1171     return 0;
1172 }
1173
1174
1175 static int dvbsub_parse_region_segment(AVCodecContext *avctx,
1176                                        const uint8_t *buf, int buf_size)
1177 {
1178     DVBSubContext *ctx = avctx->priv_data;
1179
1180     const uint8_t *buf_end = buf + buf_size;
1181     int region_id, object_id;
1182     int av_unused version;
1183     DVBSubRegion *region;
1184     DVBSubObject *object;
1185     DVBSubObjectDisplay *display;
1186     int fill;
1187
1188     if (buf_size < 10)
1189         return AVERROR_INVALIDDATA;
1190
1191     region_id = *buf++;
1192
1193     region = get_region(ctx, region_id);
1194
1195     if (!region) {
1196         region = av_mallocz(sizeof(DVBSubRegion));
1197         if (!region)
1198             return AVERROR(ENOMEM);
1199
1200         region->id = region_id;
1201         region->version = -1;
1202
1203         region->next = ctx->region_list;
1204         ctx->region_list = region;
1205     }
1206
1207     version = ((*buf)>>4) & 15;
1208     fill = ((*buf++) >> 3) & 1;
1209
1210     region->width = AV_RB16(buf);
1211     buf += 2;
1212     region->height = AV_RB16(buf);
1213     buf += 2;
1214
1215     if (region->width * region->height != region->buf_size) {
1216         av_free(region->pbuf);
1217
1218         region->buf_size = region->width * region->height;
1219
1220         region->pbuf = av_malloc(region->buf_size);
1221         if (!region->pbuf) {
1222             region->buf_size =
1223             region->width =
1224             region->height = 0;
1225             return AVERROR(ENOMEM);
1226         }
1227
1228         fill = 1;
1229         region->dirty = 0;
1230     }
1231
1232     region->depth = 1 << (((*buf++) >> 2) & 7);
1233     if(region->depth<2 || region->depth>8){
1234         av_log(avctx, AV_LOG_ERROR, "region depth %d is invalid\n", region->depth);
1235         region->depth= 4;
1236     }
1237     region->clut = *buf++;
1238
1239     if (region->depth == 8) {
1240         region->bgcolor = *buf++;
1241         buf += 1;
1242     } else {
1243         buf += 1;
1244
1245         if (region->depth == 4)
1246             region->bgcolor = (((*buf++) >> 4) & 15);
1247         else
1248             region->bgcolor = (((*buf++) >> 2) & 3);
1249     }
1250
1251     ff_dlog(avctx, "Region %d, (%dx%d)\n", region_id, region->width, region->height);
1252
1253     if (fill) {
1254         memset(region->pbuf, region->bgcolor, region->buf_size);
1255         ff_dlog(avctx, "Fill region (%d)\n", region->bgcolor);
1256     }
1257
1258     delete_region_display_list(ctx, region);
1259
1260     while (buf + 5 < buf_end) {
1261         object_id = AV_RB16(buf);
1262         buf += 2;
1263
1264         object = get_object(ctx, object_id);
1265
1266         if (!object) {
1267             object = av_mallocz(sizeof(DVBSubObject));
1268             if (!object)
1269                 return AVERROR(ENOMEM);
1270
1271             object->id = object_id;
1272             object->next = ctx->object_list;
1273             ctx->object_list = object;
1274         }
1275
1276         object->type = (*buf) >> 6;
1277
1278         display = av_mallocz(sizeof(DVBSubObjectDisplay));
1279         if (!display)
1280             return AVERROR(ENOMEM);
1281
1282         display->object_id = object_id;
1283         display->region_id = region_id;
1284
1285         display->x_pos = AV_RB16(buf) & 0xfff;
1286         buf += 2;
1287         display->y_pos = AV_RB16(buf) & 0xfff;
1288         buf += 2;
1289
1290         if ((object->type == 1 || object->type == 2) && buf+1 < buf_end) {
1291             display->fgcolor = *buf++;
1292             display->bgcolor = *buf++;
1293         }
1294
1295         display->region_list_next = region->display_list;
1296         region->display_list = display;
1297
1298         display->object_list_next = object->display_list;
1299         object->display_list = display;
1300     }
1301
1302     return 0;
1303 }
1304
1305 static int dvbsub_parse_page_segment(AVCodecContext *avctx,
1306                                      const uint8_t *buf, int buf_size, AVSubtitle *sub, int *got_output)
1307 {
1308     DVBSubContext *ctx = avctx->priv_data;
1309     DVBSubRegionDisplay *display;
1310     DVBSubRegionDisplay *tmp_display_list, **tmp_ptr;
1311
1312     const uint8_t *buf_end = buf + buf_size;
1313     int region_id;
1314     int page_state;
1315     int timeout;
1316     int version;
1317
1318     if (buf_size < 1)
1319         return AVERROR_INVALIDDATA;
1320
1321     timeout = *buf++;
1322     version = ((*buf)>>4) & 15;
1323     page_state = ((*buf++) >> 2) & 3;
1324
1325     if (ctx->version == version) {
1326         return 0;
1327     }
1328
1329     ctx->time_out = timeout;
1330     ctx->version = version;
1331
1332     ff_dlog(avctx, "Page time out %ds, state %d\n", ctx->time_out, page_state);
1333
1334     if(ctx->compute_edt == 1)
1335         save_subtitle_set(avctx, sub, got_output);
1336
1337     if (page_state == 1 || page_state == 2) {
1338         delete_regions(ctx);
1339         delete_objects(ctx);
1340         delete_cluts(ctx);
1341     }
1342
1343     tmp_display_list = ctx->display_list;
1344     ctx->display_list = NULL;
1345
1346     while (buf + 5 < buf_end) {
1347         region_id = *buf++;
1348         buf += 1;
1349
1350         display = tmp_display_list;
1351         tmp_ptr = &tmp_display_list;
1352
1353         while (display && display->region_id != region_id) {
1354             tmp_ptr = &display->next;
1355             display = display->next;
1356         }
1357
1358         if (!display) {
1359             display = av_mallocz(sizeof(DVBSubRegionDisplay));
1360             if (!display)
1361                 return AVERROR(ENOMEM);
1362         }
1363
1364         display->region_id = region_id;
1365
1366         display->x_pos = AV_RB16(buf);
1367         buf += 2;
1368         display->y_pos = AV_RB16(buf);
1369         buf += 2;
1370
1371         *tmp_ptr = display->next;
1372
1373         display->next = ctx->display_list;
1374         ctx->display_list = display;
1375
1376         ff_dlog(avctx, "Region %d, (%d,%d)\n", region_id, display->x_pos, display->y_pos);
1377     }
1378
1379     while (tmp_display_list) {
1380         display = tmp_display_list;
1381
1382         tmp_display_list = display->next;
1383
1384         av_freep(&display);
1385     }
1386
1387     return 0;
1388 }
1389
1390
1391 #ifdef DEBUG
1392 static int save_display_set(DVBSubContext *ctx)
1393 {
1394     DVBSubRegion *region;
1395     DVBSubRegionDisplay *display;
1396     DVBSubCLUT *clut;
1397     uint32_t *clut_table;
1398     int x_pos, y_pos, width, height;
1399     int x, y, y_off, x_off;
1400     uint32_t *pbuf;
1401     char filename[32];
1402     static int fileno_index = 0;
1403
1404     x_pos = -1;
1405     y_pos = -1;
1406     width = 0;
1407     height = 0;
1408
1409     for (display = ctx->display_list; display; display = display->next) {
1410         region = get_region(ctx, display->region_id);
1411
1412         if (!region)
1413             return -1;
1414
1415         if (x_pos == -1) {
1416             x_pos = display->x_pos;
1417             y_pos = display->y_pos;
1418             width = region->width;
1419             height = region->height;
1420         } else {
1421             if (display->x_pos < x_pos) {
1422                 width += (x_pos - display->x_pos);
1423                 x_pos = display->x_pos;
1424             }
1425
1426             if (display->y_pos < y_pos) {
1427                 height += (y_pos - display->y_pos);
1428                 y_pos = display->y_pos;
1429             }
1430
1431             if (display->x_pos + region->width > x_pos + width) {
1432                 width = display->x_pos + region->width - x_pos;
1433             }
1434
1435             if (display->y_pos + region->height > y_pos + height) {
1436                 height = display->y_pos + region->height - y_pos;
1437             }
1438         }
1439     }
1440
1441     if (x_pos >= 0) {
1442
1443         pbuf = av_malloc(width * height * 4);
1444         if (!pbuf)
1445             return -1;
1446
1447         for (display = ctx->display_list; display; display = display->next) {
1448             region = get_region(ctx, display->region_id);
1449
1450             if (!region)
1451                 return -1;
1452
1453             x_off = display->x_pos - x_pos;
1454             y_off = display->y_pos - y_pos;
1455
1456             clut = get_clut(ctx, region->clut);
1457
1458             if (!clut)
1459                 clut = &default_clut;
1460
1461             switch (region->depth) {
1462             case 2:
1463                 clut_table = clut->clut4;
1464                 break;
1465             case 8:
1466                 clut_table = clut->clut256;
1467                 break;
1468             case 4:
1469             default:
1470                 clut_table = clut->clut16;
1471                 break;
1472             }
1473
1474             for (y = 0; y < region->height; y++) {
1475                 for (x = 0; x < region->width; x++) {
1476                     pbuf[((y + y_off) * width) + x_off + x] =
1477                         clut_table[region->pbuf[y * region->width + x]];
1478                 }
1479             }
1480
1481         }
1482
1483         snprintf(filename, sizeof(filename), "dvbs.%d", fileno_index);
1484
1485         png_save(filename, pbuf, width, height);
1486
1487         av_freep(&pbuf);
1488     }
1489
1490     fileno_index++;
1491     return 0;
1492 }
1493 #endif
1494
1495 static int dvbsub_parse_display_definition_segment(AVCodecContext *avctx,
1496                                                    const uint8_t *buf,
1497                                                    int buf_size)
1498 {
1499     DVBSubContext *ctx = avctx->priv_data;
1500     DVBSubDisplayDefinition *display_def = ctx->display_definition;
1501     int dds_version, info_byte;
1502
1503     if (buf_size < 5)
1504         return AVERROR_INVALIDDATA;
1505
1506     info_byte   = bytestream_get_byte(&buf);
1507     dds_version = info_byte >> 4;
1508     if (display_def && display_def->version == dds_version)
1509         return 0; // already have this display definition version
1510
1511     if (!display_def) {
1512         display_def             = av_mallocz(sizeof(*display_def));
1513         if (!display_def)
1514             return AVERROR(ENOMEM);
1515         ctx->display_definition = display_def;
1516     }
1517
1518     display_def->version = dds_version;
1519     display_def->x       = 0;
1520     display_def->y       = 0;
1521     display_def->width   = bytestream_get_be16(&buf) + 1;
1522     display_def->height  = bytestream_get_be16(&buf) + 1;
1523     if (!avctx->width || !avctx->height) {
1524         avctx->width  = display_def->width;
1525         avctx->height = display_def->height;
1526     }
1527
1528     if (info_byte & 1<<3) { // display_window_flag
1529         if (buf_size < 13)
1530             return AVERROR_INVALIDDATA;
1531
1532         display_def->x = bytestream_get_be16(&buf);
1533         display_def->width  = bytestream_get_be16(&buf) - display_def->x + 1;
1534         display_def->y = bytestream_get_be16(&buf);
1535         display_def->height = bytestream_get_be16(&buf) - display_def->y + 1;
1536     }
1537
1538     return 0;
1539 }
1540
1541 static int dvbsub_display_end_segment(AVCodecContext *avctx, const uint8_t *buf,
1542                                       int buf_size, AVSubtitle *sub,int *got_output)
1543 {
1544     DVBSubContext *ctx = avctx->priv_data;
1545
1546     if(ctx->compute_edt == 0)
1547         save_subtitle_set(avctx, sub, got_output);
1548 #ifdef DEBUG
1549     save_display_set(ctx);
1550 #endif
1551     return 0;
1552 }
1553
1554 static int dvbsub_decode(AVCodecContext *avctx,
1555                          void *data, int *data_size,
1556                          AVPacket *avpkt)
1557 {
1558     const uint8_t *buf = avpkt->data;
1559     int buf_size = avpkt->size;
1560     DVBSubContext *ctx = avctx->priv_data;
1561     AVSubtitle *sub = data;
1562     const uint8_t *p, *p_end;
1563     int segment_type;
1564     int page_id;
1565     int segment_length;
1566     int i;
1567     int ret = 0;
1568     int got_segment = 0;
1569     int got_dds = 0;
1570
1571     ff_dlog(avctx, "DVB sub packet:\n");
1572
1573     for (i=0; i < buf_size; i++) {
1574         ff_dlog(avctx, "%02x ", buf[i]);
1575         if (i % 16 == 15)
1576             ff_dlog(avctx, "\n");
1577     }
1578
1579     if (i % 16)
1580         ff_dlog(avctx, "\n");
1581
1582     if (buf_size <= 6 || *buf != 0x0f) {
1583         ff_dlog(avctx, "incomplete or broken packet");
1584         return AVERROR_INVALIDDATA;
1585     }
1586
1587     p = buf;
1588     p_end = buf + buf_size;
1589
1590     while (p_end - p >= 6 && *p == 0x0f) {
1591         p += 1;
1592         segment_type = *p++;
1593         page_id = AV_RB16(p);
1594         p += 2;
1595         segment_length = AV_RB16(p);
1596         p += 2;
1597
1598         if (avctx->debug & FF_DEBUG_STARTCODE) {
1599             av_log(avctx, AV_LOG_DEBUG, "segment_type:%d page_id:%d segment_length:%d\n", segment_type, page_id, segment_length);
1600         }
1601
1602         if (p_end - p < segment_length) {
1603             ff_dlog(avctx, "incomplete or broken packet");
1604             ret = -1;
1605             goto end;
1606         }
1607
1608         if (page_id == ctx->composition_id || page_id == ctx->ancillary_id ||
1609             ctx->composition_id == -1 || ctx->ancillary_id == -1) {
1610             int ret = 0;
1611             switch (segment_type) {
1612             case DVBSUB_PAGE_SEGMENT:
1613                 ret = dvbsub_parse_page_segment(avctx, p, segment_length, sub, data_size);
1614                 got_segment |= 1;
1615                 break;
1616             case DVBSUB_REGION_SEGMENT:
1617                 ret = dvbsub_parse_region_segment(avctx, p, segment_length);
1618                 got_segment |= 2;
1619                 break;
1620             case DVBSUB_CLUT_SEGMENT:
1621                 ret = dvbsub_parse_clut_segment(avctx, p, segment_length);
1622                 if (ret < 0) goto end;
1623                 got_segment |= 4;
1624                 break;
1625             case DVBSUB_OBJECT_SEGMENT:
1626                 ret = dvbsub_parse_object_segment(avctx, p, segment_length);
1627                 got_segment |= 8;
1628                 break;
1629             case DVBSUB_DISPLAYDEFINITION_SEGMENT:
1630                 ret = dvbsub_parse_display_definition_segment(avctx, p,
1631                                                               segment_length);
1632                 got_dds = 1;
1633                 break;
1634             case DVBSUB_DISPLAY_SEGMENT:
1635                 ret = dvbsub_display_end_segment(avctx, p, segment_length, sub, data_size);
1636                 if (got_segment == 15 && !got_dds && !avctx->width && !avctx->height) {
1637                     // Default from ETSI EN 300 743 V1.3.1 (7.2.1)
1638                     avctx->width  = 720;
1639                     avctx->height = 576;
1640                 }
1641                 got_segment |= 16;
1642                 break;
1643             default:
1644                 ff_dlog(avctx, "Subtitling segment type 0x%x, page id %d, length %d\n",
1645                         segment_type, page_id, segment_length);
1646                 break;
1647             }
1648             if (ret < 0)
1649                 goto end;
1650         }
1651
1652         p += segment_length;
1653     }
1654     // Some streams do not send a display segment but if we have all the other
1655     // segments then we need no further data.
1656     if (got_segment == 15) {
1657         av_log(avctx, AV_LOG_DEBUG, "Missing display_end_segment, emulating\n");
1658         dvbsub_display_end_segment(avctx, p, 0, sub, data_size);
1659     }
1660
1661 end:
1662     if(ret < 0) {
1663         *data_size = 0;
1664         avsubtitle_free(sub);
1665         return ret;
1666     } else {
1667         if(ctx->compute_edt == 1 )
1668             FFSWAP(int64_t, ctx->prev_start, sub->pts);
1669     }
1670
1671     return p - buf;
1672 }
1673
1674 #define DS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_SUBTITLE_PARAM
1675 static const AVOption options[] = {
1676     {"compute_edt", "compute end of time using pts or timeout", offsetof(DVBSubContext, compute_edt), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DS},
1677     {"compute_clut", "compute clut when not available(-1) or always(1) or never(0)", offsetof(DVBSubContext, compute_clut), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, DS},
1678     {"dvb_substream", "", offsetof(DVBSubContext, substream), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, DS},
1679     {NULL}
1680 };
1681 static const AVClass dvbsubdec_class = {
1682     .class_name = "DVB Sub Decoder",
1683     .item_name  = av_default_item_name,
1684     .option     = options,
1685     .version    = LIBAVUTIL_VERSION_INT,
1686 };
1687
1688 AVCodec ff_dvbsub_decoder = {
1689     .name           = "dvbsub",
1690     .long_name      = NULL_IF_CONFIG_SMALL("DVB subtitles"),
1691     .type           = AVMEDIA_TYPE_SUBTITLE,
1692     .id             = AV_CODEC_ID_DVB_SUBTITLE,
1693     .priv_data_size = sizeof(DVBSubContext),
1694     .init           = dvbsub_init_decoder,
1695     .close          = dvbsub_close_decoder,
1696     .decode         = dvbsub_decode,
1697     .priv_class     = &dvbsubdec_class,
1698 };