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