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.

536 lines
17KB

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