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