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.

670 lines
20KB

  1. /*
  2. * PGS subtitle decoder
  3. * Copyright (c) 2009 Stephen Backway
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; 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. #define RGBA(r,g,b,a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))
  32. #define MAX_EPOCH_PALETTES 8 // Max 8 allowed per PGS epoch
  33. #define MAX_EPOCH_OBJECTS 64 // Max 64 allowed per PGS epoch
  34. #define MAX_OBJECT_REFS 2 // Max objects per display set
  35. enum SegmentType {
  36. PALETTE_SEGMENT = 0x14,
  37. OBJECT_SEGMENT = 0x15,
  38. PRESENTATION_SEGMENT = 0x16,
  39. WINDOW_SEGMENT = 0x17,
  40. DISPLAY_SEGMENT = 0x80,
  41. };
  42. typedef struct PGSSubObjectRef {
  43. int id;
  44. int window_id;
  45. uint8_t composition_flag;
  46. int x;
  47. int y;
  48. int crop_x;
  49. int crop_y;
  50. int crop_w;
  51. int crop_h;
  52. } PGSSubObjectRef;
  53. typedef struct PGSSubPresentation {
  54. int id_number;
  55. int palette_id;
  56. int object_count;
  57. PGSSubObjectRef objects[MAX_OBJECT_REFS];
  58. int64_t pts;
  59. } PGSSubPresentation;
  60. typedef struct PGSSubObject {
  61. int id;
  62. int w;
  63. int h;
  64. uint8_t *rle;
  65. unsigned int rle_buffer_size, rle_data_len;
  66. unsigned int rle_remaining_len;
  67. } PGSSubObject;
  68. typedef struct PGSSubObjects {
  69. int count;
  70. PGSSubObject object[MAX_EPOCH_OBJECTS];
  71. } PGSSubObjects;
  72. typedef struct PGSSubPalette {
  73. int id;
  74. uint32_t clut[256];
  75. } PGSSubPalette;
  76. typedef struct PGSSubPalettes {
  77. int count;
  78. PGSSubPalette palette[MAX_EPOCH_PALETTES];
  79. } PGSSubPalettes;
  80. typedef struct PGSSubContext {
  81. PGSSubPresentation presentation;
  82. PGSSubPalettes palettes;
  83. PGSSubObjects objects;
  84. } PGSSubContext;
  85. static void flush_cache(AVCodecContext *avctx)
  86. {
  87. PGSSubContext *ctx = avctx->priv_data;
  88. int i;
  89. for (i = 0; i < ctx->objects.count; i++) {
  90. av_freep(&ctx->objects.object[i].rle);
  91. ctx->objects.object[i].rle_buffer_size = 0;
  92. ctx->objects.object[i].rle_remaining_len = 0;
  93. }
  94. ctx->objects.count = 0;
  95. ctx->palettes.count = 0;
  96. }
  97. static PGSSubObject * find_object(int id, PGSSubObjects *objects)
  98. {
  99. int i;
  100. for (i = 0; i < objects->count; i++) {
  101. if (objects->object[i].id == id)
  102. return &objects->object[i];
  103. }
  104. return NULL;
  105. }
  106. static PGSSubPalette * find_palette(int id, PGSSubPalettes *palettes)
  107. {
  108. int i;
  109. for (i = 0; i < palettes->count; i++) {
  110. if (palettes->palette[i].id == id)
  111. return &palettes->palette[i];
  112. }
  113. return NULL;
  114. }
  115. static av_cold int init_decoder(AVCodecContext *avctx)
  116. {
  117. avctx->pix_fmt = AV_PIX_FMT_PAL8;
  118. return 0;
  119. }
  120. static av_cold int close_decoder(AVCodecContext *avctx)
  121. {
  122. flush_cache(avctx);
  123. return 0;
  124. }
  125. /**
  126. * Decode the RLE data.
  127. *
  128. * The subtitle is stored as an Run Length Encoded image.
  129. *
  130. * @param avctx contains the current codec context
  131. * @param sub pointer to the processed subtitle data
  132. * @param buf pointer to the RLE data to process
  133. * @param buf_size size of the RLE data to process
  134. */
  135. static int decode_rle(AVCodecContext *avctx, AVSubtitleRect *rect,
  136. const uint8_t *buf, unsigned int buf_size)
  137. {
  138. const uint8_t *rle_bitmap_end;
  139. int pixel_count, line_count;
  140. rle_bitmap_end = buf + buf_size;
  141. rect->pict.data[0] = av_malloc(rect->w * rect->h);
  142. if (!rect->pict.data[0])
  143. return AVERROR(ENOMEM);
  144. pixel_count = 0;
  145. line_count = 0;
  146. while (buf < rle_bitmap_end && line_count < rect->h) {
  147. uint8_t flags, color;
  148. int run;
  149. color = bytestream_get_byte(&buf);
  150. run = 1;
  151. if (color == 0x00) {
  152. flags = bytestream_get_byte(&buf);
  153. run = flags & 0x3f;
  154. if (flags & 0x40)
  155. run = (run << 8) + bytestream_get_byte(&buf);
  156. color = flags & 0x80 ? bytestream_get_byte(&buf) : 0;
  157. }
  158. if (run > 0 && pixel_count + run <= rect->w * rect->h) {
  159. memset(rect->pict.data[0] + pixel_count, color, run);
  160. pixel_count += run;
  161. } else if (!run) {
  162. /*
  163. * New Line. Check if correct pixels decoded, if not display warning
  164. * and adjust bitmap pointer to correct new line position.
  165. */
  166. if (pixel_count % rect->w > 0) {
  167. av_log(avctx, AV_LOG_ERROR, "Decoded %d pixels, when line should be %d pixels\n",
  168. pixel_count % rect->w, rect->w);
  169. if (avctx->err_recognition & AV_EF_EXPLODE) {
  170. return AVERROR_INVALIDDATA;
  171. }
  172. }
  173. line_count++;
  174. }
  175. }
  176. if (pixel_count < rect->w * rect->h) {
  177. av_log(avctx, AV_LOG_ERROR, "Insufficient RLE data for subtitle\n");
  178. return AVERROR_INVALIDDATA;
  179. }
  180. ff_dlog(avctx, "Pixel Count = %d, Area = %d\n", pixel_count, rect->w * rect->h);
  181. return 0;
  182. }
  183. /**
  184. * Parse the picture segment packet.
  185. *
  186. * The picture segment contains details on the sequence id,
  187. * width, height and Run Length Encoded (RLE) bitmap data.
  188. *
  189. * @param avctx contains the current codec context
  190. * @param buf pointer to the packet to process
  191. * @param buf_size size of packet to process
  192. */
  193. static int parse_object_segment(AVCodecContext *avctx,
  194. const uint8_t *buf, int buf_size)
  195. {
  196. PGSSubContext *ctx = avctx->priv_data;
  197. PGSSubObject *object;
  198. uint8_t sequence_desc;
  199. unsigned int rle_bitmap_len, width, height;
  200. int id;
  201. if (buf_size <= 4)
  202. return AVERROR_INVALIDDATA;
  203. buf_size -= 4;
  204. id = bytestream_get_be16(&buf);
  205. object = find_object(id, &ctx->objects);
  206. if (!object) {
  207. if (ctx->objects.count >= MAX_EPOCH_OBJECTS) {
  208. av_log(avctx, AV_LOG_ERROR, "Too many objects in epoch\n");
  209. return AVERROR_INVALIDDATA;
  210. }
  211. object = &ctx->objects.object[ctx->objects.count++];
  212. object->id = id;
  213. }
  214. /* skip object version number */
  215. buf += 1;
  216. /* Read the Sequence Description to determine if start of RLE data or appended to previous RLE */
  217. sequence_desc = bytestream_get_byte(&buf);
  218. if (!(sequence_desc & 0x80)) {
  219. /* Additional RLE data */
  220. if (buf_size > object->rle_remaining_len)
  221. return AVERROR_INVALIDDATA;
  222. memcpy(object->rle + object->rle_data_len, buf, buf_size);
  223. object->rle_data_len += buf_size;
  224. object->rle_remaining_len -= buf_size;
  225. return 0;
  226. }
  227. if (buf_size <= 7)
  228. return AVERROR_INVALIDDATA;
  229. buf_size -= 7;
  230. /* Decode rle bitmap length, stored size includes width/height data */
  231. rle_bitmap_len = bytestream_get_be24(&buf) - 2*2;
  232. if (buf_size > rle_bitmap_len) {
  233. av_log(avctx, AV_LOG_ERROR,
  234. "Buffer dimension %d larger than the expected RLE data %d\n",
  235. buf_size, rle_bitmap_len);
  236. return AVERROR_INVALIDDATA;
  237. }
  238. /* Get bitmap dimensions from data */
  239. width = bytestream_get_be16(&buf);
  240. height = bytestream_get_be16(&buf);
  241. /* Make sure the bitmap is not too large */
  242. if (avctx->width < width || avctx->height < height) {
  243. av_log(avctx, AV_LOG_ERROR, "Bitmap dimensions larger than video.\n");
  244. return AVERROR_INVALIDDATA;
  245. }
  246. object->w = width;
  247. object->h = height;
  248. av_fast_malloc(&object->rle, &object->rle_buffer_size, rle_bitmap_len);
  249. if (!object->rle)
  250. return AVERROR(ENOMEM);
  251. memcpy(object->rle, buf, buf_size);
  252. object->rle_data_len = buf_size;
  253. object->rle_remaining_len = rle_bitmap_len - buf_size;
  254. return 0;
  255. }
  256. /**
  257. * Parse the palette segment packet.
  258. *
  259. * The palette segment contains details of the palette,
  260. * a maximum of 256 colors can be defined.
  261. *
  262. * @param avctx contains the current codec context
  263. * @param buf pointer to the packet to process
  264. * @param buf_size size of packet to process
  265. */
  266. static int parse_palette_segment(AVCodecContext *avctx,
  267. const uint8_t *buf, int buf_size)
  268. {
  269. PGSSubContext *ctx = avctx->priv_data;
  270. PGSSubPalette *palette;
  271. const uint8_t *buf_end = buf + buf_size;
  272. const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;
  273. int color_id;
  274. int y, cb, cr, alpha;
  275. int r, g, b, r_add, g_add, b_add;
  276. int id;
  277. id = bytestream_get_byte(&buf);
  278. palette = find_palette(id, &ctx->palettes);
  279. if (!palette) {
  280. if (ctx->palettes.count >= MAX_EPOCH_PALETTES) {
  281. av_log(avctx, AV_LOG_ERROR, "Too many palettes in epoch\n");
  282. return AVERROR_INVALIDDATA;
  283. }
  284. palette = &ctx->palettes.palette[ctx->palettes.count++];
  285. palette->id = id;
  286. }
  287. /* Skip palette version */
  288. buf += 1;
  289. while (buf < buf_end) {
  290. color_id = bytestream_get_byte(&buf);
  291. y = bytestream_get_byte(&buf);
  292. cr = bytestream_get_byte(&buf);
  293. cb = bytestream_get_byte(&buf);
  294. alpha = bytestream_get_byte(&buf);
  295. YUV_TO_RGB1(cb, cr);
  296. YUV_TO_RGB2(r, g, b, y);
  297. ff_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
  298. /* Store color in palette */
  299. palette->clut[color_id] = RGBA(r,g,b,alpha);
  300. }
  301. return 0;
  302. }
  303. /**
  304. * Parse the presentation segment packet.
  305. *
  306. * The presentation segment contains details on the video
  307. * width, video height, x & y subtitle position.
  308. *
  309. * @param avctx contains the current codec context
  310. * @param buf pointer to the packet to process
  311. * @param buf_size size of packet to process
  312. * @todo TODO: Implement cropping
  313. */
  314. static int parse_presentation_segment(AVCodecContext *avctx,
  315. const uint8_t *buf, int buf_size,
  316. int64_t pts)
  317. {
  318. PGSSubContext *ctx = avctx->priv_data;
  319. int i, state, ret;
  320. // Video descriptor
  321. int w = bytestream_get_be16(&buf);
  322. int h = bytestream_get_be16(&buf);
  323. ctx->presentation.pts = pts;
  324. ff_dlog(avctx, "Video Dimensions %dx%d\n",
  325. w, h);
  326. ret = ff_set_dimensions(avctx, w, h);
  327. if (ret < 0)
  328. return ret;
  329. /* Skip 1 bytes of unknown, frame rate */
  330. buf++;
  331. // Composition descriptor
  332. ctx->presentation.id_number = bytestream_get_be16(&buf);
  333. /*
  334. * state is a 2 bit field that defines pgs epoch boundaries
  335. * 00 - Normal, previously defined objects and palettes are still valid
  336. * 01 - Acquisition point, previous objects and palettes can be released
  337. * 10 - Epoch start, previous objects and palettes can be released
  338. * 11 - Epoch continue, previous objects and palettes can be released
  339. *
  340. * reserved 6 bits discarded
  341. */
  342. state = bytestream_get_byte(&buf) >> 6;
  343. if (state != 0) {
  344. flush_cache(avctx);
  345. }
  346. /*
  347. * skip palette_update_flag (0x80),
  348. */
  349. buf += 1;
  350. ctx->presentation.palette_id = bytestream_get_byte(&buf);
  351. ctx->presentation.object_count = bytestream_get_byte(&buf);
  352. if (ctx->presentation.object_count > MAX_OBJECT_REFS) {
  353. av_log(avctx, AV_LOG_ERROR,
  354. "Invalid number of presentation objects %d\n",
  355. ctx->presentation.object_count);
  356. ctx->presentation.object_count = 2;
  357. if (avctx->err_recognition & AV_EF_EXPLODE) {
  358. return AVERROR_INVALIDDATA;
  359. }
  360. }
  361. for (i = 0; i < ctx->presentation.object_count; i++)
  362. {
  363. ctx->presentation.objects[i].id = bytestream_get_be16(&buf);
  364. ctx->presentation.objects[i].window_id = bytestream_get_byte(&buf);
  365. ctx->presentation.objects[i].composition_flag = bytestream_get_byte(&buf);
  366. ctx->presentation.objects[i].x = bytestream_get_be16(&buf);
  367. ctx->presentation.objects[i].y = bytestream_get_be16(&buf);
  368. // If cropping
  369. if (ctx->presentation.objects[i].composition_flag & 0x80) {
  370. ctx->presentation.objects[i].crop_x = bytestream_get_be16(&buf);
  371. ctx->presentation.objects[i].crop_y = bytestream_get_be16(&buf);
  372. ctx->presentation.objects[i].crop_w = bytestream_get_be16(&buf);
  373. ctx->presentation.objects[i].crop_h = bytestream_get_be16(&buf);
  374. }
  375. ff_dlog(avctx, "Subtitle Placement x=%d, y=%d\n",
  376. ctx->presentation.objects[i].x, ctx->presentation.objects[i].y);
  377. if (ctx->presentation.objects[i].x > avctx->width ||
  378. ctx->presentation.objects[i].y > avctx->height) {
  379. av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
  380. ctx->presentation.objects[i].x,
  381. ctx->presentation.objects[i].y,
  382. avctx->width, avctx->height);
  383. ctx->presentation.objects[i].x = 0;
  384. ctx->presentation.objects[i].y = 0;
  385. if (avctx->err_recognition & AV_EF_EXPLODE) {
  386. return AVERROR_INVALIDDATA;
  387. }
  388. }
  389. }
  390. return 0;
  391. }
  392. /**
  393. * Parse the display segment packet.
  394. *
  395. * The display segment controls the updating of the display.
  396. *
  397. * @param avctx contains the current codec context
  398. * @param data pointer to the data pertaining the subtitle to display
  399. * @param buf pointer to the packet to process
  400. * @param buf_size size of packet to process
  401. */
  402. static int display_end_segment(AVCodecContext *avctx, void *data,
  403. const uint8_t *buf, int buf_size)
  404. {
  405. AVSubtitle *sub = data;
  406. PGSSubContext *ctx = avctx->priv_data;
  407. PGSSubPalette *palette;
  408. int i, ret;
  409. memset(sub, 0, sizeof(*sub));
  410. sub->pts = ctx->presentation.pts;
  411. sub->start_display_time = 0;
  412. // There is no explicit end time for PGS subtitles. The end time
  413. // is defined by the start of the next sub which may contain no
  414. // objects (i.e. clears the previous sub)
  415. sub->end_display_time = UINT32_MAX;
  416. sub->format = 0;
  417. // Blank if last object_count was 0.
  418. if (!ctx->presentation.object_count)
  419. return 1;
  420. sub->rects = av_mallocz(sizeof(*sub->rects) * ctx->presentation.object_count);
  421. if (!sub->rects) {
  422. return AVERROR(ENOMEM);
  423. }
  424. palette = find_palette(ctx->presentation.palette_id, &ctx->palettes);
  425. if (!palette) {
  426. // Missing palette. Should only happen with damaged streams.
  427. av_log(avctx, AV_LOG_ERROR, "Invalid palette id %d\n",
  428. ctx->presentation.palette_id);
  429. avsubtitle_free(sub);
  430. return AVERROR_INVALIDDATA;
  431. }
  432. for (i = 0; i < ctx->presentation.object_count; i++) {
  433. PGSSubObject *object;
  434. sub->rects[i] = av_mallocz(sizeof(*sub->rects[0]));
  435. if (!sub->rects[i]) {
  436. avsubtitle_free(sub);
  437. return AVERROR(ENOMEM);
  438. }
  439. sub->num_rects++;
  440. sub->rects[i]->type = SUBTITLE_BITMAP;
  441. /* Process bitmap */
  442. object = find_object(ctx->presentation.objects[i].id, &ctx->objects);
  443. if (!object) {
  444. // Missing object. Should only happen with damaged streams.
  445. av_log(avctx, AV_LOG_ERROR, "Invalid object id %d\n",
  446. ctx->presentation.objects[i].id);
  447. if (avctx->err_recognition & AV_EF_EXPLODE) {
  448. avsubtitle_free(sub);
  449. return AVERROR_INVALIDDATA;
  450. }
  451. // Leaves rect empty with 0 width and height.
  452. continue;
  453. }
  454. if (ctx->presentation.objects[i].composition_flag & 0x40)
  455. sub->rects[i]->flags |= AV_SUBTITLE_FLAG_FORCED;
  456. sub->rects[i]->x = ctx->presentation.objects[i].x;
  457. sub->rects[i]->y = ctx->presentation.objects[i].y;
  458. sub->rects[i]->w = object->w;
  459. sub->rects[i]->h = object->h;
  460. sub->rects[i]->pict.linesize[0] = object->w;
  461. if (object->rle) {
  462. if (object->rle_remaining_len) {
  463. av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
  464. object->rle_data_len, object->rle_remaining_len);
  465. if (avctx->err_recognition & AV_EF_EXPLODE) {
  466. avsubtitle_free(sub);
  467. return AVERROR_INVALIDDATA;
  468. }
  469. }
  470. ret = decode_rle(avctx, sub->rects[i], object->rle, object->rle_data_len);
  471. if (ret < 0) {
  472. if ((avctx->err_recognition & AV_EF_EXPLODE) ||
  473. ret == AVERROR(ENOMEM)) {
  474. avsubtitle_free(sub);
  475. return ret;
  476. }
  477. sub->rects[i]->w = 0;
  478. sub->rects[i]->h = 0;
  479. continue;
  480. }
  481. }
  482. /* Allocate memory for colors */
  483. sub->rects[i]->nb_colors = 256;
  484. sub->rects[i]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
  485. if (!sub->rects[i]->pict.data[1]) {
  486. avsubtitle_free(sub);
  487. return AVERROR(ENOMEM);
  488. }
  489. memcpy(sub->rects[i]->pict.data[1], palette->clut, sub->rects[i]->nb_colors * sizeof(uint32_t));
  490. }
  491. return 1;
  492. }
  493. static int decode(AVCodecContext *avctx, void *data, int *data_size,
  494. AVPacket *avpkt)
  495. {
  496. const uint8_t *buf = avpkt->data;
  497. int buf_size = avpkt->size;
  498. const uint8_t *buf_end;
  499. uint8_t segment_type;
  500. int segment_length;
  501. int i, ret;
  502. ff_dlog(avctx, "PGS sub packet:\n");
  503. for (i = 0; i < buf_size; i++) {
  504. ff_dlog(avctx, "%02x ", buf[i]);
  505. if (i % 16 == 15)
  506. ff_dlog(avctx, "\n");
  507. }
  508. if (i & 15)
  509. ff_dlog(avctx, "\n");
  510. *data_size = 0;
  511. /* Ensure that we have received at a least a segment code and segment length */
  512. if (buf_size < 3)
  513. return -1;
  514. buf_end = buf + buf_size;
  515. /* Step through buffer to identify segments */
  516. while (buf < buf_end) {
  517. segment_type = bytestream_get_byte(&buf);
  518. segment_length = bytestream_get_be16(&buf);
  519. ff_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
  520. if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
  521. break;
  522. ret = 0;
  523. switch (segment_type) {
  524. case PALETTE_SEGMENT:
  525. ret = parse_palette_segment(avctx, buf, segment_length);
  526. break;
  527. case OBJECT_SEGMENT:
  528. ret = parse_object_segment(avctx, buf, segment_length);
  529. break;
  530. case PRESENTATION_SEGMENT:
  531. ret = parse_presentation_segment(avctx, buf, segment_length, avpkt->pts);
  532. break;
  533. case WINDOW_SEGMENT:
  534. /*
  535. * Window Segment Structure (No new information provided):
  536. * 2 bytes: Unknown,
  537. * 2 bytes: X position of subtitle,
  538. * 2 bytes: Y position of subtitle,
  539. * 2 bytes: Width of subtitle,
  540. * 2 bytes: Height of subtitle.
  541. */
  542. break;
  543. case DISPLAY_SEGMENT:
  544. ret = display_end_segment(avctx, data, buf, segment_length);
  545. if (ret >= 0)
  546. *data_size = ret;
  547. break;
  548. default:
  549. av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",
  550. segment_type, segment_length);
  551. ret = AVERROR_INVALIDDATA;
  552. break;
  553. }
  554. if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
  555. return ret;
  556. buf += segment_length;
  557. }
  558. return buf_size;
  559. }
  560. AVCodec ff_pgssub_decoder = {
  561. .name = "pgssub",
  562. .long_name = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"),
  563. .type = AVMEDIA_TYPE_SUBTITLE,
  564. .id = AV_CODEC_ID_HDMV_PGS_SUBTITLE,
  565. .priv_data_size = sizeof(PGSSubContext),
  566. .init = init_decoder,
  567. .close = close_decoder,
  568. .decode = decode,
  569. };