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.

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