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.

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