3 * Copyright (c) 2009 Stephen Backway
5 * This file is part of FFmpeg.
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.
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.
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
24 * PGS subtitle decoder
29 #include "bytestream.h"
30 #include "libavutil/colorspace.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/opt.h"
34 #define RGBA(r,g,b,a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))
37 PALETTE_SEGMENT = 0x14,
38 PICTURE_SEGMENT = 0x15,
39 PRESENTATION_SEGMENT = 0x16,
40 WINDOW_SEGMENT = 0x17,
41 DISPLAY_SEGMENT = 0x80,
44 typedef struct PGSSubPictureReference {
49 } PGSSubPictureReference;
51 typedef struct PGSSubPresentation {
54 PGSSubPictureReference *objects;
58 typedef struct PGSSubPicture {
62 unsigned int rle_buffer_size, rle_data_len;
63 unsigned int rle_remaining_len;
66 typedef struct PGSSubContext {
68 PGSSubPresentation presentation;
70 PGSSubPicture pictures[UINT16_MAX];
74 static av_cold int init_decoder(AVCodecContext *avctx)
76 avctx->pix_fmt = AV_PIX_FMT_PAL8;
81 static av_cold int close_decoder(AVCodecContext *avctx)
85 PGSSubContext *ctx = avctx->priv_data;
87 av_freep(&ctx->presentation.objects);
88 ctx->presentation.object_count = 0;
90 for (picture = 0; picture < UINT16_MAX; ++picture) {
91 av_freep(&ctx->pictures[picture].rle);
92 ctx->pictures[picture].rle_buffer_size = 0;
99 * Decode the RLE data.
101 * The subtitle is stored as an Run Length Encoded image.
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
108 static int decode_rle(AVCodecContext *avctx, AVSubtitle *sub, int rect,
109 const uint8_t *buf, unsigned int buf_size)
111 const uint8_t *rle_bitmap_end;
112 int pixel_count, line_count;
114 rle_bitmap_end = buf + buf_size;
116 sub->rects[rect]->pict.data[0] = av_malloc(sub->rects[rect]->w * sub->rects[rect]->h);
118 if (!sub->rects[rect]->pict.data[0])
124 while (buf < rle_bitmap_end && line_count < sub->rects[rect]->h) {
125 uint8_t flags, color;
128 color = bytestream_get_byte(&buf);
132 flags = bytestream_get_byte(&buf);
135 run = (run << 8) + bytestream_get_byte(&buf);
136 color = flags & 0x80 ? bytestream_get_byte(&buf) : 0;
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);
144 * New Line. Check if correct pixels decoded, if not display warning
145 * and adjust bitmap pointer to correct new line position.
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);
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");
159 av_dlog(avctx, "Pixel Count = %d, Area = %d\n", pixel_count, sub->rects[rect]->w * sub->rects[rect]->h);
165 * Parse the picture segment packet.
167 * The picture segment contains details on the sequence id,
168 * width, height and Run Length Encoded (RLE) bitmap data.
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
175 static int parse_picture_segment(AVCodecContext *avctx,
176 const uint8_t *buf, int buf_size)
178 PGSSubContext *ctx = avctx->priv_data;
180 uint8_t sequence_desc;
181 unsigned int rle_bitmap_len, width, height;
188 picture_id = bytestream_get_be16(&buf);
190 /* skip 1 unknown byte: Version Number */
193 /* Read the Sequence Description to determine if start of RLE data or appended to previous RLE */
194 sequence_desc = bytestream_get_byte(&buf);
196 if (!(sequence_desc & 0x80)) {
197 /* Additional RLE data */
198 if (buf_size > ctx->pictures[picture_id].rle_remaining_len)
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;
212 /* Decode rle bitmap length, stored size includes width/height data */
213 rle_bitmap_len = bytestream_get_be24(&buf) - 2*2;
215 /* Get bitmap dimensions from data */
216 width = bytestream_get_be16(&buf);
217 height = bytestream_get_be16(&buf);
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");
225 if (buf_size > rle_bitmap_len) {
226 av_log(avctx, AV_LOG_ERROR, "too much RLE data\n");
227 return AVERROR_INVALIDDATA;
230 ctx->pictures[picture_id].w = width;
231 ctx->pictures[picture_id].h = height;
233 av_fast_malloc(&ctx->pictures[picture_id].rle, &ctx->pictures[picture_id].rle_buffer_size, rle_bitmap_len);
235 if (!ctx->pictures[picture_id].rle)
238 memcpy(ctx->pictures[picture_id].rle, buf, buf_size);
239 ctx->pictures[picture_id].rle_data_len = buf_size;
240 ctx->pictures[picture_id].rle_remaining_len = rle_bitmap_len - buf_size;
246 * Parse the palette segment packet.
248 * The palette segment contains details of the palette,
249 * a maximum of 256 colors can be defined.
251 * @param avctx contains the current codec context
252 * @param buf pointer to the packet to process
253 * @param buf_size size of packet to process
255 static void parse_palette_segment(AVCodecContext *avctx,
256 const uint8_t *buf, int buf_size)
258 PGSSubContext *ctx = avctx->priv_data;
260 const uint8_t *buf_end = buf + buf_size;
261 const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
263 int y, cb, cr, alpha;
264 int r, g, b, r_add, g_add, b_add;
266 /* Skip two null bytes */
269 while (buf < buf_end) {
270 color_id = bytestream_get_byte(&buf);
271 y = bytestream_get_byte(&buf);
272 cr = bytestream_get_byte(&buf);
273 cb = bytestream_get_byte(&buf);
274 alpha = bytestream_get_byte(&buf);
277 YUV_TO_RGB2(r, g, b, y);
279 av_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
281 /* Store color in palette */
282 ctx->clut[color_id] = RGBA(r,g,b,alpha);
287 * Parse the presentation segment packet.
289 * The presentation segment contains details on the video
290 * width, video height, x & y subtitle position.
292 * @param avctx contains the current codec context
293 * @param buf pointer to the packet to process
294 * @param buf_size size of packet to process
295 * @todo TODO: Implement cropping
297 static void parse_presentation_segment(AVCodecContext *avctx,
298 const uint8_t *buf, int buf_size,
301 PGSSubContext *ctx = avctx->priv_data;
303 int w = bytestream_get_be16(&buf);
304 int h = bytestream_get_be16(&buf);
306 uint16_t object_index;
308 ctx->presentation.pts = pts;
310 av_dlog(avctx, "Video Dimensions %dx%d\n",
312 if (av_image_check_size(w, h, 0, avctx) >= 0)
313 avcodec_set_dimensions(avctx, w, h);
315 /* Skip 1 bytes of unknown, frame rate? */
318 ctx->presentation.id_number = bytestream_get_be16(&buf);
321 * Skip 3 bytes of unknown:
323 * palette_update_flag (0x80),
328 ctx->presentation.object_count = bytestream_get_byte(&buf);
329 if (!ctx->presentation.object_count)
332 /* Verify that enough bytes are remaining for all of the objects. */
334 if (buf_size < ctx->presentation.object_count * 8) {
335 ctx->presentation.object_count = 0;
339 av_freep(&ctx->presentation.objects);
340 ctx->presentation.objects = av_malloc(sizeof(PGSSubPictureReference) * ctx->presentation.object_count);
341 if (!ctx->presentation.objects) {
342 ctx->presentation.object_count = 0;
346 for (object_index = 0; object_index < ctx->presentation.object_count; ++object_index) {
347 PGSSubPictureReference *reference = &ctx->presentation.objects[object_index];
348 reference->picture_id = bytestream_get_be16(&buf);
350 /* Skip window_id_ref */
352 /* composition_flag (0x80 - object cropped, 0x40 - object forced) */
353 reference->composition = bytestream_get_byte(&buf);
355 reference->x = bytestream_get_be16(&buf);
356 reference->y = bytestream_get_be16(&buf);
358 /* TODO If cropping, cropping_x, cropping_y, cropping_width, cropping_height (all 2 bytes).*/
359 av_dlog(avctx, "Subtitle Placement ID=%d, x=%d, y=%d\n", reference->picture_id, reference->x, reference->y);
361 if (reference->x > avctx->width || reference->y > avctx->height) {
362 av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
363 reference->x, reference->y, avctx->width, avctx->height);
371 * Parse the display segment packet.
373 * The display segment controls the updating of the display.
375 * @param avctx contains the current codec context
376 * @param data pointer to the data pertaining the subtitle to display
377 * @param buf pointer to the packet to process
378 * @param buf_size size of packet to process
379 * @todo TODO: Fix start time, relies on correct PTS, currently too late
381 * @todo TODO: Fix end time, normally cleared by a second display
382 * @todo segment, which is currently ignored as it clears
383 * @todo the subtitle too early.
385 static int display_end_segment(AVCodecContext *avctx, void *data,
386 const uint8_t *buf, int buf_size)
388 AVSubtitle *sub = data;
389 PGSSubContext *ctx = avctx->priv_data;
395 * The end display time is a timeout value and is only reached
396 * if the next subtitle is later than timeout or subtitle has
397 * not been cleared by a subsequent empty display command.
400 pts = ctx->presentation.pts != AV_NOPTS_VALUE ? ctx->presentation.pts : sub->pts;
401 memset(sub, 0, sizeof(*sub));
403 ctx->presentation.pts = AV_NOPTS_VALUE;
405 // Blank if last object_count was 0.
406 if (!ctx->presentation.object_count)
409 sub->start_display_time = 0;
410 sub->end_display_time = 20000;
413 sub->num_rects = ctx->presentation.object_count;
414 sub->rects = av_mallocz(sizeof(*sub->rects) * sub->num_rects);
416 for (rect = 0; rect < sub->num_rects; ++rect) {
417 uint16_t picture_id = ctx->presentation.objects[rect].picture_id;
418 sub->rects[rect] = av_mallocz(sizeof(*sub->rects[rect]));
419 sub->rects[rect]->x = ctx->presentation.objects[rect].x;
420 sub->rects[rect]->y = ctx->presentation.objects[rect].y;
421 sub->rects[rect]->w = ctx->pictures[picture_id].w;
422 sub->rects[rect]->h = ctx->pictures[picture_id].h;
423 sub->rects[rect]->type = SUBTITLE_BITMAP;
426 sub->rects[rect]->pict.linesize[0] = ctx->pictures[picture_id].w;
427 if (ctx->pictures[picture_id].rle) {
428 if (ctx->pictures[picture_id].rle_remaining_len)
429 av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
430 ctx->pictures[picture_id].rle_data_len, ctx->pictures[picture_id].rle_remaining_len);
431 if (decode_rle(avctx, sub, rect, ctx->pictures[picture_id].rle, ctx->pictures[picture_id].rle_data_len) < 0)
435 /* Allocate memory for colors */
436 sub->rects[rect]->nb_colors = 256;
437 sub->rects[rect]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
439 /* Copy the forced flag */
440 sub->rects[rect]->flags = (ctx->presentation.objects[rect].composition & 0x40) != 0 ? AV_SUBTITLE_FLAG_FORCED : 0;
442 if (!ctx->forced_subs_only || ctx->presentation.objects[rect].composition & 0x40)
443 memcpy(sub->rects[rect]->pict.data[1], ctx->clut, sub->rects[rect]->nb_colors * sizeof(uint32_t));
449 static int decode(AVCodecContext *avctx, void *data, int *data_size,
452 PGSSubContext *ctx = avctx->priv_data;
453 const uint8_t *buf = avpkt->data;
454 int buf_size = avpkt->size;
455 AVSubtitle *sub = data;
457 const uint8_t *buf_end;
458 uint8_t segment_type;
462 av_dlog(avctx, "PGS sub packet:\n");
464 for (i = 0; i < buf_size; i++) {
465 av_dlog(avctx, "%02x ", buf[i]);
467 av_dlog(avctx, "\n");
471 av_dlog(avctx, "\n");
475 /* Ensure that we have received at a least a segment code and segment length */
479 buf_end = buf + buf_size;
481 /* Step through buffer to identify segments */
482 while (buf < buf_end) {
483 segment_type = bytestream_get_byte(&buf);
484 segment_length = bytestream_get_be16(&buf);
486 av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
488 if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
491 switch (segment_type) {
492 case PALETTE_SEGMENT:
493 parse_palette_segment(avctx, buf, segment_length);
495 case PICTURE_SEGMENT:
496 parse_picture_segment(avctx, buf, segment_length);
498 case PRESENTATION_SEGMENT:
499 parse_presentation_segment(avctx, buf, segment_length, sub->pts);
503 * Window Segment Structure (No new information provided):
505 * 2 bytes: X position of subtitle,
506 * 2 bytes: Y position of subtitle,
507 * 2 bytes: Width of subtitle,
508 * 2 bytes: Height of subtitle.
511 case DISPLAY_SEGMENT:
512 *data_size = display_end_segment(avctx, data, buf, segment_length);
515 av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",
516 segment_type, segment_length);
520 buf += segment_length;
526 #define OFFSET(x) offsetof(PGSSubContext, x)
527 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
528 static const AVOption options[] = {
529 {"forced_subs_only", "Only show forced subtitles", OFFSET(forced_subs_only), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, SD},
533 static const AVClass pgsdec_class = {
534 .class_name = "PGS subtitle decoder",
535 .item_name = av_default_item_name,
537 .version = LIBAVUTIL_VERSION_INT,
540 AVCodec ff_pgssub_decoder = {
542 .type = AVMEDIA_TYPE_SUBTITLE,
543 .id = AV_CODEC_ID_HDMV_PGS_SUBTITLE,
544 .priv_data_size = sizeof(PGSSubContext),
545 .init = init_decoder,
546 .close = close_decoder,
548 .long_name = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"),
549 .priv_class = &pgsdec_class,