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.

558 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 "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 void 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. }
  233. /**
  234. * Parse the presentation segment packet.
  235. *
  236. * The presentation segment contains details on the video
  237. * width, video height, x & y subtitle position.
  238. *
  239. * @param avctx contains the current codec context
  240. * @param buf pointer to the packet to process
  241. * @param buf_size size of packet to process
  242. * @todo TODO: Implement cropping
  243. */
  244. static int parse_presentation_segment(AVCodecContext *avctx,
  245. const uint8_t *buf, int buf_size,
  246. int64_t pts)
  247. {
  248. PGSSubContext *ctx = avctx->priv_data;
  249. int ret;
  250. int w = bytestream_get_be16(&buf);
  251. int h = bytestream_get_be16(&buf);
  252. uint16_t object_index;
  253. ctx->presentation.pts = pts;
  254. av_dlog(avctx, "Video Dimensions %dx%d\n",
  255. w, h);
  256. ret = ff_set_dimensions(avctx, w, h);
  257. if (ret < 0)
  258. return ret;
  259. /* Skip 1 bytes of unknown, frame rate? */
  260. buf++;
  261. ctx->presentation.id_number = bytestream_get_be16(&buf);
  262. /*
  263. * Skip 3 bytes of unknown:
  264. * state
  265. * palette_update_flag (0x80),
  266. * palette_id_to_use,
  267. */
  268. buf += 3;
  269. ctx->presentation.object_count = bytestream_get_byte(&buf);
  270. if (!ctx->presentation.object_count)
  271. return 0;
  272. /* Verify that enough bytes are remaining for all of the objects. */
  273. buf_size -= 11;
  274. if (buf_size < ctx->presentation.object_count * 8) {
  275. ctx->presentation.object_count = 0;
  276. return AVERROR_INVALIDDATA;
  277. }
  278. av_freep(&ctx->presentation.objects);
  279. ctx->presentation.objects = av_malloc_array(ctx->presentation.object_count, sizeof(PGSSubPictureReference));
  280. if (!ctx->presentation.objects) {
  281. ctx->presentation.object_count = 0;
  282. return AVERROR(ENOMEM);
  283. }
  284. for (object_index = 0; object_index < ctx->presentation.object_count; ++object_index) {
  285. PGSSubPictureReference *reference = &ctx->presentation.objects[object_index];
  286. reference->picture_id = bytestream_get_be16(&buf);
  287. /* Skip window_id_ref */
  288. buf++;
  289. /* composition_flag (0x80 - object cropped, 0x40 - object forced) */
  290. reference->composition = bytestream_get_byte(&buf);
  291. reference->x = bytestream_get_be16(&buf);
  292. reference->y = bytestream_get_be16(&buf);
  293. /* TODO If cropping, cropping_x, cropping_y, cropping_width, cropping_height (all 2 bytes).*/
  294. av_dlog(avctx, "Subtitle Placement ID=%d, x=%d, y=%d\n", reference->picture_id, reference->x, reference->y);
  295. if (reference->x > avctx->width || reference->y > avctx->height) {
  296. av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
  297. reference->x, reference->y, avctx->width, avctx->height);
  298. reference->x = 0;
  299. reference->y = 0;
  300. }
  301. }
  302. return 0;
  303. }
  304. /**
  305. * Parse the display segment packet.
  306. *
  307. * The display segment controls the updating of the display.
  308. *
  309. * @param avctx contains the current codec context
  310. * @param data pointer to the data pertaining the subtitle to display
  311. * @param buf pointer to the packet to process
  312. * @param buf_size size of packet to process
  313. * @todo TODO: Fix start time, relies on correct PTS, currently too late
  314. *
  315. * @todo TODO: Fix end time, normally cleared by a second display
  316. * @todo segment, which is currently ignored as it clears
  317. * @todo the subtitle too early.
  318. */
  319. static int display_end_segment(AVCodecContext *avctx, void *data,
  320. const uint8_t *buf, int buf_size)
  321. {
  322. AVSubtitle *sub = data;
  323. PGSSubContext *ctx = avctx->priv_data;
  324. int64_t pts;
  325. uint16_t rect;
  326. /*
  327. * The end display time is a timeout value and is only reached
  328. * if the next subtitle is later than timeout or subtitle has
  329. * not been cleared by a subsequent empty display command.
  330. */
  331. pts = ctx->presentation.pts != AV_NOPTS_VALUE ? ctx->presentation.pts : sub->pts;
  332. memset(sub, 0, sizeof(*sub));
  333. sub->pts = pts;
  334. ctx->presentation.pts = AV_NOPTS_VALUE;
  335. // Blank if last object_count was 0.
  336. if (!ctx->presentation.object_count)
  337. return 1;
  338. sub->start_display_time = 0;
  339. sub->end_display_time = 20000;
  340. sub->format = 0;
  341. sub->num_rects = ctx->presentation.object_count;
  342. sub->rects = av_mallocz_array(sub->num_rects, sizeof(*sub->rects));
  343. for (rect = 0; rect < sub->num_rects; ++rect) {
  344. uint16_t picture_id = ctx->presentation.objects[rect].picture_id;
  345. sub->rects[rect] = av_mallocz(sizeof(*sub->rects[rect]));
  346. sub->rects[rect]->x = ctx->presentation.objects[rect].x;
  347. sub->rects[rect]->y = ctx->presentation.objects[rect].y;
  348. sub->rects[rect]->w = ctx->pictures[picture_id].w;
  349. sub->rects[rect]->h = ctx->pictures[picture_id].h;
  350. sub->rects[rect]->type = SUBTITLE_BITMAP;
  351. /* Process bitmap */
  352. sub->rects[rect]->pict.linesize[0] = ctx->pictures[picture_id].w;
  353. if (ctx->pictures[picture_id].rle) {
  354. if (ctx->pictures[picture_id].rle_remaining_len)
  355. av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
  356. ctx->pictures[picture_id].rle_data_len, ctx->pictures[picture_id].rle_remaining_len);
  357. if (decode_rle(avctx, sub, rect, ctx->pictures[picture_id].rle, ctx->pictures[picture_id].rle_data_len) < 0)
  358. return 0;
  359. }
  360. /* Allocate memory for colors */
  361. sub->rects[rect]->nb_colors = 256;
  362. sub->rects[rect]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
  363. /* Copy the forced flag */
  364. sub->rects[rect]->flags = (ctx->presentation.objects[rect].composition & 0x40) != 0 ? AV_SUBTITLE_FLAG_FORCED : 0;
  365. if (!ctx->forced_subs_only || ctx->presentation.objects[rect].composition & 0x40)
  366. memcpy(sub->rects[rect]->pict.data[1], ctx->clut, sub->rects[rect]->nb_colors * sizeof(uint32_t));
  367. }
  368. return 1;
  369. }
  370. static int decode(AVCodecContext *avctx, void *data, int *data_size,
  371. AVPacket *avpkt)
  372. {
  373. const uint8_t *buf = avpkt->data;
  374. int buf_size = avpkt->size;
  375. AVSubtitle *sub = data;
  376. const uint8_t *buf_end;
  377. uint8_t segment_type;
  378. int segment_length;
  379. int i, ret;
  380. av_dlog(avctx, "PGS sub packet:\n");
  381. for (i = 0; i < buf_size; i++) {
  382. av_dlog(avctx, "%02x ", buf[i]);
  383. if (i % 16 == 15)
  384. av_dlog(avctx, "\n");
  385. }
  386. if (i & 15)
  387. av_dlog(avctx, "\n");
  388. *data_size = 0;
  389. /* Ensure that we have received at a least a segment code and segment length */
  390. if (buf_size < 3)
  391. return -1;
  392. buf_end = buf + buf_size;
  393. /* Step through buffer to identify segments */
  394. while (buf < buf_end) {
  395. segment_type = bytestream_get_byte(&buf);
  396. segment_length = bytestream_get_be16(&buf);
  397. av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
  398. if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
  399. break;
  400. switch (segment_type) {
  401. case PALETTE_SEGMENT:
  402. parse_palette_segment(avctx, buf, segment_length);
  403. break;
  404. case OBJECT_SEGMENT:
  405. parse_picture_segment(avctx, buf, segment_length);
  406. break;
  407. case PRESENTATION_SEGMENT:
  408. ret = parse_presentation_segment(avctx, buf, segment_length, sub->pts);
  409. if (ret < 0)
  410. return ret;
  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. *data_size = display_end_segment(avctx, data, buf, segment_length);
  424. break;
  425. default:
  426. av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",
  427. segment_type, segment_length);
  428. break;
  429. }
  430. buf += segment_length;
  431. }
  432. return buf_size;
  433. }
  434. #define OFFSET(x) offsetof(PGSSubContext, x)
  435. #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
  436. static const AVOption options[] = {
  437. {"forced_subs_only", "Only show forced subtitles", OFFSET(forced_subs_only), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, SD},
  438. { NULL },
  439. };
  440. static const AVClass pgsdec_class = {
  441. .class_name = "PGS subtitle decoder",
  442. .item_name = av_default_item_name,
  443. .option = options,
  444. .version = LIBAVUTIL_VERSION_INT,
  445. };
  446. AVCodec ff_pgssub_decoder = {
  447. .name = "pgssub",
  448. .long_name = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"),
  449. .type = AVMEDIA_TYPE_SUBTITLE,
  450. .id = AV_CODEC_ID_HDMV_PGS_SUBTITLE,
  451. .priv_data_size = sizeof(PGSSubContext),
  452. .init = init_decoder,
  453. .close = close_decoder,
  454. .decode = decode,
  455. .priv_class = &pgsdec_class,
  456. };