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))
37 #define MAX_EPOCH_PALETTES 8 // Max 8 allowed per PGS epoch
38 #define MAX_EPOCH_OBJECTS 64 // Max 64 allowed per PGS epoch
39 #define MAX_OBJECT_REFS 2 // Max objects per display set
42 PALETTE_SEGMENT = 0x14,
43 OBJECT_SEGMENT = 0x15,
44 PRESENTATION_SEGMENT = 0x16,
45 WINDOW_SEGMENT = 0x17,
46 DISPLAY_SEGMENT = 0x80,
49 typedef struct PGSSubObjectRef {
52 uint8_t composition_flag;
61 typedef struct PGSSubPresentation {
65 PGSSubObjectRef objects[MAX_OBJECT_REFS];
69 typedef struct PGSSubObject {
74 unsigned int rle_buffer_size, rle_data_len;
75 unsigned int rle_remaining_len;
78 typedef struct PGSSubObjects {
80 PGSSubObject object[MAX_EPOCH_OBJECTS];
83 typedef struct PGSSubPalette {
88 typedef struct PGSSubPalettes {
90 PGSSubPalette palette[MAX_EPOCH_PALETTES];
93 typedef struct PGSSubContext {
95 PGSSubPresentation presentation;
96 PGSSubPalettes palettes;
97 PGSSubObjects objects;
101 static void flush_cache(AVCodecContext *avctx)
103 PGSSubContext *ctx = avctx->priv_data;
106 for (i = 0; i < ctx->objects.count; i++) {
107 av_freep(&ctx->objects.object[i].rle);
108 ctx->objects.object[i].rle_buffer_size = 0;
109 ctx->objects.object[i].rle_remaining_len = 0;
111 ctx->objects.count = 0;
112 ctx->palettes.count = 0;
115 static PGSSubObject * find_object(int id, PGSSubObjects *objects)
119 for (i = 0; i < objects->count; i++) {
120 if (objects->object[i].id == id)
121 return &objects->object[i];
126 static PGSSubPalette * find_palette(int id, PGSSubPalettes *palettes)
130 for (i = 0; i < palettes->count; i++) {
131 if (palettes->palette[i].id == id)
132 return &palettes->palette[i];
137 static av_cold int init_decoder(AVCodecContext *avctx)
139 avctx->pix_fmt = AV_PIX_FMT_PAL8;
144 static av_cold int close_decoder(AVCodecContext *avctx)
152 * Decode the RLE data.
154 * The subtitle is stored as a Run Length Encoded image.
156 * @param avctx contains the current codec context
157 * @param sub pointer to the processed subtitle data
158 * @param buf pointer to the RLE data to process
159 * @param buf_size size of the RLE data to process
161 static int decode_rle(AVCodecContext *avctx, AVSubtitleRect *rect,
162 const uint8_t *buf, unsigned int buf_size)
164 const uint8_t *rle_bitmap_end;
165 int pixel_count, line_count;
167 rle_bitmap_end = buf + buf_size;
169 rect->pict.data[0] = av_malloc_array(rect->w, rect->h);
171 if (!rect->pict.data[0])
172 return AVERROR(ENOMEM);
177 while (buf < rle_bitmap_end && line_count < rect->h) {
178 uint8_t flags, color;
181 color = bytestream_get_byte(&buf);
185 flags = bytestream_get_byte(&buf);
188 run = (run << 8) + bytestream_get_byte(&buf);
189 color = flags & 0x80 ? bytestream_get_byte(&buf) : 0;
192 if (run > 0 && pixel_count + run <= rect->w * rect->h) {
193 memset(rect->pict.data[0] + pixel_count, color, run);
197 * New Line. Check if correct pixels decoded, if not display warning
198 * and adjust bitmap pointer to correct new line position.
200 if (pixel_count % rect->w > 0) {
201 av_log(avctx, AV_LOG_ERROR, "Decoded %d pixels, when line should be %d pixels\n",
202 pixel_count % rect->w, rect->w);
203 if (avctx->err_recognition & AV_EF_EXPLODE) {
204 return AVERROR_INVALIDDATA;
211 if (pixel_count < rect->w * rect->h) {
212 av_log(avctx, AV_LOG_ERROR, "Insufficient RLE data for subtitle\n");
213 return AVERROR_INVALIDDATA;
216 av_dlog(avctx, "Pixel Count = %d, Area = %d\n", pixel_count, rect->w * rect->h);
222 * Parse the picture segment packet.
224 * The picture segment contains details on the sequence id,
225 * width, height and Run Length Encoded (RLE) bitmap data.
227 * @param avctx contains the current codec context
228 * @param buf pointer to the packet to process
229 * @param buf_size size of packet to process
231 static int parse_object_segment(AVCodecContext *avctx,
232 const uint8_t *buf, int buf_size)
234 PGSSubContext *ctx = avctx->priv_data;
235 PGSSubObject *object;
237 uint8_t sequence_desc;
238 unsigned int rle_bitmap_len, width, height;
242 return AVERROR_INVALIDDATA;
245 id = bytestream_get_be16(&buf);
246 object = find_object(id, &ctx->objects);
248 if (ctx->objects.count >= MAX_EPOCH_OBJECTS) {
249 av_log(avctx, AV_LOG_ERROR, "Too many objects in epoch\n");
250 return AVERROR_INVALIDDATA;
252 object = &ctx->objects.object[ctx->objects.count++];
256 /* skip object version number */
259 /* Read the Sequence Description to determine if start of RLE data or appended to previous RLE */
260 sequence_desc = bytestream_get_byte(&buf);
262 if (!(sequence_desc & 0x80)) {
263 /* Additional RLE data */
264 if (buf_size > object->rle_remaining_len)
265 return AVERROR_INVALIDDATA;
267 memcpy(object->rle + object->rle_data_len, buf, buf_size);
268 object->rle_data_len += buf_size;
269 object->rle_remaining_len -= buf_size;
275 return AVERROR_INVALIDDATA;
278 /* Decode rle bitmap length, stored size includes width/height data */
279 rle_bitmap_len = bytestream_get_be24(&buf) - 2*2;
281 if (buf_size > rle_bitmap_len) {
282 av_log(avctx, AV_LOG_ERROR,
283 "Buffer dimension %d larger than the expected RLE data %d\n",
284 buf_size, rle_bitmap_len);
285 return AVERROR_INVALIDDATA;
288 /* Get bitmap dimensions from data */
289 width = bytestream_get_be16(&buf);
290 height = bytestream_get_be16(&buf);
292 /* Make sure the bitmap is not too large */
293 if (avctx->width < width || avctx->height < height) {
294 av_log(avctx, AV_LOG_ERROR, "Bitmap dimensions larger than video.\n");
295 return AVERROR_INVALIDDATA;
301 av_fast_padded_malloc(&object->rle, &object->rle_buffer_size, rle_bitmap_len);
304 return AVERROR(ENOMEM);
306 memcpy(object->rle, buf, buf_size);
307 object->rle_data_len = buf_size;
308 object->rle_remaining_len = rle_bitmap_len - buf_size;
314 * Parse the palette segment packet.
316 * The palette segment contains details of the palette,
317 * a maximum of 256 colors can be defined.
319 * @param avctx contains the current codec context
320 * @param buf pointer to the packet to process
321 * @param buf_size size of packet to process
323 static int parse_palette_segment(AVCodecContext *avctx,
324 const uint8_t *buf, int buf_size)
326 PGSSubContext *ctx = avctx->priv_data;
327 PGSSubPalette *palette;
329 const uint8_t *buf_end = buf + buf_size;
330 const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;
332 int y, cb, cr, alpha;
333 int r, g, b, r_add, g_add, b_add;
336 id = bytestream_get_byte(&buf);
337 palette = find_palette(id, &ctx->palettes);
339 if (ctx->palettes.count >= MAX_EPOCH_PALETTES) {
340 av_log(avctx, AV_LOG_ERROR, "Too many palettes in epoch\n");
341 return AVERROR_INVALIDDATA;
343 palette = &ctx->palettes.palette[ctx->palettes.count++];
347 /* Skip palette version */
350 while (buf < buf_end) {
351 color_id = bytestream_get_byte(&buf);
352 y = bytestream_get_byte(&buf);
353 cr = bytestream_get_byte(&buf);
354 cb = bytestream_get_byte(&buf);
355 alpha = bytestream_get_byte(&buf);
358 YUV_TO_RGB2(r, g, b, y);
360 av_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
362 /* Store color in palette */
363 palette->clut[color_id] = RGBA(r,g,b,alpha);
369 * Parse the presentation segment packet.
371 * The presentation segment contains details on the video
372 * width, video height, x & y subtitle position.
374 * @param avctx contains the current codec context
375 * @param buf pointer to the packet to process
376 * @param buf_size size of packet to process
377 * @todo TODO: Implement cropping
379 static int parse_presentation_segment(AVCodecContext *avctx,
380 const uint8_t *buf, int buf_size,
383 PGSSubContext *ctx = avctx->priv_data;
385 const uint8_t *buf_end = buf + buf_size;
388 int w = bytestream_get_be16(&buf);
389 int h = bytestream_get_be16(&buf);
391 ctx->presentation.pts = pts;
393 av_dlog(avctx, "Video Dimensions %dx%d\n",
395 ret = ff_set_dimensions(avctx, w, h);
399 /* Skip 1 bytes of unknown, frame rate */
402 // Composition descriptor
403 ctx->presentation.id_number = bytestream_get_be16(&buf);
405 * state is a 2 bit field that defines pgs epoch boundaries
406 * 00 - Normal, previously defined objects and palettes are still valid
407 * 01 - Acquisition point, previous objects and palettes can be released
408 * 10 - Epoch start, previous objects and palettes can be released
409 * 11 - Epoch continue, previous objects and palettes can be released
411 * reserved 6 bits discarded
413 state = bytestream_get_byte(&buf) >> 6;
419 * skip palette_update_flag (0x80),
422 ctx->presentation.palette_id = bytestream_get_byte(&buf);
423 ctx->presentation.object_count = bytestream_get_byte(&buf);
424 if (ctx->presentation.object_count > MAX_OBJECT_REFS) {
425 av_log(avctx, AV_LOG_ERROR,
426 "Invalid number of presentation objects %d\n",
427 ctx->presentation.object_count);
428 ctx->presentation.object_count = 2;
429 if (avctx->err_recognition & AV_EF_EXPLODE) {
430 return AVERROR_INVALIDDATA;
435 for (i = 0; i < ctx->presentation.object_count; i++)
438 if (buf_end - buf < 8) {
439 av_log(avctx, AV_LOG_ERROR, "Insufficent space for object\n");
440 ctx->presentation.object_count = i;
441 return AVERROR_INVALIDDATA;
444 ctx->presentation.objects[i].id = bytestream_get_be16(&buf);
445 ctx->presentation.objects[i].window_id = bytestream_get_byte(&buf);
446 ctx->presentation.objects[i].composition_flag = bytestream_get_byte(&buf);
448 ctx->presentation.objects[i].x = bytestream_get_be16(&buf);
449 ctx->presentation.objects[i].y = bytestream_get_be16(&buf);
452 if (ctx->presentation.objects[i].composition_flag & 0x80) {
453 ctx->presentation.objects[i].crop_x = bytestream_get_be16(&buf);
454 ctx->presentation.objects[i].crop_y = bytestream_get_be16(&buf);
455 ctx->presentation.objects[i].crop_w = bytestream_get_be16(&buf);
456 ctx->presentation.objects[i].crop_h = bytestream_get_be16(&buf);
459 av_dlog(avctx, "Subtitle Placement x=%d, y=%d\n",
460 ctx->presentation.objects[i].x, ctx->presentation.objects[i].y);
462 if (ctx->presentation.objects[i].x > avctx->width ||
463 ctx->presentation.objects[i].y > avctx->height) {
464 av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
465 ctx->presentation.objects[i].x,
466 ctx->presentation.objects[i].y,
467 avctx->width, avctx->height);
468 ctx->presentation.objects[i].x = 0;
469 ctx->presentation.objects[i].y = 0;
470 if (avctx->err_recognition & AV_EF_EXPLODE) {
471 return AVERROR_INVALIDDATA;
480 * Parse the display segment packet.
482 * The display segment controls the updating of the display.
484 * @param avctx contains the current codec context
485 * @param data pointer to the data pertaining the subtitle to display
486 * @param buf pointer to the packet to process
487 * @param buf_size size of packet to process
489 static int display_end_segment(AVCodecContext *avctx, void *data,
490 const uint8_t *buf, int buf_size)
492 AVSubtitle *sub = data;
493 PGSSubContext *ctx = avctx->priv_data;
495 PGSSubPalette *palette;
498 pts = ctx->presentation.pts != AV_NOPTS_VALUE ? ctx->presentation.pts : sub->pts;
499 memset(sub, 0, sizeof(*sub));
501 ctx->presentation.pts = AV_NOPTS_VALUE;
502 sub->start_display_time = 0;
503 // There is no explicit end time for PGS subtitles. The end time
504 // is defined by the start of the next sub which may contain no
505 // objects (i.e. clears the previous sub)
506 sub->end_display_time = UINT32_MAX;
509 // Blank if last object_count was 0.
510 if (!ctx->presentation.object_count)
512 sub->rects = av_mallocz_array(ctx->presentation.object_count, sizeof(*sub->rects));
514 return AVERROR(ENOMEM);
516 palette = find_palette(ctx->presentation.palette_id, &ctx->palettes);
518 // Missing palette. Should only happen with damaged streams.
519 av_log(avctx, AV_LOG_ERROR, "Invalid palette id %d\n",
520 ctx->presentation.palette_id);
521 avsubtitle_free(sub);
522 return AVERROR_INVALIDDATA;
524 for (i = 0; i < ctx->presentation.object_count; i++) {
525 PGSSubObject *object;
527 sub->rects[i] = av_mallocz(sizeof(*sub->rects[0]));
528 if (!sub->rects[i]) {
529 avsubtitle_free(sub);
530 return AVERROR(ENOMEM);
533 sub->rects[i]->type = SUBTITLE_BITMAP;
536 object = find_object(ctx->presentation.objects[i].id, &ctx->objects);
538 // Missing object. Should only happen with damaged streams.
539 av_log(avctx, AV_LOG_ERROR, "Invalid object id %d\n",
540 ctx->presentation.objects[i].id);
541 if (avctx->err_recognition & AV_EF_EXPLODE) {
542 avsubtitle_free(sub);
543 return AVERROR_INVALIDDATA;
545 // Leaves rect empty with 0 width and height.
548 if (ctx->presentation.objects[i].composition_flag & 0x40)
549 sub->rects[i]->flags |= AV_SUBTITLE_FLAG_FORCED;
551 sub->rects[i]->x = ctx->presentation.objects[i].x;
552 sub->rects[i]->y = ctx->presentation.objects[i].y;
553 sub->rects[i]->w = object->w;
554 sub->rects[i]->h = object->h;
556 sub->rects[i]->pict.linesize[0] = object->w;
559 if (object->rle_remaining_len) {
560 av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
561 object->rle_data_len, object->rle_remaining_len);
562 if (avctx->err_recognition & AV_EF_EXPLODE) {
563 avsubtitle_free(sub);
564 return AVERROR_INVALIDDATA;
567 ret = decode_rle(avctx, sub->rects[i], object->rle, object->rle_data_len);
569 if ((avctx->err_recognition & AV_EF_EXPLODE) ||
570 ret == AVERROR(ENOMEM)) {
571 avsubtitle_free(sub);
574 sub->rects[i]->w = 0;
575 sub->rects[i]->h = 0;
579 /* Allocate memory for colors */
580 sub->rects[i]->nb_colors = 256;
581 sub->rects[i]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
582 if (!sub->rects[i]->pict.data[1]) {
583 avsubtitle_free(sub);
584 return AVERROR(ENOMEM);
587 if (!ctx->forced_subs_only || ctx->presentation.objects[i].composition_flag & 0x40)
588 memcpy(sub->rects[i]->pict.data[1], palette->clut, sub->rects[i]->nb_colors * sizeof(uint32_t));
594 static int decode(AVCodecContext *avctx, void *data, int *data_size,
597 const uint8_t *buf = avpkt->data;
598 int buf_size = avpkt->size;
600 const uint8_t *buf_end;
601 uint8_t segment_type;
605 av_dlog(avctx, "PGS sub packet:\n");
607 for (i = 0; i < buf_size; i++) {
608 av_dlog(avctx, "%02x ", buf[i]);
610 av_dlog(avctx, "\n");
614 av_dlog(avctx, "\n");
618 /* Ensure that we have received at a least a segment code and segment length */
622 buf_end = buf + buf_size;
624 /* Step through buffer to identify segments */
625 while (buf < buf_end) {
626 segment_type = bytestream_get_byte(&buf);
627 segment_length = bytestream_get_be16(&buf);
629 av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
631 if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
635 switch (segment_type) {
636 case PALETTE_SEGMENT:
637 ret = parse_palette_segment(avctx, buf, segment_length);
640 ret = parse_object_segment(avctx, buf, segment_length);
642 case PRESENTATION_SEGMENT:
643 ret = parse_presentation_segment(avctx, buf, segment_length, ((AVSubtitle*)(data))->pts);
647 * Window Segment Structure (No new information provided):
649 * 2 bytes: X position of subtitle,
650 * 2 bytes: Y position of subtitle,
651 * 2 bytes: Width of subtitle,
652 * 2 bytes: Height of subtitle.
655 case DISPLAY_SEGMENT:
656 ret = display_end_segment(avctx, data, buf, segment_length);
661 av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",
662 segment_type, segment_length);
663 ret = AVERROR_INVALIDDATA;
666 if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
669 buf += segment_length;
675 #define OFFSET(x) offsetof(PGSSubContext, x)
676 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
677 static const AVOption options[] = {
678 {"forced_subs_only", "Only show forced subtitles", OFFSET(forced_subs_only), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, SD},
682 static const AVClass pgsdec_class = {
683 .class_name = "PGS subtitle decoder",
684 .item_name = av_default_item_name,
686 .version = LIBAVUTIL_VERSION_INT,
689 AVCodec ff_pgssub_decoder = {
691 .long_name = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"),
692 .type = AVMEDIA_TYPE_SUBTITLE,
693 .id = AV_CODEC_ID_HDMV_PGS_SUBTITLE,
694 .priv_data_size = sizeof(PGSSubContext),
695 .init = init_decoder,
696 .close = close_decoder,
698 .priv_class = &pgsdec_class,