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