You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

571 lines
18KB

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