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.

544 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. int64_t pts;
  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. ctx->pictures[picture_id].w = width;
  185. ctx->pictures[picture_id].h = height;
  186. av_fast_malloc(&ctx->pictures[picture_id].rle, &ctx->pictures[picture_id].rle_buffer_size, rle_bitmap_len);
  187. if (!ctx->pictures[picture_id].rle)
  188. return -1;
  189. memcpy(ctx->pictures[picture_id].rle, buf, buf_size);
  190. ctx->pictures[picture_id].rle_data_len = buf_size;
  191. ctx->pictures[picture_id].rle_remaining_len = rle_bitmap_len - buf_size;
  192. return 0;
  193. }
  194. /**
  195. * Parse the palette segment packet.
  196. *
  197. * The palette segment contains details of the palette,
  198. * a maximum of 256 colors can be defined.
  199. *
  200. * @param avctx contains the current codec context
  201. * @param buf pointer to the packet to process
  202. * @param buf_size size of packet to process
  203. */
  204. static void parse_palette_segment(AVCodecContext *avctx,
  205. const uint8_t *buf, int buf_size)
  206. {
  207. PGSSubContext *ctx = avctx->priv_data;
  208. const uint8_t *buf_end = buf + buf_size;
  209. const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;
  210. int color_id;
  211. int y, cb, cr, alpha;
  212. int r, g, b, r_add, g_add, b_add;
  213. /* Skip two null bytes */
  214. buf += 2;
  215. while (buf < buf_end) {
  216. color_id = bytestream_get_byte(&buf);
  217. y = bytestream_get_byte(&buf);
  218. cr = bytestream_get_byte(&buf);
  219. cb = bytestream_get_byte(&buf);
  220. alpha = bytestream_get_byte(&buf);
  221. YUV_TO_RGB1(cb, cr);
  222. YUV_TO_RGB2(r, g, b, y);
  223. av_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
  224. /* Store color in palette */
  225. ctx->clut[color_id] = RGBA(r,g,b,alpha);
  226. }
  227. }
  228. /**
  229. * Parse the presentation segment packet.
  230. *
  231. * The presentation segment contains details on the video
  232. * width, video height, x & y subtitle position.
  233. *
  234. * @param avctx contains the current codec context
  235. * @param buf pointer to the packet to process
  236. * @param buf_size size of packet to process
  237. * @todo TODO: Implement cropping
  238. */
  239. static void parse_presentation_segment(AVCodecContext *avctx,
  240. const uint8_t *buf, int buf_size)
  241. {
  242. PGSSubContext *ctx = avctx->priv_data;
  243. int w = bytestream_get_be16(&buf);
  244. int h = bytestream_get_be16(&buf);
  245. uint16_t object_index;
  246. av_dlog(avctx, "Video Dimensions %dx%d\n",
  247. w, h);
  248. if (av_image_check_size(w, h, 0, avctx) >= 0)
  249. avcodec_set_dimensions(avctx, w, h);
  250. /* Skip 1 bytes of unknown, frame rate? */
  251. buf++;
  252. ctx->presentation.id_number = bytestream_get_be16(&buf);
  253. /*
  254. * Skip 3 bytes of unknown:
  255. * state
  256. * palette_update_flag (0x80),
  257. * palette_id_to_use,
  258. */
  259. buf += 3;
  260. ctx->presentation.object_count = bytestream_get_byte(&buf);
  261. if (!ctx->presentation.object_count)
  262. return;
  263. /* Verify that enough bytes are remaining for all of the objects. */
  264. buf_size -= 11;
  265. if (buf_size < ctx->presentation.object_count * 8) {
  266. ctx->presentation.object_count = 0;
  267. return;
  268. }
  269. av_freep(&ctx->presentation.objects);
  270. ctx->presentation.objects = av_malloc(sizeof(PGSSubPictureReference) * ctx->presentation.object_count);
  271. if (!ctx->presentation.objects) {
  272. ctx->presentation.object_count = 0;
  273. return;
  274. }
  275. for (object_index = 0; object_index < ctx->presentation.object_count; ++object_index) {
  276. PGSSubPictureReference *reference = &ctx->presentation.objects[object_index];
  277. reference->picture_id = bytestream_get_be16(&buf);
  278. /* Skip window_id_ref */
  279. buf++;
  280. /* composition_flag (0x80 - object cropped, 0x40 - object forced) */
  281. reference->composition = bytestream_get_byte(&buf);
  282. reference->x = bytestream_get_be16(&buf);
  283. reference->y = bytestream_get_be16(&buf);
  284. /* TODO If cropping, cropping_x, cropping_y, cropping_width, cropping_height (all 2 bytes).*/
  285. av_dlog(avctx, "Subtitle Placement ID=%d, x=%d, y=%d\n", reference->picture_id, reference->x, reference->y);
  286. if (reference->x > avctx->width || reference->y > avctx->height) {
  287. av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
  288. reference->x, reference->y, avctx->width, avctx->height);
  289. reference->x = 0;
  290. reference->y = 0;
  291. }
  292. }
  293. }
  294. /**
  295. * Parse the display segment packet.
  296. *
  297. * The display segment controls the updating of the display.
  298. *
  299. * @param avctx contains the current codec context
  300. * @param data pointer to the data pertaining the subtitle to display
  301. * @param buf pointer to the packet to process
  302. * @param buf_size size of packet to process
  303. * @todo TODO: Fix start time, relies on correct PTS, currently too late
  304. *
  305. * @todo TODO: Fix end time, normally cleared by a second display
  306. * @todo segment, which is currently ignored as it clears
  307. * @todo the subtitle too early.
  308. */
  309. static int display_end_segment(AVCodecContext *avctx, void *data,
  310. const uint8_t *buf, int buf_size)
  311. {
  312. AVSubtitle *sub = data;
  313. PGSSubContext *ctx = avctx->priv_data;
  314. int64_t pts;
  315. uint16_t rect;
  316. /*
  317. * The end display time is a timeout value and is only reached
  318. * if the next subtitle is later than timeout or subtitle has
  319. * not been cleared by a subsequent empty display command.
  320. */
  321. pts = ctx->pts != AV_NOPTS_VALUE ? ctx->pts : sub->pts;
  322. memset(sub, 0, sizeof(*sub));
  323. sub->pts = pts;
  324. ctx->pts = AV_NOPTS_VALUE;
  325. // Blank if last object_count was 0.
  326. if (!ctx->presentation.object_count)
  327. return 1;
  328. sub->start_display_time = 0;
  329. sub->end_display_time = 20000;
  330. sub->format = 0;
  331. sub->num_rects = ctx->presentation.object_count;
  332. sub->rects = av_mallocz(sizeof(*sub->rects) * sub->num_rects);
  333. for (rect = 0; rect < sub->num_rects; ++rect) {
  334. uint16_t picture_id = ctx->presentation.objects[rect].picture_id;
  335. sub->rects[rect] = av_mallocz(sizeof(*sub->rects[rect]));
  336. sub->rects[rect]->x = ctx->presentation.objects[rect].x;
  337. sub->rects[rect]->y = ctx->presentation.objects[rect].y;
  338. sub->rects[rect]->w = ctx->pictures[picture_id].w;
  339. sub->rects[rect]->h = ctx->pictures[picture_id].h;
  340. sub->rects[rect]->type = SUBTITLE_BITMAP;
  341. /* Process bitmap */
  342. sub->rects[rect]->pict.linesize[0] = ctx->pictures[picture_id].w;
  343. if (ctx->pictures[picture_id].rle) {
  344. if (ctx->pictures[picture_id].rle_remaining_len)
  345. av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
  346. ctx->pictures[picture_id].rle_data_len, ctx->pictures[picture_id].rle_remaining_len);
  347. if (decode_rle(avctx, sub, rect, ctx->pictures[picture_id].rle, ctx->pictures[picture_id].rle_data_len) < 0)
  348. return 0;
  349. }
  350. /* Allocate memory for colors */
  351. sub->rects[rect]->nb_colors = 256;
  352. sub->rects[rect]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
  353. /* Copy the forced flag */
  354. sub->rects[rect]->forced = (ctx->presentation.objects[rect].composition & 0x40) != 0;
  355. if (!ctx->forced_subs_only || ctx->presentation.objects[rect].composition & 0x40)
  356. memcpy(sub->rects[rect]->pict.data[1], ctx->clut, sub->rects[rect]->nb_colors * sizeof(uint32_t));
  357. }
  358. return 1;
  359. }
  360. static int decode(AVCodecContext *avctx, void *data, int *data_size,
  361. AVPacket *avpkt)
  362. {
  363. PGSSubContext *ctx = avctx->priv_data;
  364. const uint8_t *buf = avpkt->data;
  365. int buf_size = avpkt->size;
  366. AVSubtitle *sub = data;
  367. const uint8_t *buf_end;
  368. uint8_t segment_type;
  369. int segment_length;
  370. int i;
  371. av_dlog(avctx, "PGS sub packet:\n");
  372. for (i = 0; i < buf_size; i++) {
  373. av_dlog(avctx, "%02x ", buf[i]);
  374. if (i % 16 == 15)
  375. av_dlog(avctx, "\n");
  376. }
  377. if (i & 15)
  378. av_dlog(avctx, "\n");
  379. *data_size = 0;
  380. /* Ensure that we have received at a least a segment code and segment length */
  381. if (buf_size < 3)
  382. return -1;
  383. buf_end = buf + buf_size;
  384. /* Step through buffer to identify segments */
  385. while (buf < buf_end) {
  386. segment_type = bytestream_get_byte(&buf);
  387. segment_length = bytestream_get_be16(&buf);
  388. av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
  389. if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
  390. break;
  391. switch (segment_type) {
  392. case PALETTE_SEGMENT:
  393. parse_palette_segment(avctx, buf, segment_length);
  394. break;
  395. case PICTURE_SEGMENT:
  396. parse_picture_segment(avctx, buf, segment_length);
  397. break;
  398. case PRESENTATION_SEGMENT:
  399. parse_presentation_segment(avctx, buf, segment_length);
  400. ctx->pts = sub->pts;
  401. break;
  402. case WINDOW_SEGMENT:
  403. /*
  404. * Window Segment Structure (No new information provided):
  405. * 2 bytes: Unknown,
  406. * 2 bytes: X position of subtitle,
  407. * 2 bytes: Y position of subtitle,
  408. * 2 bytes: Width of subtitle,
  409. * 2 bytes: Height of subtitle.
  410. */
  411. break;
  412. case DISPLAY_SEGMENT:
  413. *data_size = display_end_segment(avctx, data, buf, segment_length);
  414. break;
  415. default:
  416. av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",
  417. segment_type, segment_length);
  418. break;
  419. }
  420. buf += segment_length;
  421. }
  422. return buf_size;
  423. }
  424. #define OFFSET(x) offsetof(PGSSubContext, x)
  425. #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
  426. static const AVOption options[] = {
  427. {"forced_subs_only", "Only show forced subtitles", OFFSET(forced_subs_only), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, SD},
  428. { NULL },
  429. };
  430. static const AVClass pgsdec_class = {
  431. .class_name = "PGS subtitle decoder",
  432. .item_name = av_default_item_name,
  433. .option = options,
  434. .version = LIBAVUTIL_VERSION_INT,
  435. };
  436. AVCodec ff_pgssub_decoder = {
  437. .name = "pgssub",
  438. .type = AVMEDIA_TYPE_SUBTITLE,
  439. .id = AV_CODEC_ID_HDMV_PGS_SUBTITLE,
  440. .priv_data_size = sizeof(PGSSubContext),
  441. .init = init_decoder,
  442. .close = close_decoder,
  443. .decode = decode,
  444. .long_name = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"),
  445. .priv_class = &pgsdec_class,
  446. };