]> git.sesse.net Git - ffmpeg/blob - libavcodec/pgssubdec.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / pgssubdec.c
1 /*
2  * PGS subtitle decoder
3  * Copyright (c) 2009 Stephen Backway
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 /**
23  * @file
24  * PGS subtitle decoder
25  */
26
27 #include "avcodec.h"
28 #include "dsputil.h"
29 #include "bytestream.h"
30 #include "libavutil/colorspace.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/opt.h"
33
34 #define RGBA(r,g,b,a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))
35
36 enum SegmentType {
37     PALETTE_SEGMENT      = 0x14,
38     PICTURE_SEGMENT      = 0x15,
39     PRESENTATION_SEGMENT = 0x16,
40     WINDOW_SEGMENT       = 0x17,
41     DISPLAY_SEGMENT      = 0x80,
42 };
43
44 typedef struct PGSSubPictureReference {
45     int x;
46     int y;
47     int picture_id;
48     int composition;
49 } PGSSubPictureReference;
50
51 typedef struct PGSSubPresentation {
52     int                    id_number;
53     int                    object_count;
54     PGSSubPictureReference *objects;
55 } PGSSubPresentation;
56
57 typedef struct PGSSubPicture {
58     int          w;
59     int          h;
60     uint8_t      *rle;
61     unsigned int rle_buffer_size, rle_data_len;
62     unsigned int rle_remaining_len;
63 } PGSSubPicture;
64
65 typedef struct PGSSubContext {
66     AVClass *class;
67     PGSSubPresentation presentation;
68     uint32_t           clut[256];
69     PGSSubPicture      pictures[UINT16_MAX];
70     int forced_subs_only;
71 } PGSSubContext;
72
73 static av_cold int init_decoder(AVCodecContext *avctx)
74 {
75     avctx->pix_fmt     = PIX_FMT_PAL8;
76
77     return 0;
78 }
79
80 static av_cold int close_decoder(AVCodecContext *avctx)
81 {
82     uint16_t picture;
83
84     PGSSubContext *ctx = avctx->priv_data;
85
86     av_freep(&ctx->presentation.objects);
87     ctx->presentation.object_count = 0;
88
89     for (picture = 0; picture < UINT16_MAX; ++picture) {
90         av_freep(&ctx->pictures[picture].rle);
91         ctx->pictures[picture].rle_buffer_size = 0;
92     }
93
94     return 0;
95 }
96
97 /**
98  * Decode the RLE data.
99  *
100  * The subtitle is stored as an Run Length Encoded image.
101  *
102  * @param avctx contains the current codec context
103  * @param sub pointer to the processed subtitle data
104  * @param buf pointer to the RLE data to process
105  * @param buf_size size of the RLE data to process
106  */
107 static int decode_rle(AVCodecContext *avctx, AVSubtitle *sub, int rect,
108                       const uint8_t *buf, unsigned int buf_size)
109 {
110     const uint8_t *rle_bitmap_end;
111     int pixel_count, line_count;
112
113     rle_bitmap_end = buf + buf_size;
114
115     sub->rects[rect]->pict.data[0] = av_malloc(sub->rects[rect]->w * sub->rects[rect]->h);
116
117     if (!sub->rects[rect]->pict.data[0])
118         return -1;
119
120     pixel_count = 0;
121     line_count  = 0;
122
123     while (buf < rle_bitmap_end && line_count < sub->rects[rect]->h) {
124         uint8_t flags, color;
125         int run;
126
127         color = bytestream_get_byte(&buf);
128         run   = 1;
129
130         if (color == 0x00) {
131             flags = bytestream_get_byte(&buf);
132             run   = flags & 0x3f;
133             if (flags & 0x40)
134                 run = (run << 8) + bytestream_get_byte(&buf);
135             color = flags & 0x80 ? bytestream_get_byte(&buf) : 0;
136         }
137
138         if (run > 0 && pixel_count + run <= sub->rects[rect]->w * sub->rects[rect]->h) {
139             memset(sub->rects[rect]->pict.data[0] + pixel_count, color, run);
140             pixel_count += run;
141         } else if (!run) {
142             /*
143              * New Line. Check if correct pixels decoded, if not display warning
144              * and adjust bitmap pointer to correct new line position.
145              */
146             if (pixel_count % sub->rects[rect]->w > 0)
147                 av_log(avctx, AV_LOG_ERROR, "Decoded %d pixels, when line should be %d pixels\n",
148                        pixel_count % sub->rects[rect]->w, sub->rects[rect]->w);
149             line_count++;
150         }
151     }
152
153     if (pixel_count < sub->rects[rect]->w * sub->rects[rect]->h) {
154         av_log(avctx, AV_LOG_ERROR, "Insufficient RLE data for subtitle\n");
155         return -1;
156     }
157
158     av_dlog(avctx, "Pixel Count = %d, Area = %d\n", pixel_count, sub->rects[rect]->w * sub->rects[rect]->h);
159
160     return 0;
161 }
162
163 /**
164  * Parse the picture segment packet.
165  *
166  * The picture segment contains details on the sequence id,
167  * width, height and Run Length Encoded (RLE) bitmap data.
168  *
169  * @param avctx contains the current codec context
170  * @param buf pointer to the packet to process
171  * @param buf_size size of packet to process
172  * @todo TODO: Enable support for RLE data over multiple packets
173  */
174 static int parse_picture_segment(AVCodecContext *avctx,
175                                   const uint8_t *buf, int buf_size)
176 {
177     PGSSubContext *ctx = avctx->priv_data;
178
179     uint8_t sequence_desc;
180     unsigned int rle_bitmap_len, width, height;
181     uint16_t picture_id;
182
183     if (buf_size <= 4)
184         return -1;
185     buf_size -= 4;
186
187     picture_id = bytestream_get_be16(&buf);
188
189     /* skip 1 unknown byte: Version Number */
190     buf++;
191
192     /* Read the Sequence Description to determine if start of RLE data or appended to previous RLE */
193     sequence_desc = bytestream_get_byte(&buf);
194
195     if (!(sequence_desc & 0x80)) {
196         /* Additional RLE data */
197         if (buf_size > ctx->pictures[picture_id].rle_remaining_len)
198             return -1;
199
200         memcpy(ctx->pictures[picture_id].rle + ctx->pictures[picture_id].rle_data_len, buf, buf_size);
201         ctx->pictures[picture_id].rle_data_len += buf_size;
202         ctx->pictures[picture_id].rle_remaining_len -= buf_size;
203
204         return 0;
205     }
206
207     if (buf_size <= 7)
208         return -1;
209     buf_size -= 7;
210
211     /* Decode rle bitmap length, stored size includes width/height data */
212     rle_bitmap_len = bytestream_get_be24(&buf) - 2*2;
213
214     /* Get bitmap dimensions from data */
215     width  = bytestream_get_be16(&buf);
216     height = bytestream_get_be16(&buf);
217
218     /* Make sure the bitmap is not too large */
219     if (avctx->width < width || avctx->height < height) {
220         av_log(avctx, AV_LOG_ERROR, "Bitmap dimensions larger than video.\n");
221         return -1;
222     }
223
224     ctx->pictures[picture_id].w = width;
225     ctx->pictures[picture_id].h = height;
226
227     av_fast_malloc(&ctx->pictures[picture_id].rle, &ctx->pictures[picture_id].rle_buffer_size, rle_bitmap_len);
228
229     if (!ctx->pictures[picture_id].rle)
230         return -1;
231
232     memcpy(ctx->pictures[picture_id].rle, buf, buf_size);
233     ctx->pictures[picture_id].rle_data_len      = buf_size;
234     ctx->pictures[picture_id].rle_remaining_len = rle_bitmap_len - buf_size;
235
236     return 0;
237 }
238
239 /**
240  * Parse the palette segment packet.
241  *
242  * The palette segment contains details of the palette,
243  * a maximum of 256 colors can be defined.
244  *
245  * @param avctx contains the current codec context
246  * @param buf pointer to the packet to process
247  * @param buf_size size of packet to process
248  */
249 static void parse_palette_segment(AVCodecContext *avctx,
250                                   const uint8_t *buf, int buf_size)
251 {
252     PGSSubContext *ctx = avctx->priv_data;
253
254     const uint8_t *buf_end = buf + buf_size;
255     const uint8_t *cm      = ff_cropTbl + MAX_NEG_CROP;
256     int color_id;
257     int y, cb, cr, alpha;
258     int r, g, b, r_add, g_add, b_add;
259
260     /* Skip two null bytes */
261     buf += 2;
262
263     while (buf < buf_end) {
264         color_id  = bytestream_get_byte(&buf);
265         y         = bytestream_get_byte(&buf);
266         cr        = bytestream_get_byte(&buf);
267         cb        = bytestream_get_byte(&buf);
268         alpha     = bytestream_get_byte(&buf);
269
270         YUV_TO_RGB1(cb, cr);
271         YUV_TO_RGB2(r, g, b, y);
272
273         av_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
274
275         /* Store color in palette */
276         ctx->clut[color_id] = RGBA(r,g,b,alpha);
277     }
278 }
279
280 /**
281  * Parse the presentation segment packet.
282  *
283  * The presentation segment contains details on the video
284  * width, video height, x & y subtitle position.
285  *
286  * @param avctx contains the current codec context
287  * @param buf pointer to the packet to process
288  * @param buf_size size of packet to process
289  * @todo TODO: Implement cropping
290  */
291 static void parse_presentation_segment(AVCodecContext *avctx,
292                                        const uint8_t *buf, int buf_size)
293 {
294     PGSSubContext *ctx = avctx->priv_data;
295
296     int w = bytestream_get_be16(&buf);
297     int h = bytestream_get_be16(&buf);
298
299     uint16_t object_index;
300
301     av_dlog(avctx, "Video Dimensions %dx%d\n",
302             w, h);
303     if (av_image_check_size(w, h, 0, avctx) >= 0)
304         avcodec_set_dimensions(avctx, w, h);
305
306     /* Skip 1 bytes of unknown, frame rate? */
307     buf++;
308
309     ctx->presentation.id_number = bytestream_get_be16(&buf);
310
311     /*
312      * Skip 3 bytes of unknown:
313      *     state
314      *     palette_update_flag (0x80),
315      *     palette_id_to_use,
316      */
317     buf += 3;
318
319     ctx->presentation.object_count = bytestream_get_byte(&buf);
320     if (!ctx->presentation.object_count)
321         return;
322
323     /* Verify that enough bytes are remaining for all of the objects. */
324     buf_size -= 11;
325     if (buf_size < ctx->presentation.object_count * 8) {
326         ctx->presentation.object_count = 0;
327         return;
328     }
329
330     av_freep(&ctx->presentation.objects);
331     ctx->presentation.objects = av_malloc(sizeof(PGSSubPictureReference) * ctx->presentation.object_count);
332     if (!ctx->presentation.objects) {
333         ctx->presentation.object_count = 0;
334         return;
335     }
336
337     for (object_index = 0; object_index < ctx->presentation.object_count; ++object_index) {
338         PGSSubPictureReference *reference = &ctx->presentation.objects[object_index];
339         reference->picture_id             = bytestream_get_be16(&buf);
340
341         /* Skip window_id_ref */
342         buf++;
343         /* composition_flag (0x80 - object cropped, 0x40 - object forced) */
344         reference->composition = bytestream_get_byte(&buf);
345
346         reference->x = bytestream_get_be16(&buf);
347         reference->y = bytestream_get_be16(&buf);
348
349         /* TODO If cropping, cropping_x, cropping_y, cropping_width, cropping_height (all 2 bytes).*/
350         av_dlog(avctx, "Subtitle Placement ID=%d, x=%d, y=%d\n", reference->picture_id, reference->x, reference->y);
351
352         if (reference->x > avctx->width || reference->y > avctx->height) {
353             av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
354                    reference->x, reference->y, avctx->width, avctx->height);
355             reference->x = 0;
356             reference->y = 0;
357         }
358     }
359 }
360
361 /**
362  * Parse the display segment packet.
363  *
364  * The display segment controls the updating of the display.
365  *
366  * @param avctx contains the current codec context
367  * @param data pointer to the data pertaining the subtitle to display
368  * @param buf pointer to the packet to process
369  * @param buf_size size of packet to process
370  * @todo TODO: Fix start time, relies on correct PTS, currently too late
371  *
372  * @todo TODO: Fix end time, normally cleared by a second display
373  * @todo       segment, which is currently ignored as it clears
374  * @todo       the subtitle too early.
375  */
376 static int display_end_segment(AVCodecContext *avctx, void *data,
377                                const uint8_t *buf, int buf_size)
378 {
379     AVSubtitle    *sub = data;
380     PGSSubContext *ctx = avctx->priv_data;
381
382     uint16_t rect;
383
384     /*
385      *      The end display time is a timeout value and is only reached
386      *      if the next subtitle is later than timeout or subtitle has
387      *      not been cleared by a subsequent empty display command.
388      */
389
390     memset(sub, 0, sizeof(*sub));
391
392     // Blank if last object_count was 0.
393     if (!ctx->presentation.object_count)
394         return 1;
395
396     sub->start_display_time = 0;
397     sub->end_display_time   = 20000;
398     sub->format             = 0;
399
400     sub->num_rects = ctx->presentation.object_count;
401     sub->rects     = av_mallocz(sizeof(*sub->rects) * sub->num_rects);
402
403     for (rect = 0; rect < sub->num_rects; ++rect) {
404         uint16_t picture_id    = ctx->presentation.objects[rect].picture_id;
405         sub->rects[rect]       = av_mallocz(sizeof(*sub->rects[rect]));
406         sub->rects[rect]->x    = ctx->presentation.objects[rect].x;
407         sub->rects[rect]->y    = ctx->presentation.objects[rect].y;
408         sub->rects[rect]->w    = ctx->pictures[picture_id].w;
409         sub->rects[rect]->h    = ctx->pictures[picture_id].h;
410         sub->rects[rect]->type = SUBTITLE_BITMAP;
411
412         /* Process bitmap */
413         sub->rects[rect]->pict.linesize[0] = ctx->pictures[picture_id].w;
414         if (ctx->pictures[picture_id].rle) {
415             if (ctx->pictures[picture_id].rle_remaining_len)
416                 av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
417                        ctx->pictures[picture_id].rle_data_len, ctx->pictures[picture_id].rle_remaining_len);
418             if (decode_rle(avctx, sub, rect, ctx->pictures[picture_id].rle, ctx->pictures[picture_id].rle_data_len) < 0)
419                 return 0;
420         }
421
422         /* Allocate memory for colors */
423         sub->rects[rect]->nb_colors    = 256;
424         sub->rects[rect]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
425
426         if (!ctx->forced_subs_only || ctx->presentation.objects[rect].composition & 0x40)
427         memcpy(sub->rects[rect]->pict.data[1], ctx->clut, sub->rects[rect]->nb_colors * sizeof(uint32_t));
428     }
429
430     return 1;
431 }
432
433 static int decode(AVCodecContext *avctx, void *data, int *data_size,
434                   AVPacket *avpkt)
435 {
436     const uint8_t *buf = avpkt->data;
437     int buf_size       = avpkt->size;
438
439     const uint8_t *buf_end;
440     uint8_t       segment_type;
441     int           segment_length;
442     int i;
443
444     av_dlog(avctx, "PGS sub packet:\n");
445
446     for (i = 0; i < buf_size; i++) {
447         av_dlog(avctx, "%02x ", buf[i]);
448         if (i % 16 == 15)
449             av_dlog(avctx, "\n");
450     }
451
452     if (i & 15)
453         av_dlog(avctx, "\n");
454
455     *data_size = 0;
456
457     /* Ensure that we have received at a least a segment code and segment length */
458     if (buf_size < 3)
459         return -1;
460
461     buf_end = buf + buf_size;
462
463     /* Step through buffer to identify segments */
464     while (buf < buf_end) {
465         segment_type   = bytestream_get_byte(&buf);
466         segment_length = bytestream_get_be16(&buf);
467
468         av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
469
470         if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
471             break;
472
473         switch (segment_type) {
474         case PALETTE_SEGMENT:
475             parse_palette_segment(avctx, buf, segment_length);
476             break;
477         case PICTURE_SEGMENT:
478             parse_picture_segment(avctx, buf, segment_length);
479             break;
480         case PRESENTATION_SEGMENT:
481             parse_presentation_segment(avctx, buf, segment_length);
482             break;
483         case WINDOW_SEGMENT:
484             /*
485              * Window Segment Structure (No new information provided):
486              *     2 bytes: Unknown,
487              *     2 bytes: X position of subtitle,
488              *     2 bytes: Y position of subtitle,
489              *     2 bytes: Width of subtitle,
490              *     2 bytes: Height of subtitle.
491              */
492             break;
493         case DISPLAY_SEGMENT:
494             *data_size = display_end_segment(avctx, data, buf, segment_length);
495             break;
496         default:
497             av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",
498                    segment_type, segment_length);
499             break;
500         }
501
502         buf += segment_length;
503     }
504
505     return buf_size;
506 }
507
508 #define OFFSET(x) offsetof(PGSSubContext, x)
509 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
510 static const AVOption options[] = {
511     {"forced_subs_only", "Only show forced subtitles", OFFSET(forced_subs_only), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 1, SD},
512     { NULL },
513 };
514
515 static const AVClass pgsdec_class = {
516     .class_name = "PGS subtitle decoder",
517     .item_name  = av_default_item_name,
518     .option     = options,
519     .version    = LIBAVUTIL_VERSION_INT,
520 };
521
522 AVCodec ff_pgssub_decoder = {
523     .name           = "pgssub",
524     .type           = AVMEDIA_TYPE_SUBTITLE,
525     .id             = CODEC_ID_HDMV_PGS_SUBTITLE,
526     .priv_data_size = sizeof(PGSSubContext),
527     .init           = init_decoder,
528     .close          = close_decoder,
529     .decode         = decode,
530     .long_name      = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"),
531     .priv_class     = &pgsdec_class,
532 };