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.

663 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. av_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. /* Get bitmap dimensions from data */
  233. width = bytestream_get_be16(&buf);
  234. height = bytestream_get_be16(&buf);
  235. /* Make sure the bitmap is not too large */
  236. if (avctx->width < width || avctx->height < height) {
  237. av_log(avctx, AV_LOG_ERROR, "Bitmap dimensions larger than video.\n");
  238. return AVERROR_INVALIDDATA;
  239. }
  240. object->w = width;
  241. object->h = height;
  242. av_fast_malloc(&object->rle, &object->rle_buffer_size, rle_bitmap_len);
  243. if (!object->rle)
  244. return AVERROR(ENOMEM);
  245. memcpy(object->rle, buf, buf_size);
  246. object->rle_data_len = buf_size;
  247. object->rle_remaining_len = rle_bitmap_len - buf_size;
  248. return 0;
  249. }
  250. /**
  251. * Parse the palette segment packet.
  252. *
  253. * The palette segment contains details of the palette,
  254. * a maximum of 256 colors can be defined.
  255. *
  256. * @param avctx contains the current codec context
  257. * @param buf pointer to the packet to process
  258. * @param buf_size size of packet to process
  259. */
  260. static int parse_palette_segment(AVCodecContext *avctx,
  261. const uint8_t *buf, int buf_size)
  262. {
  263. PGSSubContext *ctx = avctx->priv_data;
  264. PGSSubPalette *palette;
  265. const uint8_t *buf_end = buf + buf_size;
  266. const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;
  267. int color_id;
  268. int y, cb, cr, alpha;
  269. int r, g, b, r_add, g_add, b_add;
  270. int id;
  271. id = bytestream_get_byte(&buf);
  272. palette = find_palette(id, &ctx->palettes);
  273. if (!palette) {
  274. if (ctx->palettes.count >= MAX_EPOCH_PALETTES) {
  275. av_log(avctx, AV_LOG_ERROR, "Too many palettes in epoch\n");
  276. return AVERROR_INVALIDDATA;
  277. }
  278. palette = &ctx->palettes.palette[ctx->palettes.count++];
  279. palette->id = id;
  280. }
  281. /* Skip palette version */
  282. buf += 1;
  283. while (buf < buf_end) {
  284. color_id = bytestream_get_byte(&buf);
  285. y = bytestream_get_byte(&buf);
  286. cr = bytestream_get_byte(&buf);
  287. cb = bytestream_get_byte(&buf);
  288. alpha = bytestream_get_byte(&buf);
  289. YUV_TO_RGB1(cb, cr);
  290. YUV_TO_RGB2(r, g, b, y);
  291. av_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
  292. /* Store color in palette */
  293. palette->clut[color_id] = RGBA(r,g,b,alpha);
  294. }
  295. return 0;
  296. }
  297. /**
  298. * Parse the presentation segment packet.
  299. *
  300. * The presentation segment contains details on the video
  301. * width, video height, x & y subtitle position.
  302. *
  303. * @param avctx contains the current codec context
  304. * @param buf pointer to the packet to process
  305. * @param buf_size size of packet to process
  306. * @todo TODO: Implement cropping
  307. */
  308. static int parse_presentation_segment(AVCodecContext *avctx,
  309. const uint8_t *buf, int buf_size,
  310. int64_t pts)
  311. {
  312. PGSSubContext *ctx = avctx->priv_data;
  313. int i, state, ret;
  314. // Video descriptor
  315. int w = bytestream_get_be16(&buf);
  316. int h = bytestream_get_be16(&buf);
  317. ctx->presentation.pts = pts;
  318. av_dlog(avctx, "Video Dimensions %dx%d\n",
  319. w, h);
  320. ret = ff_set_dimensions(avctx, w, h);
  321. if (ret < 0)
  322. return ret;
  323. /* Skip 1 bytes of unknown, frame rate */
  324. buf++;
  325. // Composition descriptor
  326. ctx->presentation.id_number = bytestream_get_be16(&buf);
  327. /*
  328. * state is a 2 bit field that defines pgs epoch boundaries
  329. * 00 - Normal, previously defined objects and palettes are still valid
  330. * 01 - Acquisition point, previous objects and palettes can be released
  331. * 10 - Epoch start, previous objects and palettes can be released
  332. * 11 - Epoch continue, previous objects and palettes can be released
  333. *
  334. * reserved 6 bits discarded
  335. */
  336. state = bytestream_get_byte(&buf) >> 6;
  337. if (state != 0) {
  338. flush_cache(avctx);
  339. }
  340. /*
  341. * skip palette_update_flag (0x80),
  342. */
  343. buf += 1;
  344. ctx->presentation.palette_id = bytestream_get_byte(&buf);
  345. ctx->presentation.object_count = bytestream_get_byte(&buf);
  346. if (ctx->presentation.object_count > MAX_OBJECT_REFS) {
  347. av_log(avctx, AV_LOG_ERROR,
  348. "Invalid number of presentation objects %d\n",
  349. ctx->presentation.object_count);
  350. ctx->presentation.object_count = 2;
  351. if (avctx->err_recognition & AV_EF_EXPLODE) {
  352. return AVERROR_INVALIDDATA;
  353. }
  354. }
  355. for (i = 0; i < ctx->presentation.object_count; i++)
  356. {
  357. ctx->presentation.objects[i].id = bytestream_get_be16(&buf);
  358. ctx->presentation.objects[i].window_id = bytestream_get_byte(&buf);
  359. ctx->presentation.objects[i].composition_flag = bytestream_get_byte(&buf);
  360. ctx->presentation.objects[i].x = bytestream_get_be16(&buf);
  361. ctx->presentation.objects[i].y = bytestream_get_be16(&buf);
  362. // If cropping
  363. if (ctx->presentation.objects[i].composition_flag & 0x80) {
  364. ctx->presentation.objects[i].crop_x = bytestream_get_be16(&buf);
  365. ctx->presentation.objects[i].crop_y = bytestream_get_be16(&buf);
  366. ctx->presentation.objects[i].crop_w = bytestream_get_be16(&buf);
  367. ctx->presentation.objects[i].crop_h = bytestream_get_be16(&buf);
  368. }
  369. av_dlog(avctx, "Subtitle Placement x=%d, y=%d\n",
  370. ctx->presentation.objects[i].x, ctx->presentation.objects[i].y);
  371. if (ctx->presentation.objects[i].x > avctx->width ||
  372. ctx->presentation.objects[i].y > avctx->height) {
  373. av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
  374. ctx->presentation.objects[i].x,
  375. ctx->presentation.objects[i].y,
  376. avctx->width, avctx->height);
  377. ctx->presentation.objects[i].x = 0;
  378. ctx->presentation.objects[i].y = 0;
  379. if (avctx->err_recognition & AV_EF_EXPLODE) {
  380. return AVERROR_INVALIDDATA;
  381. }
  382. }
  383. }
  384. return 0;
  385. }
  386. /**
  387. * Parse the display segment packet.
  388. *
  389. * The display segment controls the updating of the display.
  390. *
  391. * @param avctx contains the current codec context
  392. * @param data pointer to the data pertaining the subtitle to display
  393. * @param buf pointer to the packet to process
  394. * @param buf_size size of packet to process
  395. */
  396. static int display_end_segment(AVCodecContext *avctx, void *data,
  397. const uint8_t *buf, int buf_size)
  398. {
  399. AVSubtitle *sub = data;
  400. PGSSubContext *ctx = avctx->priv_data;
  401. PGSSubPalette *palette;
  402. int i, ret;
  403. memset(sub, 0, sizeof(*sub));
  404. sub->pts = ctx->presentation.pts;
  405. sub->start_display_time = 0;
  406. // There is no explicit end time for PGS subtitles. The end time
  407. // is defined by the start of the next sub which may contain no
  408. // objects (i.e. clears the previous sub)
  409. sub->end_display_time = UINT32_MAX;
  410. sub->format = 0;
  411. // Blank if last object_count was 0.
  412. if (!ctx->presentation.object_count)
  413. return 1;
  414. sub->rects = av_mallocz(sizeof(*sub->rects) * ctx->presentation.object_count);
  415. if (!sub->rects) {
  416. return AVERROR(ENOMEM);
  417. }
  418. palette = find_palette(ctx->presentation.palette_id, &ctx->palettes);
  419. if (!palette) {
  420. // Missing palette. Should only happen with damaged streams.
  421. av_log(avctx, AV_LOG_ERROR, "Invalid palette id %d\n",
  422. ctx->presentation.palette_id);
  423. avsubtitle_free(sub);
  424. return AVERROR_INVALIDDATA;
  425. }
  426. for (i = 0; i < ctx->presentation.object_count; i++) {
  427. PGSSubObject *object;
  428. sub->rects[i] = av_mallocz(sizeof(*sub->rects[0]));
  429. if (!sub->rects[i]) {
  430. avsubtitle_free(sub);
  431. return AVERROR(ENOMEM);
  432. }
  433. sub->num_rects++;
  434. sub->rects[i]->type = SUBTITLE_BITMAP;
  435. /* Process bitmap */
  436. object = find_object(ctx->presentation.objects[i].id, &ctx->objects);
  437. if (!object) {
  438. // Missing object. Should only happen with damaged streams.
  439. av_log(avctx, AV_LOG_ERROR, "Invalid object id %d\n",
  440. ctx->presentation.objects[i].id);
  441. if (avctx->err_recognition & AV_EF_EXPLODE) {
  442. avsubtitle_free(sub);
  443. return AVERROR_INVALIDDATA;
  444. }
  445. // Leaves rect empty with 0 width and height.
  446. continue;
  447. }
  448. if (ctx->presentation.objects[i].composition_flag & 0x40)
  449. sub->rects[i]->flags |= AV_SUBTITLE_FLAG_FORCED;
  450. sub->rects[i]->x = ctx->presentation.objects[i].x;
  451. sub->rects[i]->y = ctx->presentation.objects[i].y;
  452. sub->rects[i]->w = object->w;
  453. sub->rects[i]->h = object->h;
  454. sub->rects[i]->pict.linesize[0] = object->w;
  455. if (object->rle) {
  456. if (object->rle_remaining_len) {
  457. av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
  458. object->rle_data_len, object->rle_remaining_len);
  459. if (avctx->err_recognition & AV_EF_EXPLODE) {
  460. avsubtitle_free(sub);
  461. return AVERROR_INVALIDDATA;
  462. }
  463. }
  464. ret = decode_rle(avctx, sub->rects[i], object->rle, object->rle_data_len);
  465. if (ret < 0) {
  466. if ((avctx->err_recognition & AV_EF_EXPLODE) ||
  467. ret == AVERROR(ENOMEM)) {
  468. avsubtitle_free(sub);
  469. return ret;
  470. }
  471. sub->rects[i]->w = 0;
  472. sub->rects[i]->h = 0;
  473. continue;
  474. }
  475. }
  476. /* Allocate memory for colors */
  477. sub->rects[i]->nb_colors = 256;
  478. sub->rects[i]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
  479. if (!sub->rects[i]->pict.data[1]) {
  480. avsubtitle_free(sub);
  481. return AVERROR(ENOMEM);
  482. }
  483. memcpy(sub->rects[i]->pict.data[1], palette->clut, sub->rects[i]->nb_colors * sizeof(uint32_t));
  484. }
  485. return 1;
  486. }
  487. static int decode(AVCodecContext *avctx, void *data, int *data_size,
  488. AVPacket *avpkt)
  489. {
  490. const uint8_t *buf = avpkt->data;
  491. int buf_size = avpkt->size;
  492. const uint8_t *buf_end;
  493. uint8_t segment_type;
  494. int segment_length;
  495. int i, ret;
  496. av_dlog(avctx, "PGS sub packet:\n");
  497. for (i = 0; i < buf_size; i++) {
  498. av_dlog(avctx, "%02x ", buf[i]);
  499. if (i % 16 == 15)
  500. av_dlog(avctx, "\n");
  501. }
  502. if (i & 15)
  503. av_dlog(avctx, "\n");
  504. *data_size = 0;
  505. /* Ensure that we have received at a least a segment code and segment length */
  506. if (buf_size < 3)
  507. return -1;
  508. buf_end = buf + buf_size;
  509. /* Step through buffer to identify segments */
  510. while (buf < buf_end) {
  511. segment_type = bytestream_get_byte(&buf);
  512. segment_length = bytestream_get_be16(&buf);
  513. av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
  514. if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
  515. break;
  516. ret = 0;
  517. switch (segment_type) {
  518. case PALETTE_SEGMENT:
  519. ret = parse_palette_segment(avctx, buf, segment_length);
  520. break;
  521. case OBJECT_SEGMENT:
  522. ret = parse_object_segment(avctx, buf, segment_length);
  523. break;
  524. case PRESENTATION_SEGMENT:
  525. ret = parse_presentation_segment(avctx, buf, segment_length, avpkt->pts);
  526. break;
  527. case WINDOW_SEGMENT:
  528. /*
  529. * Window Segment Structure (No new information provided):
  530. * 2 bytes: Unknown,
  531. * 2 bytes: X position of subtitle,
  532. * 2 bytes: Y position of subtitle,
  533. * 2 bytes: Width of subtitle,
  534. * 2 bytes: Height of subtitle.
  535. */
  536. break;
  537. case DISPLAY_SEGMENT:
  538. ret = display_end_segment(avctx, data, buf, segment_length);
  539. if (ret >= 0)
  540. *data_size = ret;
  541. break;
  542. default:
  543. av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",
  544. segment_type, segment_length);
  545. ret = AVERROR_INVALIDDATA;
  546. break;
  547. }
  548. if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
  549. return ret;
  550. buf += segment_length;
  551. }
  552. return buf_size;
  553. }
  554. AVCodec ff_pgssub_decoder = {
  555. .name = "pgssub",
  556. .long_name = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"),
  557. .type = AVMEDIA_TYPE_SUBTITLE,
  558. .id = AV_CODEC_ID_HDMV_PGS_SUBTITLE,
  559. .priv_data_size = sizeof(PGSSubContext),
  560. .init = init_decoder,
  561. .close = close_decoder,
  562. .decode = decode,
  563. };