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