libavcodec/pgssubdec.c
Go to the documentation of this file.
00001 /*
00002  * PGS subtitle decoder
00003  * Copyright (c) 2009 Stephen Backway
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00027 #include "avcodec.h"
00028 #include "dsputil.h"
00029 #include "bytestream.h"
00030 #include "libavutil/colorspace.h"
00031 #include "libavutil/imgutils.h"
00032 
00033 #define RGBA(r,g,b,a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))
00034 
00035 enum SegmentType {
00036     PALETTE_SEGMENT      = 0x14,
00037     PICTURE_SEGMENT      = 0x15,
00038     PRESENTATION_SEGMENT = 0x16,
00039     WINDOW_SEGMENT       = 0x17,
00040     DISPLAY_SEGMENT      = 0x80,
00041 };
00042 
00043 typedef struct PGSSubPictureReference {
00044     int x;
00045     int y;
00046     int picture_id;
00047 } PGSSubPictureReference;
00048 
00049 typedef struct PGSSubPresentation {
00050     int                    id_number;
00051     int                    object_count;
00052     PGSSubPictureReference *objects;
00053 } PGSSubPresentation;
00054 
00055 typedef struct PGSSubPicture {
00056     int          w;
00057     int          h;
00058     uint8_t      *rle;
00059     unsigned int rle_buffer_size, rle_data_len;
00060     unsigned int rle_remaining_len;
00061 } PGSSubPicture;
00062 
00063 typedef struct PGSSubContext {
00064     PGSSubPresentation presentation;
00065     uint32_t           clut[256];
00066     PGSSubPicture      pictures[UINT16_MAX];
00067 } PGSSubContext;
00068 
00069 static av_cold int init_decoder(AVCodecContext *avctx)
00070 {
00071     avctx->pix_fmt     = PIX_FMT_PAL8;
00072 
00073     return 0;
00074 }
00075 
00076 static av_cold int close_decoder(AVCodecContext *avctx)
00077 {
00078     uint16_t picture;
00079 
00080     PGSSubContext *ctx = avctx->priv_data;
00081 
00082     av_freep(&ctx->presentation.objects);
00083     ctx->presentation.object_count = 0;
00084 
00085     for (picture = 0; picture < UINT16_MAX; ++picture) {
00086         av_freep(&ctx->pictures[picture].rle);
00087         ctx->pictures[picture].rle_buffer_size = 0;
00088     }
00089 
00090     return 0;
00091 }
00092 
00103 static int decode_rle(AVCodecContext *avctx, AVSubtitle *sub, int rect,
00104                       const uint8_t *buf, unsigned int buf_size)
00105 {
00106     const uint8_t *rle_bitmap_end;
00107     int pixel_count, line_count;
00108 
00109     rle_bitmap_end = buf + buf_size;
00110 
00111     sub->rects[rect]->pict.data[0] = av_malloc(sub->rects[rect]->w * sub->rects[rect]->h);
00112 
00113     if (!sub->rects[rect]->pict.data[0])
00114         return -1;
00115 
00116     pixel_count = 0;
00117     line_count  = 0;
00118 
00119     while (buf < rle_bitmap_end && line_count < sub->rects[rect]->h) {
00120         uint8_t flags, color;
00121         int run;
00122 
00123         color = bytestream_get_byte(&buf);
00124         run   = 1;
00125 
00126         if (color == 0x00) {
00127             flags = bytestream_get_byte(&buf);
00128             run   = flags & 0x3f;
00129             if (flags & 0x40)
00130                 run = (run << 8) + bytestream_get_byte(&buf);
00131             color = flags & 0x80 ? bytestream_get_byte(&buf) : 0;
00132         }
00133 
00134         if (run > 0 && pixel_count + run <= sub->rects[rect]->w * sub->rects[rect]->h) {
00135             memset(sub->rects[rect]->pict.data[0] + pixel_count, color, run);
00136             pixel_count += run;
00137         } else if (!run) {
00138             /*
00139              * New Line. Check if correct pixels decoded, if not display warning
00140              * and adjust bitmap pointer to correct new line position.
00141              */
00142             if (pixel_count % sub->rects[rect]->w > 0)
00143                 av_log(avctx, AV_LOG_ERROR, "Decoded %d pixels, when line should be %d pixels\n",
00144                        pixel_count % sub->rects[rect]->w, sub->rects[rect]->w);
00145             line_count++;
00146         }
00147     }
00148 
00149     if (pixel_count < sub->rects[rect]->w * sub->rects[rect]->h) {
00150         av_log(avctx, AV_LOG_ERROR, "Insufficient RLE data for subtitle\n");
00151         return -1;
00152     }
00153 
00154     av_dlog(avctx, "Pixel Count = %d, Area = %d\n", pixel_count, sub->rects[rect]->w * sub->rects[rect]->h);
00155 
00156     return 0;
00157 }
00158 
00170 static int parse_picture_segment(AVCodecContext *avctx,
00171                                   const uint8_t *buf, int buf_size)
00172 {
00173     PGSSubContext *ctx = avctx->priv_data;
00174 
00175     uint8_t sequence_desc;
00176     unsigned int rle_bitmap_len, width, height;
00177     uint16_t picture_id;
00178 
00179     if (buf_size <= 4)
00180         return -1;
00181     buf_size -= 4;
00182 
00183     picture_id = bytestream_get_be16(&buf);
00184 
00185     /* skip 1 unknown byte: Version Number */
00186     buf++;
00187 
00188     /* Read the Sequence Description to determine if start of RLE data or appended to previous RLE */
00189     sequence_desc = bytestream_get_byte(&buf);
00190 
00191     if (!(sequence_desc & 0x80)) {
00192         /* Additional RLE data */
00193         if (buf_size > ctx->pictures[picture_id].rle_remaining_len)
00194             return -1;
00195 
00196         memcpy(ctx->pictures[picture_id].rle + ctx->pictures[picture_id].rle_data_len, buf, buf_size);
00197         ctx->pictures[picture_id].rle_data_len += buf_size;
00198         ctx->pictures[picture_id].rle_remaining_len -= buf_size;
00199 
00200         return 0;
00201     }
00202 
00203     if (buf_size <= 7)
00204         return -1;
00205     buf_size -= 7;
00206 
00207     /* Decode rle bitmap length, stored size includes width/height data */
00208     rle_bitmap_len = bytestream_get_be24(&buf) - 2*2;
00209 
00210     /* Get bitmap dimensions from data */
00211     width  = bytestream_get_be16(&buf);
00212     height = bytestream_get_be16(&buf);
00213 
00214     /* Make sure the bitmap is not too large */
00215     if (avctx->width < width || avctx->height < height) {
00216         av_log(avctx, AV_LOG_ERROR, "Bitmap dimensions larger than video.\n");
00217         return -1;
00218     }
00219 
00220     ctx->pictures[picture_id].w = width;
00221     ctx->pictures[picture_id].h = height;
00222 
00223     av_fast_malloc(&ctx->pictures[picture_id].rle, &ctx->pictures[picture_id].rle_buffer_size, rle_bitmap_len);
00224 
00225     if (!ctx->pictures[picture_id].rle)
00226         return -1;
00227 
00228     memcpy(ctx->pictures[picture_id].rle, buf, buf_size);
00229     ctx->pictures[picture_id].rle_data_len      = buf_size;
00230     ctx->pictures[picture_id].rle_remaining_len = rle_bitmap_len - buf_size;
00231 
00232     return 0;
00233 }
00234 
00245 static void parse_palette_segment(AVCodecContext *avctx,
00246                                   const uint8_t *buf, int buf_size)
00247 {
00248     PGSSubContext *ctx = avctx->priv_data;
00249 
00250     const uint8_t *buf_end = buf + buf_size;
00251     const uint8_t *cm      = ff_cropTbl + MAX_NEG_CROP;
00252     int color_id;
00253     int y, cb, cr, alpha;
00254     int r, g, b, r_add, g_add, b_add;
00255 
00256     /* Skip two null bytes */
00257     buf += 2;
00258 
00259     while (buf < buf_end) {
00260         color_id  = bytestream_get_byte(&buf);
00261         y         = bytestream_get_byte(&buf);
00262         cr        = bytestream_get_byte(&buf);
00263         cb        = bytestream_get_byte(&buf);
00264         alpha     = bytestream_get_byte(&buf);
00265 
00266         YUV_TO_RGB1(cb, cr);
00267         YUV_TO_RGB2(r, g, b, y);
00268 
00269         av_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha);
00270 
00271         /* Store color in palette */
00272         ctx->clut[color_id] = RGBA(r,g,b,alpha);
00273     }
00274 }
00275 
00288 static void parse_presentation_segment(AVCodecContext *avctx,
00289                                        const uint8_t *buf, int buf_size)
00290 {
00291     PGSSubContext *ctx = avctx->priv_data;
00292 
00293     int w = bytestream_get_be16(&buf);
00294     int h = bytestream_get_be16(&buf);
00295 
00296     uint16_t object_index;
00297 
00298     av_dlog(avctx, "Video Dimensions %dx%d\n",
00299             w, h);
00300     if (av_image_check_size(w, h, 0, avctx) >= 0)
00301         avcodec_set_dimensions(avctx, w, h);
00302 
00303     /* Skip 1 bytes of unknown, frame rate? */
00304     buf++;
00305 
00306     ctx->presentation.id_number = bytestream_get_be16(&buf);
00307 
00308     /*
00309      * Skip 3 bytes of unknown:
00310      *     state
00311      *     palette_update_flag (0x80),
00312      *     palette_id_to_use,
00313      */
00314     buf += 3;
00315 
00316     ctx->presentation.object_count = bytestream_get_byte(&buf);
00317     if (!ctx->presentation.object_count)
00318         return;
00319 
00320     /* Verify that enough bytes are remaining for all of the objects. */
00321     buf_size -= 11;
00322     if (buf_size < ctx->presentation.object_count * 8) {
00323         ctx->presentation.object_count = 0;
00324         return;
00325     }
00326 
00327     av_freep(&ctx->presentation.objects);
00328     ctx->presentation.objects = av_malloc(sizeof(PGSSubPictureReference) * ctx->presentation.object_count);
00329     if (!ctx->presentation.objects) {
00330         ctx->presentation.object_count = 0;
00331         return;
00332     }
00333 
00334     for (object_index = 0; object_index < ctx->presentation.object_count; ++object_index) {
00335         PGSSubPictureReference *reference = &ctx->presentation.objects[object_index];
00336         reference->picture_id             = bytestream_get_be16(&buf);
00337 
00338          /*
00339          * Skip 2 bytes of unknown:
00340          *     window_id_ref,
00341          *     composition_flag (0x80 - object cropped, 0x40 - object forced)
00342          */
00343         buf += 2;
00344 
00345         reference->x = bytestream_get_be16(&buf);
00346         reference->y = bytestream_get_be16(&buf);
00347 
00348         /* TODO If cropping, cropping_x, cropping_y, cropping_width, cropping_height (all 2 bytes).*/
00349         av_dlog(avctx, "Subtitle Placement ID=%d, x=%d, y=%d\n", reference->picture_id, reference->x, reference->y);
00350 
00351         if (reference->x > avctx->width || reference->y > avctx->height) {
00352             av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",
00353                    reference->x, reference->y, avctx->width, avctx->height);
00354             reference->x = 0;
00355             reference->y = 0;
00356         }
00357     }
00358 }
00359 
00375 static int display_end_segment(AVCodecContext *avctx, void *data,
00376                                const uint8_t *buf, int buf_size)
00377 {
00378     AVSubtitle    *sub = data;
00379     PGSSubContext *ctx = avctx->priv_data;
00380 
00381     uint16_t rect;
00382 
00383     /*
00384      *      The end display time is a timeout value and is only reached
00385      *      if the next subtitle is later than timeout or subtitle has
00386      *      not been cleared by a subsequent empty display command.
00387      */
00388 
00389     memset(sub, 0, sizeof(*sub));
00390 
00391     // Blank if last object_count was 0.
00392     if (!ctx->presentation.object_count)
00393         return 1;
00394 
00395     sub->start_display_time = 0;
00396     sub->end_display_time   = 20000;
00397     sub->format             = 0;
00398 
00399     sub->num_rects = ctx->presentation.object_count;
00400     sub->rects     = av_mallocz(sizeof(*sub->rects) * sub->num_rects);
00401 
00402     for (rect = 0; rect < sub->num_rects; ++rect) {
00403         uint16_t picture_id    = ctx->presentation.objects[rect].picture_id;
00404         sub->rects[rect]       = av_mallocz(sizeof(*sub->rects[rect]));
00405         sub->rects[rect]->x    = ctx->presentation.objects[rect].x;
00406         sub->rects[rect]->y    = ctx->presentation.objects[rect].y;
00407         sub->rects[rect]->w    = ctx->pictures[picture_id].w;
00408         sub->rects[rect]->h    = ctx->pictures[picture_id].h;
00409         sub->rects[rect]->type = SUBTITLE_BITMAP;
00410 
00411         /* Process bitmap */
00412         sub->rects[rect]->pict.linesize[0] = ctx->pictures[picture_id].w;
00413         if (ctx->pictures[picture_id].rle) {
00414             if (ctx->pictures[picture_id].rle_remaining_len)
00415                 av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n",
00416                        ctx->pictures[picture_id].rle_data_len, ctx->pictures[picture_id].rle_remaining_len);
00417             if (decode_rle(avctx, sub, rect, ctx->pictures[picture_id].rle, ctx->pictures[picture_id].rle_data_len) < 0)
00418                 return 0;
00419         }
00420 
00421         /* Allocate memory for colors */
00422         sub->rects[rect]->nb_colors    = 256;
00423         sub->rects[rect]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
00424 
00425         memcpy(sub->rects[rect]->pict.data[1], ctx->clut, sub->rects[rect]->nb_colors * sizeof(uint32_t));
00426     }
00427 
00428     return 1;
00429 }
00430 
00431 static int decode(AVCodecContext *avctx, void *data, int *data_size,
00432                   AVPacket *avpkt)
00433 {
00434     const uint8_t *buf = avpkt->data;
00435     int buf_size       = avpkt->size;
00436 
00437     const uint8_t *buf_end;
00438     uint8_t       segment_type;
00439     int           segment_length;
00440     int i;
00441 
00442     av_dlog(avctx, "PGS sub packet:\n");
00443 
00444     for (i = 0; i < buf_size; i++) {
00445         av_dlog(avctx, "%02x ", buf[i]);
00446         if (i % 16 == 15)
00447             av_dlog(avctx, "\n");
00448     }
00449 
00450     if (i & 15)
00451         av_dlog(avctx, "\n");
00452 
00453     *data_size = 0;
00454 
00455     /* Ensure that we have received at a least a segment code and segment length */
00456     if (buf_size < 3)
00457         return -1;
00458 
00459     buf_end = buf + buf_size;
00460 
00461     /* Step through buffer to identify segments */
00462     while (buf < buf_end) {
00463         segment_type   = bytestream_get_byte(&buf);
00464         segment_length = bytestream_get_be16(&buf);
00465 
00466         av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);
00467 
00468         if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)
00469             break;
00470 
00471         switch (segment_type) {
00472         case PALETTE_SEGMENT:
00473             parse_palette_segment(avctx, buf, segment_length);
00474             break;
00475         case PICTURE_SEGMENT:
00476             parse_picture_segment(avctx, buf, segment_length);
00477             break;
00478         case PRESENTATION_SEGMENT:
00479             parse_presentation_segment(avctx, buf, segment_length);
00480             break;
00481         case WINDOW_SEGMENT:
00482             /*
00483              * Window Segment Structure (No new information provided):
00484              *     2 bytes: Unkown,
00485              *     2 bytes: X position of subtitle,
00486              *     2 bytes: Y position of subtitle,
00487              *     2 bytes: Width of subtitle,
00488              *     2 bytes: Height of subtitle.
00489              */
00490             break;
00491         case DISPLAY_SEGMENT:
00492             *data_size = display_end_segment(avctx, data, buf, segment_length);
00493             break;
00494         default:
00495             av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",
00496                    segment_type, segment_length);
00497             break;
00498         }
00499 
00500         buf += segment_length;
00501     }
00502 
00503     return buf_size;
00504 }
00505 
00506 AVCodec ff_pgssub_decoder = {
00507     .name           = "pgssub",
00508     .type           = AVMEDIA_TYPE_SUBTITLE,
00509     .id             = CODEC_ID_HDMV_PGS_SUBTITLE,
00510     .priv_data_size = sizeof(PGSSubContext),
00511     .init           = init_decoder,
00512     .close          = close_decoder,
00513     .decode         = decode,
00514     .long_name = NULL_IF_CONFIG_SMALL("HDMV Presentation Graphic Stream subtitles"),
00515 };