OSDN Git Service

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