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
28 #include "bytestream.h"
32 #include "libavutil/colorspace.h"
33 #include "libavutil/imgutils.h"
34 #include "libavutil/opt.h"
36 #define RGBA(r,g,b,a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))
39 PALETTE_SEGMENT = 0x14,
40 PICTURE_SEGMENT = 0x15,
41 PRESENTATION_SEGMENT = 0x16,
42 WINDOW_SEGMENT = 0x17,
43 DISPLAY_SEGMENT = 0x80,
46 typedef struct PGSSubPictureReference {
51 } PGSSubPictureReference;
53 typedef struct PGSSubPresentation {
56 PGSSubPictureReference *objects;
60 typedef struct PGSSubPicture {
64 unsigned int rle_buffer_size, rle_data_len;
65 unsigned int rle_remaining_len;
68 typedef struct PGSSubContext {
70 PGSSubPresentation presentation;
72 PGSSubPicture pictures[UINT16_MAX];
76 static av_cold int init_decoder(AVCodecContext *avctx)
78 avctx->pix_fmt = AV_PIX_FMT_PAL8;
83 static av_cold int close_decoder(AVCodecContext *avctx)
87 PGSSubContext *ctx = avctx->priv_data;
89 av_freep(&ctx->presentation.objects);
90 ctx->presentation.object_count = 0;
92 for (picture = 0; picture < UINT16_MAX; ++picture) {
93 av_freep(&ctx->pictures[picture].rle);
94 ctx->pictures[picture].rle_buffer_size = 0;
101 * Decode the RLE data.
103 * The subtitle is stored as a Run Length Encoded image.
105 * @param avctx contains the current codec context
106 * @param sub pointer to the processed subtitle data
107 * @param buf pointer to the RLE data to process
108 * @param buf_size size of the RLE data to process
110 static int decode_rle(AVCodecContext *avctx, AVSubtitle *sub, int rect,
111 const uint8_t *buf, unsigned int buf_size)
113 const uint8_t *rle_bitmap_end;
114 int pixel_count, line_count;
116 rle_bitmap_end = buf + buf_size;
118 sub->rects[rect]->pict.data[0] = av_malloc(sub->rects[rect]->w * sub->rects[rect]->h);
120 if (!sub->rects[rect]->pict.data[0])
126 while (buf < rle_bitmap_end && line_count < sub->rects[rect]->h) {
127 uint8_t flags, color;
130 color = bytestream_get_byte(&buf);
134 flags = bytestream_get_byte(&buf);
137 run = (run << 8) + bytestream_get_byte(&buf);
138 color = flags & 0x80 ? bytestream_get_byte(&buf) : 0;
141 if (run > 0 && pixel_count + run <= sub->rects[rect]->w * sub->rects[rect]->h) {
142 memset(sub->rects[rect]->pict.data[0] + pixel_count, color, run);
146 * New Line. Check if correct pixels decoded, if not display warning
147 * and adjust bitmap pointer to correct new line position.
149 if (pixel_count % sub->rects[rect]->w > 0)
150 av_log(avctx, AV_LOG_ERROR, "Decoded %d pixels, when line should be %d pixels\n",
151 pixel_count % sub->rects[rect]->w, sub->rects[rect]->w);
156 if (pixel_count < sub->rects[rect]->w * sub->rects[rect]->h) {
157 av_log(avctx, AV_LOG_ERROR, "Insufficient RLE data for subtitle\n");
161 av_dlog(avctx, "Pixel Count = %d, Area = %d\n", pixel_count, sub->rects[rect]->w * sub->rects[rect]->h);
167 * Parse the picture segment packet.
169 * The picture segment contains details on the sequence id,
170 * width, height and Run Length Encoded (RLE) bitmap data.
172 * @param avctx contains the current codec context
173 * @param buf pointer to the packet to process
174 * @param buf_size size of packet to process
175 * @todo TODO: Enable support for RLE data over multiple packets
177 static int parse_picture_segment(AVCodecContext *avctx,
178 const uint8_t *buf, int buf_size)
180 PGSSubContext *ctx = avctx->priv_data;
182 uint8_t sequence_desc;
183 unsigned int rle_bitmap_len, width, height;
190 picture_id = bytestream_get_be16(&buf);
192 /* skip 1 unknown byte: Version Number */
195 /* Read the Sequence Description to determine if start of RLE data or appended to previous RLE */
196 sequence_desc = bytestream_get_byte(&buf);
198 if (!(sequence_desc & 0x80)) {
199 /* Additional RLE data */
200 if (buf_size > ctx->pictures[picture_id].rle_remaining_len)
203 memcpy(ctx->pictures[picture_id].rle + ctx->pictures[picture_id].rle_data_len, buf, buf_size);
204 ctx->pictures[picture_id].rle_data_len += buf_size;
205 ctx->pictures[picture_id].rle_remaining_len -= buf_size;
214 /* Decode rle bitmap length, stored size includes width/height data */
215 rle_bitmap_len = bytestream_get_be24(&buf) - 2*2;
217 /* Get bitmap dimensions from data */
218 width = bytestream_get_be16(&buf);
219 height = bytestream_get_be16(&buf);
221 /* Make sure the bitmap is not too large */
222 if (avctx->width < width || avctx->height < height) {
223 av_log(avctx, AV_LOG_ERROR, "Bitmap dimensions larger than video.\n");
227 if (buf_size > rle_bitmap_len) {
228 av_log(avctx, AV_LOG_ERROR, "too much RLE data\n");
229 return AVERROR_INVALIDDATA;
232 ctx->pictures[picture_id].w = width;
233 ctx->pictures[picture_id].h = height;
235 av_fast_padded_malloc(&ctx->pictures[picture_id].rle, &ctx->pictures[picture_id].rle_buffer_size, rle_bitmap_len);
237 if (!ctx->pictures[picture_id].rle)
240 memcpy(ctx->pictures[picture_id].rle, buf, buf_size);
241 ctx->pictures[picture_id].rle_data_len = buf_size;
242 ctx->pictures[picture_id].rle_remaining_len = rle_bitmap_len - buf_size;
248 * Parse the palette segment packet.
250 * The palette segment contains details of the palette,
251 * a maximum of 256 colors can be defined.
253 * @param avctx contains the current codec context
254 * @param buf pointer to the packet to process
255 * @param buf_size size of packet to process
257 static void parse_palette_segment(AVCodecContext *avctx,
258 const uint8_t *buf, int buf_size)
260 PGSSubContext *ctx = avctx->priv_data;
262 const uint8_t *buf_end = buf + buf_size;
263 const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;
265 int y, cb, cr, alpha;
266 int r, g, b, r_add, g_add, b_add;
268 /* Skip two null bytes */
271 while (buf < buf_end) {
272 color_id = bytestream_get_byte(&buf);
273 y = bytestream_get_byte(&buf);
274 cr = bytestream_get_byte(&buf);
275 cb = bytestream_get_byte(&buf);
276 alpha = bytestream_get_byte(&buf);
279 YUV_TO_RGB2(r, g, b, y);
281 av_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
283 /* Store color in palette */
284 ctx->clut[color_id] = RGBA(r,g,b,alpha);
289 * Parse the presentation segment packet.
291 * The presentation segment contains details on the video
292 * width, video height, x & y subtitle position.
294 * @param avctx contains the current codec context
295 * @param buf pointer to the packet to process
296 * @param buf_size size of packet to process
297 * @todo TODO: Implement cropping
299 static int parse_presentation_segment(AVCodecContext *avctx,
300 const uint8_t *buf, int buf_size,
303 PGSSubContext *ctx = avctx->priv_data;
306 int w = bytestream_get_be16(&buf);
307 int h = bytestream_get_be16(&buf);
309 uint16_t object_index;
311 ctx->presentation.pts = pts;
313 av_dlog(avctx, "Video Dimensions %dx%d\n",
315 ret = ff_set_dimensions(avctx, w, h);
319 /* Skip 1 bytes of unknown, frame rate? */
322 ctx->presentation.id_number = bytestream_get_be16(&buf);
325 * Skip 3 bytes of unknown:
327 * palette_update_flag (0x80),
332 ctx->presentation.object_count = bytestream_get_byte(&buf);
333 if (!ctx->presentation.object_count)
336 /* Verify that enough bytes are remaining for all of the objects. */
338 if (buf_size < ctx->presentation.object_count * 8) {
339 ctx->presentation.object_count = 0;
340 return AVERROR_INVALIDDATA;
343 av_freep(&ctx->presentation.objects);
344 ctx->presentation.objects = av_malloc(sizeof(PGSSubPictureReference) * ctx->presentation.object_count);
345 if (!ctx->presentation.objects) {
346 ctx->presentation.object_count = 0;
347 return AVERROR(ENOMEM);
350 for (object_index = 0; object_index < ctx->presentation.object_count; ++object_index) {
351 PGSSubPictureReference *reference = &ctx->presentation.objects[object_index];
352 reference->picture_id = bytestream_get_be16(&buf);
354 /* Skip window_id_ref */
356 /* composition_flag (0x80 - object cropped, 0x40 - object forced) */
357 reference->composition = bytestream_get_byte(&buf);
359 reference->x = bytestream_get_be16(&buf);
360 reference->y = bytestream_get_be16(&buf);
362 /* TODO If cropping, cropping_x, cropping_y, cropping_width, cropping_height (all 2 bytes).*/
363 av_dlog(avctx, "Subtitle Placement ID=%d, x=%d, y=%d\n", reference->picture_id, reference->x, reference->y);
365 if (reference->x > avctx->width || reference->y > avctx->height) {
366 av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
367 reference->x, reference->y, avctx->width, avctx->height);
377 * Parse the display segment packet.
379 * The display segment controls the updating of the display.
381 * @param avctx contains the current codec context
382 * @param data pointer to the data pertaining the subtitle to display
383 * @param buf pointer to the packet to process
384 * @param buf_size size of packet to process
385 * @todo TODO: Fix start time, relies on correct PTS, currently too late
387 * @todo TODO: Fix end time, normally cleared by a second display
388 * @todo segment, which is currently ignored as it clears
389 * @todo the subtitle too early.
391 static int display_end_segment(AVCodecContext *avctx, void *data,
392 const uint8_t *buf, int buf_size)
394 AVSubtitle *sub = data;
395 PGSSubContext *ctx = avctx->priv_data;
401 * The end display time is a timeout value and is only reached
402 * if the next subtitle is later than timeout or subtitle has
403 * not been cleared by a subsequent empty display command.
406 pts = ctx->presentation.pts != AV_NOPTS_VALUE ? ctx->presentation.pts : sub->pts;
407 memset(sub, 0, sizeof(*sub));
409 ctx->presentation.pts = AV_NOPTS_VALUE;
411 // Blank if last object_count was 0.
412 if (!ctx->presentation.object_count)
415 sub->start_display_time = 0;
416 sub->end_display_time = 20000;
419 sub->num_rects = ctx->presentation.object_count;
420 sub->rects = av_mallocz(sizeof(*sub->rects) * sub->num_rects);
422 for (rect = 0; rect < sub->num_rects; ++rect) {
423 uint16_t picture_id = ctx->presentation.objects[rect].picture_id;
424 sub->rects[rect] = av_mallocz(sizeof(*sub->rects[rect]));
425 sub->rects[rect]->x = ctx->presentation.objects[rect].x;
426 sub->rects[rect]->y = ctx->presentation.objects[rect].y;
427 sub->rects[rect]->w = ctx->pictures[picture_id].w;
428 sub->rects[rect]->h = ctx->pictures[picture_id].h;
429 sub->rects[rect]->type = SUBTITLE_BITMAP;
432 sub->rects[rect]->pict.linesize[0] = ctx->pictures[picture_id].w;
433 if (ctx->pictures[picture_id].rle) {
434 if (ctx->pictures[picture_id].rle_remaining_len)
435 av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
436 ctx->pictures[picture_id].rle_data_len, ctx->pictures[picture_id].rle_remaining_len);
437 if (decode_rle(avctx, sub, rect, ctx->pictures[picture_id].rle, ctx->pictures[picture_id].rle_data_len) < 0)
441 /* Allocate memory for colors */
442 sub->rects[rect]->nb_colors = 256;
443 sub->rects[rect]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
445 /* Copy the forced flag */
446 sub->rects[rect]->flags = (ctx->presentation.objects[rect].composition & 0x40) != 0 ? AV_SUBTITLE_FLAG_FORCED : 0;
448 if (!ctx->forced_subs_only || ctx->presentation.objects[rect].composition & 0x40)
449 memcpy(sub->rects[rect]->pict.data[1], ctx->clut, sub->rects[rect]->nb_colors * sizeof(uint32_t));
455 static int decode(AVCodecContext *avctx, void *data, int *data_size,
458 const uint8_t *buf = avpkt->data;
459 int buf_size = avpkt->size;
460 AVSubtitle *sub = data;
462 const uint8_t *buf_end;
463 uint8_t segment_type;
467 av_dlog(avctx, "PGS sub packet:\n");
469 for (i = 0; i < buf_size; i++) {
470 av_dlog(avctx, "%02x ", buf[i]);
472 av_dlog(avctx, "\n");
476 av_dlog(avctx, "\n");
480 /* Ensure that we have received at a least a segment code and segment length */
484 buf_end = buf + buf_size;
486 /* Step through buffer to identify segments */
487 while (buf < buf_end) {
488 segment_type = bytestream_get_byte(&buf);
489 segment_length = bytestream_get_be16(&buf);
491 av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
493 if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
496 switch (segment_type) {
497 case PALETTE_SEGMENT:
498 parse_palette_segment(avctx, buf, segment_length);
500 case PICTURE_SEGMENT:
501 parse_picture_segment(avctx, buf, segment_length);
503 case PRESENTATION_SEGMENT:
504 ret = parse_presentation_segment(avctx, buf, segment_length, sub->pts);
510 * Window Segment Structure (No new information provided):
512 * 2 bytes: X position of subtitle,
513 * 2 bytes: Y position of subtitle,
514 * 2 bytes: Width of subtitle,
515 * 2 bytes: Height of subtitle.
518 case DISPLAY_SEGMENT:
519 *data_size = display_end_segment(avctx, data, buf, segment_length);
522 av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",
523 segment_type, segment_length);
527 buf += segment_length;
533 #define OFFSET(x) offsetof(PGSSubContext, x)
534 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
535 static const AVOption options[] = {
536 {"forced_subs_only", "Only show forced subtitles", OFFSET(forced_subs_only), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, SD},
540 static const AVClass pgsdec_class = {
541 .class_name = "PGS subtitle decoder",
542 .item_name = av_default_item_name,
544 .version = LIBAVUTIL_VERSION_INT,
547 AVCodec ff_pgssub_decoder = {
549 .long_name = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"),
550 .type = AVMEDIA_TYPE_SUBTITLE,
551 .id = AV_CODEC_ID_HDMV_PGS_SUBTITLE,
552 .priv_data_size = sizeof(PGSSubContext),
553 .init = init_decoder,
554 .close = close_decoder,
556 .priv_class = &pgsdec_class,