FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
pgssubdec.c
Go to the documentation of this file.
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 #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
40 
47 };
48 
49 typedef struct PGSSubObjectRef {
50  int id;
51  int window_id;
53  int x;
54  int y;
55  int crop_x;
56  int crop_y;
57  int crop_w;
58  int crop_h;
60 
61 typedef struct PGSSubPresentation {
62  int id_number;
66  int64_t pts;
68 
69 typedef struct PGSSubObject {
70  int id;
71  int w;
72  int h;
75  unsigned int rle_remaining_len;
76 } PGSSubObject;
77 
78 typedef struct PGSSubObjects {
79  int count;
82 
83 typedef struct PGSSubPalette {
84  int id;
85  uint32_t clut[256];
87 
88 typedef struct PGSSubPalettes {
89  int count;
92 
93 typedef struct PGSSubContext {
94  AVClass *class;
100 
101 static void flush_cache(AVCodecContext *avctx)
102 {
103  PGSSubContext *ctx = avctx->priv_data;
104  int i;
105 
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;
110  }
111  ctx->objects.count = 0;
112  ctx->palettes.count = 0;
113 }
114 
115 static PGSSubObject * find_object(int id, PGSSubObjects *objects)
116 {
117  int i;
118 
119  for (i = 0; i < objects->count; i++) {
120  if (objects->object[i].id == id)
121  return &objects->object[i];
122  }
123  return NULL;
124 }
125 
126 static PGSSubPalette * find_palette(int id, PGSSubPalettes *palettes)
127 {
128  int i;
129 
130  for (i = 0; i < palettes->count; i++) {
131  if (palettes->palette[i].id == id)
132  return &palettes->palette[i];
133  }
134  return NULL;
135 }
136 
138 {
139  avctx->pix_fmt = AV_PIX_FMT_PAL8;
140 
141  return 0;
142 }
143 
145 {
146  flush_cache(avctx);
147 
148  return 0;
149 }
150 
151 /**
152  * Decode the RLE data.
153  *
154  * The subtitle is stored as a Run Length Encoded image.
155  *
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
160  */
162  const uint8_t *buf, unsigned int buf_size)
163 {
164  const uint8_t *rle_bitmap_end;
165  int pixel_count, line_count;
166 
167  rle_bitmap_end = buf + buf_size;
168 
169  rect->pict.data[0] = av_malloc(rect->w * rect->h);
170 
171  if (!rect->pict.data[0])
172  return AVERROR(ENOMEM);
173 
174  pixel_count = 0;
175  line_count = 0;
176 
177  while (buf < rle_bitmap_end && line_count < rect->h) {
179  int run;
180 
181  color = bytestream_get_byte(&buf);
182  run = 1;
183 
184  if (color == 0x00) {
185  flags = bytestream_get_byte(&buf);
186  run = flags & 0x3f;
187  if (flags & 0x40)
188  run = (run << 8) + bytestream_get_byte(&buf);
189  color = flags & 0x80 ? bytestream_get_byte(&buf) : 0;
190  }
191 
192  if (run > 0 && pixel_count + run <= rect->w * rect->h) {
193  memset(rect->pict.data[0] + pixel_count, color, run);
194  pixel_count += run;
195  } else if (!run) {
196  /*
197  * New Line. Check if correct pixels decoded, if not display warning
198  * and adjust bitmap pointer to correct new line position.
199  */
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;
205  }
206  }
207  line_count++;
208  }
209  }
210 
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;
214  }
215 
216  av_dlog(avctx, "Pixel Count = %d, Area = %d\n", pixel_count, rect->w * rect->h);
217 
218  return 0;
219 }
220 
221 /**
222  * Parse the picture segment packet.
223  *
224  * The picture segment contains details on the sequence id,
225  * width, height and Run Length Encoded (RLE) bitmap data.
226  *
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
230  */
232  const uint8_t *buf, int buf_size)
233 {
234  PGSSubContext *ctx = avctx->priv_data;
235  PGSSubObject *object;
236 
237  uint8_t sequence_desc;
238  unsigned int rle_bitmap_len, width, height;
239  int id;
240 
241  if (buf_size <= 4)
242  return AVERROR_INVALIDDATA;
243  buf_size -= 4;
244 
245  id = bytestream_get_be16(&buf);
246  object = find_object(id, &ctx->objects);
247  if (!object) {
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;
251  }
252  object = &ctx->objects.object[ctx->objects.count++];
253  object->id = id;
254  }
255 
256  /* skip object version number */
257  buf += 1;
258 
259  /* Read the Sequence Description to determine if start of RLE data or appended to previous RLE */
260  sequence_desc = bytestream_get_byte(&buf);
261 
262  if (!(sequence_desc & 0x80)) {
263  /* Additional RLE data */
264  if (buf_size > object->rle_remaining_len)
265  return AVERROR_INVALIDDATA;
266 
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;
270 
271  return 0;
272  }
273 
274  if (buf_size <= 7)
275  return AVERROR_INVALIDDATA;
276  buf_size -= 7;
277 
278  /* Decode rle bitmap length, stored size includes width/height data */
279  rle_bitmap_len = bytestream_get_be24(&buf) - 2*2;
280 
281  /* Get bitmap dimensions from data */
282  width = bytestream_get_be16(&buf);
283  height = bytestream_get_be16(&buf);
284 
285  /* Make sure the bitmap is not too large */
286  if (avctx->width < width || avctx->height < height) {
287  av_log(avctx, AV_LOG_ERROR, "Bitmap dimensions larger than video.\n");
288  return AVERROR_INVALIDDATA;
289  }
290 
291  if (buf_size > rle_bitmap_len) {
292  av_log(avctx, AV_LOG_ERROR, "too much RLE data\n");
293  return AVERROR_INVALIDDATA;
294  }
295 
296  object->w = width;
297  object->h = height;
298 
299  av_fast_padded_malloc(&object->rle, &object->rle_buffer_size, rle_bitmap_len);
300 
301  if (!object->rle)
302  return AVERROR(ENOMEM);
303 
304  memcpy(object->rle, buf, buf_size);
305  object->rle_data_len = buf_size;
306  object->rle_remaining_len = rle_bitmap_len - buf_size;
307 
308  return 0;
309 }
310 
311 /**
312  * Parse the palette segment packet.
313  *
314  * The palette segment contains details of the palette,
315  * a maximum of 256 colors can be defined.
316  *
317  * @param avctx contains the current codec context
318  * @param buf pointer to the packet to process
319  * @param buf_size size of packet to process
320  */
322  const uint8_t *buf, int buf_size)
323 {
324  PGSSubContext *ctx = avctx->priv_data;
326 
327  const uint8_t *buf_end = buf + buf_size;
328  const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;
329  int color_id;
330  int y, cb, cr, alpha;
331  int r, g, b, r_add, g_add, b_add;
332  int id;
333 
334  id = bytestream_get_byte(&buf);
335  palette = find_palette(id, &ctx->palettes);
336  if (!palette) {
337  if (ctx->palettes.count >= MAX_EPOCH_PALETTES) {
338  av_log(avctx, AV_LOG_ERROR, "Too many palettes in epoch\n");
339  return AVERROR_INVALIDDATA;
340  }
341  palette = &ctx->palettes.palette[ctx->palettes.count++];
342  palette->id = id;
343  }
344 
345  /* Skip palette version */
346  buf += 1;
347 
348  while (buf < buf_end) {
349  color_id = bytestream_get_byte(&buf);
350  y = bytestream_get_byte(&buf);
351  cr = bytestream_get_byte(&buf);
352  cb = bytestream_get_byte(&buf);
353  alpha = bytestream_get_byte(&buf);
354 
355  YUV_TO_RGB1(cb, cr);
356  YUV_TO_RGB2(r, g, b, y);
357 
358  av_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
359 
360  /* Store color in palette */
361  palette->clut[color_id] = RGBA(r,g,b,alpha);
362  }
363  return 0;
364 }
365 
366 /**
367  * Parse the presentation segment packet.
368  *
369  * The presentation segment contains details on the video
370  * width, video height, x & y subtitle position.
371  *
372  * @param avctx contains the current codec context
373  * @param buf pointer to the packet to process
374  * @param buf_size size of packet to process
375  * @todo TODO: Implement cropping
376  */
378  const uint8_t *buf, int buf_size,
379  int64_t pts)
380 {
381  PGSSubContext *ctx = avctx->priv_data;
382  int i, state, ret;
383  const uint8_t *buf_end = buf + buf_size;
384 
385  // Video descriptor
386  int w = bytestream_get_be16(&buf);
387  int h = bytestream_get_be16(&buf);
388 
389  ctx->presentation.pts = pts;
390 
391  av_dlog(avctx, "Video Dimensions %dx%d\n",
392  w, h);
393  ret = ff_set_dimensions(avctx, w, h);
394  if (ret < 0)
395  return ret;
396 
397  /* Skip 1 bytes of unknown, frame rate */
398  buf++;
399 
400  // Composition descriptor
401  ctx->presentation.id_number = bytestream_get_be16(&buf);
402  /*
403  * state is a 2 bit field that defines pgs epoch boundaries
404  * 00 - Normal, previously defined objects and palettes are still valid
405  * 01 - Acquisition point, previous objects and palettes can be released
406  * 10 - Epoch start, previous objects and palettes can be released
407  * 11 - Epoch continue, previous objects and palettes can be released
408  *
409  * reserved 6 bits discarded
410  */
411  state = bytestream_get_byte(&buf) >> 6;
412  if (state != 0) {
413  flush_cache(avctx);
414  }
415 
416  /*
417  * skip palette_update_flag (0x80),
418  */
419  buf += 1;
420  ctx->presentation.palette_id = bytestream_get_byte(&buf);
421  ctx->presentation.object_count = bytestream_get_byte(&buf);
423  av_log(avctx, AV_LOG_ERROR,
424  "Invalid number of presentation objects %d\n",
426  ctx->presentation.object_count = 2;
427  if (avctx->err_recognition & AV_EF_EXPLODE) {
428  return AVERROR_INVALIDDATA;
429  }
430  }
431 
432 
433  for (i = 0; i < ctx->presentation.object_count; i++)
434  {
435 
436  if (buf_end - buf < 8) {
437  av_log(avctx, AV_LOG_ERROR, "Insufficent space for object\n");
438  ctx->presentation.object_count = i;
439  return AVERROR_INVALIDDATA;
440  }
441 
442  ctx->presentation.objects[i].id = bytestream_get_be16(&buf);
443  ctx->presentation.objects[i].window_id = bytestream_get_byte(&buf);
444  ctx->presentation.objects[i].composition_flag = bytestream_get_byte(&buf);
445 
446  ctx->presentation.objects[i].x = bytestream_get_be16(&buf);
447  ctx->presentation.objects[i].y = bytestream_get_be16(&buf);
448 
449  // If cropping
450  if (ctx->presentation.objects[i].composition_flag & 0x80) {
451  ctx->presentation.objects[i].crop_x = bytestream_get_be16(&buf);
452  ctx->presentation.objects[i].crop_y = bytestream_get_be16(&buf);
453  ctx->presentation.objects[i].crop_w = bytestream_get_be16(&buf);
454  ctx->presentation.objects[i].crop_h = bytestream_get_be16(&buf);
455  }
456 
457  av_dlog(avctx, "Subtitle Placement x=%d, y=%d\n",
458  ctx->presentation.objects[i].x, ctx->presentation.objects[i].y);
459 
460  if (ctx->presentation.objects[i].x > avctx->width ||
461  ctx->presentation.objects[i].y > avctx->height) {
462  av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
463  ctx->presentation.objects[i].x,
464  ctx->presentation.objects[i].y,
465  avctx->width, avctx->height);
466  ctx->presentation.objects[i].x = 0;
467  ctx->presentation.objects[i].y = 0;
468  if (avctx->err_recognition & AV_EF_EXPLODE) {
469  return AVERROR_INVALIDDATA;
470  }
471  }
472  }
473 
474  return 0;
475 }
476 
477 /**
478  * Parse the display segment packet.
479  *
480  * The display segment controls the updating of the display.
481  *
482  * @param avctx contains the current codec context
483  * @param data pointer to the data pertaining the subtitle to display
484  * @param buf pointer to the packet to process
485  * @param buf_size size of packet to process
486  */
487 static int display_end_segment(AVCodecContext *avctx, void *data,
488  const uint8_t *buf, int buf_size)
489 {
490  AVSubtitle *sub = data;
491  PGSSubContext *ctx = avctx->priv_data;
492  int64_t pts;
494  int i, ret;
495 
496  pts = ctx->presentation.pts != AV_NOPTS_VALUE ? ctx->presentation.pts : sub->pts;
497  memset(sub, 0, sizeof(*sub));
498  sub->pts = pts;
500  sub->start_display_time = 0;
501  // There is no explicit end time for PGS subtitles. The end time
502  // is defined by the start of the next sub which may contain no
503  // objects (i.e. clears the previous sub)
504  sub->end_display_time = UINT32_MAX;
505  sub->format = 0;
506 
507  // Blank if last object_count was 0.
508  if (!ctx->presentation.object_count)
509  return 1;
510  sub->rects = av_mallocz(sizeof(*sub->rects) * ctx->presentation.object_count);
511  if (!sub->rects) {
512  return AVERROR(ENOMEM);
513  }
514  palette = find_palette(ctx->presentation.palette_id, &ctx->palettes);
515  if (!palette) {
516  // Missing palette. Should only happen with damaged streams.
517  av_log(avctx, AV_LOG_ERROR, "Invalid palette id %d\n",
518  ctx->presentation.palette_id);
519  avsubtitle_free(sub);
520  return AVERROR_INVALIDDATA;
521  }
522  for (i = 0; i < ctx->presentation.object_count; i++) {
523  PGSSubObject *object;
524 
525  sub->rects[i] = av_mallocz(sizeof(*sub->rects[0]));
526  if (!sub->rects[i]) {
527  avsubtitle_free(sub);
528  return AVERROR(ENOMEM);
529  }
530  sub->num_rects++;
531  sub->rects[i]->type = SUBTITLE_BITMAP;
532 
533  /* Process bitmap */
534  object = find_object(ctx->presentation.objects[i].id, &ctx->objects);
535  if (!object) {
536  // Missing object. Should only happen with damaged streams.
537  av_log(avctx, AV_LOG_ERROR, "Invalid object id %d\n",
538  ctx->presentation.objects[i].id);
539  if (avctx->err_recognition & AV_EF_EXPLODE) {
540  avsubtitle_free(sub);
541  return AVERROR_INVALIDDATA;
542  }
543  // Leaves rect empty with 0 width and height.
544  continue;
545  }
546  if (ctx->presentation.objects[i].composition_flag & 0x40)
547  sub->rects[i]->flags |= AV_SUBTITLE_FLAG_FORCED;
548 
549  sub->rects[i]->x = ctx->presentation.objects[i].x;
550  sub->rects[i]->y = ctx->presentation.objects[i].y;
551  sub->rects[i]->w = object->w;
552  sub->rects[i]->h = object->h;
553 
554  sub->rects[i]->pict.linesize[0] = object->w;
555 
556  if (object->rle) {
557  if (object->rle_remaining_len) {
558  av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
559  object->rle_data_len, object->rle_remaining_len);
560  if (avctx->err_recognition & AV_EF_EXPLODE) {
561  avsubtitle_free(sub);
562  return AVERROR_INVALIDDATA;
563  }
564  }
565  ret = decode_rle(avctx, sub->rects[i], object->rle, object->rle_data_len);
566  if (ret < 0) {
567  if ((avctx->err_recognition & AV_EF_EXPLODE) ||
568  ret == AVERROR(ENOMEM)) {
569  avsubtitle_free(sub);
570  return ret;
571  }
572  sub->rects[i]->w = 0;
573  sub->rects[i]->h = 0;
574  continue;
575  }
576  }
577  /* Allocate memory for colors */
578  sub->rects[i]->nb_colors = 256;
579  sub->rects[i]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
580  if (!sub->rects[i]->pict.data[1]) {
581  avsubtitle_free(sub);
582  return AVERROR(ENOMEM);
583  }
584 
585  if (!ctx->forced_subs_only || ctx->presentation.objects[i].composition_flag & 0x40)
586  memcpy(sub->rects[i]->pict.data[1], palette->clut, sub->rects[i]->nb_colors * sizeof(uint32_t));
587 
588  }
589  return 1;
590 }
591 
592 static int decode(AVCodecContext *avctx, void *data, int *data_size,
593  AVPacket *avpkt)
594 {
595  const uint8_t *buf = avpkt->data;
596  int buf_size = avpkt->size;
597 
598  const uint8_t *buf_end;
599  uint8_t segment_type;
600  int segment_length;
601  int i, ret;
602 
603  av_dlog(avctx, "PGS sub packet:\n");
604 
605  for (i = 0; i < buf_size; i++) {
606  av_dlog(avctx, "%02x ", buf[i]);
607  if (i % 16 == 15)
608  av_dlog(avctx, "\n");
609  }
610 
611  if (i & 15)
612  av_dlog(avctx, "\n");
613 
614  *data_size = 0;
615 
616  /* Ensure that we have received at a least a segment code and segment length */
617  if (buf_size < 3)
618  return -1;
619 
620  buf_end = buf + buf_size;
621 
622  /* Step through buffer to identify segments */
623  while (buf < buf_end) {
624  segment_type = bytestream_get_byte(&buf);
625  segment_length = bytestream_get_be16(&buf);
626 
627  av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
628 
629  if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
630  break;
631 
632  ret = 0;
633  switch (segment_type) {
634  case PALETTE_SEGMENT:
635  ret = parse_palette_segment(avctx, buf, segment_length);
636  break;
637  case OBJECT_SEGMENT:
638  ret = parse_object_segment(avctx, buf, segment_length);
639  break;
641  ret = parse_presentation_segment(avctx, buf, segment_length, ((AVSubtitle*)(data))->pts);
642  break;
643  case WINDOW_SEGMENT:
644  /*
645  * Window Segment Structure (No new information provided):
646  * 2 bytes: Unknown,
647  * 2 bytes: X position of subtitle,
648  * 2 bytes: Y position of subtitle,
649  * 2 bytes: Width of subtitle,
650  * 2 bytes: Height of subtitle.
651  */
652  break;
653  case DISPLAY_SEGMENT:
654  ret = display_end_segment(avctx, data, buf, segment_length);
655  if (ret >= 0)
656  *data_size = ret;
657  break;
658  default:
659  av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",
660  segment_type, segment_length);
661  ret = AVERROR_INVALIDDATA;
662  break;
663  }
664  if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
665  return ret;
666 
667  buf += segment_length;
668  }
669 
670  return buf_size;
671 }
672 
673 #define OFFSET(x) offsetof(PGSSubContext, x)
674 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
675 static const AVOption options[] = {
676  {"forced_subs_only", "Only show forced subtitles", OFFSET(forced_subs_only), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, SD},
677  { NULL },
678 };
679 
680 static const AVClass pgsdec_class = {
681  .class_name = "PGS subtitle decoder",
682  .item_name = av_default_item_name,
683  .option = options,
684  .version = LIBAVUTIL_VERSION_INT,
685 };
686 
688  .name = "pgssub",
689  .long_name = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"),
690  .type = AVMEDIA_TYPE_SUBTITLE,
692  .priv_data_size = sizeof(PGSSubContext),
693  .init = init_decoder,
694  .close = close_decoder,
695  .decode = decode,
696  .priv_class = &pgsdec_class,
697 };