libavcodec/indeo3.c
Go to the documentation of this file.
00001 /*
00002  * Indeo Video v3 compatible decoder
00003  * Copyright (c) 2009 - 2011 Maxim Poliakovski
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00032 #include "libavutil/imgutils.h"
00033 #include "libavutil/intreadwrite.h"
00034 #include "avcodec.h"
00035 #include "internal.h"
00036 #include "dsputil.h"
00037 #include "bytestream.h"
00038 #include "get_bits.h"
00039 
00040 #include "indeo3data.h"
00041 
00042 /* RLE opcodes. */
00043 enum {
00044     RLE_ESC_F9    = 249, 
00045     RLE_ESC_FA    = 250, 
00046     RLE_ESC_FB    = 251, 
00047     RLE_ESC_FC    = 252, 
00048     RLE_ESC_FD    = 253, 
00049     RLE_ESC_FE    = 254, 
00050     RLE_ESC_FF    = 255  
00051 };
00052 
00053 
00054 /* Some constants for parsing frame bitstream flags. */
00055 #define BS_8BIT_PEL     (1 << 1) ///< 8bit pixel bitdepth indicator
00056 #define BS_KEYFRAME     (1 << 2) ///< intra frame indicator
00057 #define BS_MV_Y_HALF    (1 << 4) ///< vertical mv halfpel resolution indicator
00058 #define BS_MV_X_HALF    (1 << 5) ///< horizontal mv halfpel resolution indicator
00059 #define BS_NONREF       (1 << 8) ///< nonref (discardable) frame indicator
00060 #define BS_BUFFER        9       ///< indicates which of two frame buffers should be used
00061 
00062 
00063 typedef struct Plane {
00064     uint8_t         *buffers[2];
00065     uint8_t         *pixels[2]; 
00066     uint32_t        width;
00067     uint32_t        height;
00068     uint32_t        pitch;
00069 } Plane;
00070 
00071 #define CELL_STACK_MAX  20
00072 
00073 typedef struct Cell {
00074     int16_t         xpos;       
00075     int16_t         ypos;
00076     int16_t         width;      
00077     int16_t         height;     
00078     uint8_t         tree;       
00079     const int8_t    *mv_ptr;    
00080 } Cell;
00081 
00082 typedef struct Indeo3DecodeContext {
00083     AVCodecContext *avctx;
00084     AVFrame         frame;
00085     DSPContext      dsp;
00086 
00087     GetBitContext   gb;
00088     int             need_resync;
00089     int             skip_bits;
00090     const uint8_t   *next_cell_data;
00091     const uint8_t   *last_byte;
00092     const int8_t    *mc_vectors;
00093     unsigned        num_vectors;    
00094 
00095     int16_t         width, height;
00096     uint32_t        frame_num;      
00097     uint32_t        data_size;      
00098     uint16_t        frame_flags;    
00099     uint8_t         cb_offset;      
00100     uint8_t         buf_sel;        
00101     const uint8_t   *y_data_ptr;
00102     const uint8_t   *v_data_ptr;
00103     const uint8_t   *u_data_ptr;
00104     int32_t         y_data_size;
00105     int32_t         v_data_size;
00106     int32_t         u_data_size;
00107     const uint8_t   *alt_quant;     
00108     Plane           planes[3];
00109 } Indeo3DecodeContext;
00110 
00111 
00112 static uint8_t requant_tab[8][128];
00113 
00114 /*
00115  *  Build the static requantization table.
00116  *  This table is used to remap pixel values according to a specific
00117  *  quant index and thus avoid overflows while adding deltas.
00118  */
00119 static av_cold void build_requant_tab(void)
00120 {
00121     static int8_t offsets[8] = { 1, 1, 2, -3, -3, 3, 4, 4 };
00122     static int8_t deltas [8] = { 0, 1, 0,  4,  4, 1, 0, 1 };
00123 
00124     int i, j, step;
00125 
00126     for (i = 0; i < 8; i++) {
00127         step = i + 2;
00128         for (j = 0; j < 128; j++)
00129                 requant_tab[i][j] = (j + offsets[i]) / step * step + deltas[i];
00130     }
00131 
00132     /* some last elements calculated above will have values >= 128 */
00133     /* pixel values shall never exceed 127 so set them to non-overflowing values */
00134     /* according with the quantization step of the respective section */
00135     requant_tab[0][127] = 126;
00136     requant_tab[1][119] = 118;
00137     requant_tab[1][120] = 118;
00138     requant_tab[2][126] = 124;
00139     requant_tab[2][127] = 124;
00140     requant_tab[6][124] = 120;
00141     requant_tab[6][125] = 120;
00142     requant_tab[6][126] = 120;
00143     requant_tab[6][127] = 120;
00144 
00145     /* Patch for compatibility with the Intel's binary decoders */
00146     requant_tab[1][7] = 10;
00147     requant_tab[4][8] = 10;
00148 }
00149 
00150 
00151 static av_cold int allocate_frame_buffers(Indeo3DecodeContext *ctx,
00152                                           AVCodecContext *avctx)
00153 {
00154     int p, luma_width, luma_height, chroma_width, chroma_height;
00155     int luma_pitch, chroma_pitch, luma_size, chroma_size;
00156 
00157     luma_width  = ctx->width;
00158     luma_height = ctx->height;
00159 
00160     if (luma_width  < 16 || luma_width  > 640 ||
00161         luma_height < 16 || luma_height > 480 ||
00162         luma_width  &  3 || luma_height &   3) {
00163         av_log(avctx, AV_LOG_ERROR, "Invalid picture dimensions: %d x %d!\n",
00164                luma_width, luma_height);
00165         return AVERROR_INVALIDDATA;
00166     }
00167 
00168     chroma_width  = FFALIGN(luma_width  >> 2, 4);
00169     chroma_height = FFALIGN(luma_height >> 2, 4);
00170 
00171     luma_pitch   = FFALIGN(luma_width,   16);
00172     chroma_pitch = FFALIGN(chroma_width, 16);
00173 
00174     /* Calculate size of the luminance plane.  */
00175     /* Add one line more for INTRA prediction. */
00176     luma_size = luma_pitch * (luma_height + 1);
00177 
00178     /* Calculate size of a chrominance planes. */
00179     /* Add one line more for INTRA prediction. */
00180     chroma_size = chroma_pitch * (chroma_height + 1);
00181 
00182     /* allocate frame buffers */
00183     for (p = 0; p < 3; p++) {
00184         ctx->planes[p].pitch  = !p ? luma_pitch  : chroma_pitch;
00185         ctx->planes[p].width  = !p ? luma_width  : chroma_width;
00186         ctx->planes[p].height = !p ? luma_height : chroma_height;
00187 
00188         ctx->planes[p].buffers[0] = av_malloc(!p ? luma_size : chroma_size);
00189         ctx->planes[p].buffers[1] = av_malloc(!p ? luma_size : chroma_size);
00190 
00191         /* fill the INTRA prediction lines with the middle pixel value = 64 */
00192         memset(ctx->planes[p].buffers[0], 0x40, ctx->planes[p].pitch);
00193         memset(ctx->planes[p].buffers[1], 0x40, ctx->planes[p].pitch);
00194 
00195         /* set buffer pointers = buf_ptr + pitch and thus skip the INTRA prediction line */
00196         ctx->planes[p].pixels[0] = ctx->planes[p].buffers[0] + ctx->planes[p].pitch;
00197         ctx->planes[p].pixels[1] = ctx->planes[p].buffers[1] + ctx->planes[p].pitch;
00198         memset(ctx->planes[p].pixels[0], 0, ctx->planes[p].pitch * ctx->planes[p].height);
00199         memset(ctx->planes[p].pixels[1], 0, ctx->planes[p].pitch * ctx->planes[p].height);
00200     }
00201 
00202     return 0;
00203 }
00204 
00205 
00206 static av_cold void free_frame_buffers(Indeo3DecodeContext *ctx)
00207 {
00208     int p;
00209 
00210     for (p = 0; p < 3; p++) {
00211         av_freep(&ctx->planes[p].buffers[0]);
00212         av_freep(&ctx->planes[p].buffers[1]);
00213         ctx->planes[p].pixels[0] = ctx->planes[p].pixels[1] = 0;
00214     }
00215 }
00216 
00217 
00226 static int copy_cell(Indeo3DecodeContext *ctx, Plane *plane, Cell *cell)
00227 {
00228     int     h, w, mv_x, mv_y, offset, offset_dst;
00229     uint8_t *src, *dst;
00230 
00231     /* setup output and reference pointers */
00232     offset_dst  = (cell->ypos << 2) * plane->pitch + (cell->xpos << 2);
00233     dst         = plane->pixels[ctx->buf_sel] + offset_dst;
00234     mv_y        = cell->mv_ptr[0];
00235     mv_x        = cell->mv_ptr[1];
00236 
00237     /* -1 because there is an extra line on top for prediction */
00238     if ((cell->ypos << 2) + mv_y < -1 || (cell->xpos << 2) + mv_x < 0 ||
00239         ((cell->ypos + cell->height) << 2) + mv_y > plane->height     ||
00240         ((cell->xpos + cell->width)  << 2) + mv_x > plane->width) {
00241         av_log(ctx->avctx, AV_LOG_ERROR,
00242                "Motion vectors point out of the frame.\n");
00243         return AVERROR_INVALIDDATA;
00244     }
00245 
00246     offset      = offset_dst + mv_y * plane->pitch + mv_x;
00247     src         = plane->pixels[ctx->buf_sel ^ 1] + offset;
00248 
00249     h = cell->height << 2;
00250 
00251     for (w = cell->width; w > 0;) {
00252         /* copy using 16xH blocks */
00253         if (!((cell->xpos << 2) & 15) && w >= 4) {
00254             for (; w >= 4; src += 16, dst += 16, w -= 4)
00255                 ctx->dsp.put_no_rnd_pixels_tab[0][0](dst, src, plane->pitch, h);
00256         }
00257 
00258         /* copy using 8xH blocks */
00259         if (!((cell->xpos << 2) & 7) && w >= 2) {
00260             ctx->dsp.put_no_rnd_pixels_tab[1][0](dst, src, plane->pitch, h);
00261             w -= 2;
00262             src += 8;
00263             dst += 8;
00264         }
00265 
00266         if (w >= 1) {
00267             copy_block4(dst, src, plane->pitch, plane->pitch, h);
00268             w--;
00269             src += 4;
00270             dst += 4;
00271         }
00272     }
00273 
00274     return 0;
00275 }
00276 
00277 
00278 /* Average 4/8 pixels at once without rounding using SWAR */
00279 #define AVG_32(dst, src, ref) \
00280     AV_WN32A(dst, ((AV_RN32A(src) + AV_RN32A(ref)) >> 1) & 0x7F7F7F7FUL)
00281 
00282 #define AVG_64(dst, src, ref) \
00283     AV_WN64A(dst, ((AV_RN64A(src) + AV_RN64A(ref)) >> 1) & 0x7F7F7F7F7F7F7F7FULL)
00284 
00285 
00286 /*
00287  *  Replicate each even pixel as follows:
00288  *  ABCDEFGH -> AACCEEGG
00289  */
00290 static inline uint64_t replicate64(uint64_t a) {
00291 #if HAVE_BIGENDIAN
00292     a &= 0xFF00FF00FF00FF00ULL;
00293     a |= a >> 8;
00294 #else
00295     a &= 0x00FF00FF00FF00FFULL;
00296     a |= a << 8;
00297 #endif
00298     return a;
00299 }
00300 
00301 static inline uint32_t replicate32(uint32_t a) {
00302 #if HAVE_BIGENDIAN
00303     a &= 0xFF00FF00UL;
00304     a |= a >> 8;
00305 #else
00306     a &= 0x00FF00FFUL;
00307     a |= a << 8;
00308 #endif
00309     return a;
00310 }
00311 
00312 
00313 /* Fill n lines with 64bit pixel value pix */
00314 static inline void fill_64(uint8_t *dst, const uint64_t pix, int32_t n,
00315                            int32_t row_offset)
00316 {
00317     for (; n > 0; dst += row_offset, n--)
00318         AV_WN64A(dst, pix);
00319 }
00320 
00321 
00322 /* Error codes for cell decoding. */
00323 enum {
00324     IV3_NOERR       = 0,
00325     IV3_BAD_RLE     = 1,
00326     IV3_BAD_DATA    = 2,
00327     IV3_BAD_COUNTER = 3,
00328     IV3_UNSUPPORTED = 4,
00329     IV3_OUT_OF_DATA = 5
00330 };
00331 
00332 
00333 #define BUFFER_PRECHECK \
00334 if (*data_ptr >= last_ptr) \
00335     return IV3_OUT_OF_DATA; \
00336 
00337 #define RLE_BLOCK_COPY \
00338     if (cell->mv_ptr || !skip_flag) \
00339         copy_block4(dst, ref, row_offset, row_offset, 4 << v_zoom)
00340 
00341 #define RLE_BLOCK_COPY_8 \
00342     pix64 = AV_RN64A(ref);\
00343     if (is_first_row) {/* special prediction case: top line of a cell */\
00344         pix64 = replicate64(pix64);\
00345         fill_64(dst + row_offset, pix64, 7, row_offset);\
00346         AVG_64(dst, ref, dst + row_offset);\
00347     } else \
00348         fill_64(dst, pix64, 8, row_offset)
00349 
00350 #define RLE_LINES_COPY \
00351     copy_block4(dst, ref, row_offset, row_offset, num_lines << v_zoom)
00352 
00353 #define RLE_LINES_COPY_M10 \
00354     pix64 = AV_RN64A(ref);\
00355     if (is_top_of_cell) {\
00356         pix64 = replicate64(pix64);\
00357         fill_64(dst + row_offset, pix64, (num_lines << 1) - 1, row_offset);\
00358         AVG_64(dst, ref, dst + row_offset);\
00359     } else \
00360         fill_64(dst, pix64, num_lines << 1, row_offset)
00361 
00362 #define APPLY_DELTA_4 \
00363     AV_WN16A(dst + line_offset    ,\
00364              (AV_RN16A(ref    ) + delta_tab->deltas[dyad1]) & 0x7F7F);\
00365     AV_WN16A(dst + line_offset + 2,\
00366              (AV_RN16A(ref + 2) + delta_tab->deltas[dyad2]) & 0x7F7F);\
00367     if (mode >= 3) {\
00368         if (is_top_of_cell && !cell->ypos) {\
00369             AV_COPY32(dst, dst + row_offset);\
00370         } else {\
00371             AVG_32(dst, ref, dst + row_offset);\
00372         }\
00373     }
00374 
00375 #define APPLY_DELTA_8 \
00376     /* apply two 32-bit VQ deltas to next even line */\
00377     if (is_top_of_cell) { \
00378         AV_WN32A(dst + row_offset    , \
00379                  (replicate32(AV_RN32A(ref    )) + delta_tab->deltas_m10[dyad1]) & 0x7F7F7F7F);\
00380         AV_WN32A(dst + row_offset + 4, \
00381                  (replicate32(AV_RN32A(ref + 4)) + delta_tab->deltas_m10[dyad2]) & 0x7F7F7F7F);\
00382     } else { \
00383         AV_WN32A(dst + row_offset    , \
00384                  (AV_RN32A(ref    ) + delta_tab->deltas_m10[dyad1]) & 0x7F7F7F7F);\
00385         AV_WN32A(dst + row_offset + 4, \
00386                  (AV_RN32A(ref + 4) + delta_tab->deltas_m10[dyad2]) & 0x7F7F7F7F);\
00387     } \
00388     /* odd lines are not coded but rather interpolated/replicated */\
00389     /* first line of the cell on the top of image? - replicate */\
00390     /* otherwise - interpolate */\
00391     if (is_top_of_cell && !cell->ypos) {\
00392         AV_COPY64(dst, dst + row_offset);\
00393     } else \
00394         AVG_64(dst, ref, dst + row_offset);
00395 
00396 
00397 #define APPLY_DELTA_1011_INTER \
00398     if (mode == 10) { \
00399         AV_WN32A(dst                 , \
00400                  (AV_RN32A(dst                 ) + delta_tab->deltas_m10[dyad1]) & 0x7F7F7F7F);\
00401         AV_WN32A(dst + 4             , \
00402                  (AV_RN32A(dst + 4             ) + delta_tab->deltas_m10[dyad2]) & 0x7F7F7F7F);\
00403         AV_WN32A(dst + row_offset    , \
00404                  (AV_RN32A(dst + row_offset    ) + delta_tab->deltas_m10[dyad1]) & 0x7F7F7F7F);\
00405         AV_WN32A(dst + row_offset + 4, \
00406                  (AV_RN32A(dst + row_offset + 4) + delta_tab->deltas_m10[dyad2]) & 0x7F7F7F7F);\
00407     } else { \
00408         AV_WN16A(dst                 , \
00409                  (AV_RN16A(dst                 ) + delta_tab->deltas[dyad1]) & 0x7F7F);\
00410         AV_WN16A(dst + 2             , \
00411                  (AV_RN16A(dst + 2             ) + delta_tab->deltas[dyad2]) & 0x7F7F);\
00412         AV_WN16A(dst + row_offset    , \
00413                  (AV_RN16A(dst + row_offset    ) + delta_tab->deltas[dyad1]) & 0x7F7F);\
00414         AV_WN16A(dst + row_offset + 2, \
00415                  (AV_RN16A(dst + row_offset + 2) + delta_tab->deltas[dyad2]) & 0x7F7F);\
00416     }
00417 
00418 
00419 static int decode_cell_data(Cell *cell, uint8_t *block, uint8_t *ref_block,
00420                             int pitch, int h_zoom, int v_zoom, int mode,
00421                             const vqEntry *delta[2], int swap_quads[2],
00422                             const uint8_t **data_ptr, const uint8_t *last_ptr)
00423 {
00424     int           x, y, line, num_lines;
00425     int           rle_blocks = 0;
00426     uint8_t       code, *dst, *ref;
00427     const vqEntry *delta_tab;
00428     unsigned int  dyad1, dyad2;
00429     uint64_t      pix64;
00430     int           skip_flag = 0, is_top_of_cell, is_first_row = 1;
00431     int           row_offset, blk_row_offset, line_offset;
00432 
00433     row_offset     =  pitch;
00434     blk_row_offset = (row_offset << (2 + v_zoom)) - (cell->width << 2);
00435     line_offset    = v_zoom ? row_offset : 0;
00436 
00437     if (cell->height & v_zoom || cell->width & h_zoom)
00438         return IV3_BAD_DATA;
00439 
00440     for (y = 0; y < cell->height; is_first_row = 0, y += 1 + v_zoom) {
00441         for (x = 0; x < cell->width; x += 1 + h_zoom) {
00442             ref = ref_block;
00443             dst = block;
00444 
00445             if (rle_blocks > 0) {
00446                 if (mode <= 4) {
00447                     RLE_BLOCK_COPY;
00448                 } else if (mode == 10 && !cell->mv_ptr) {
00449                     RLE_BLOCK_COPY_8;
00450                 }
00451                 rle_blocks--;
00452             } else {
00453                 for (line = 0; line < 4;) {
00454                     num_lines = 1;
00455                     is_top_of_cell = is_first_row && !line;
00456 
00457                     /* select primary VQ table for odd, secondary for even lines */
00458                     if (mode <= 4)
00459                         delta_tab = delta[line & 1];
00460                     else
00461                         delta_tab = delta[1];
00462                     BUFFER_PRECHECK;
00463                     code = bytestream_get_byte(data_ptr);
00464                     if (code < 248) {
00465                         if (code < delta_tab->num_dyads) {
00466                             BUFFER_PRECHECK;
00467                             dyad1 = bytestream_get_byte(data_ptr);
00468                             dyad2 = code;
00469                             if (dyad1 >= delta_tab->num_dyads || dyad1 >= 248)
00470                                 return IV3_BAD_DATA;
00471                         } else {
00472                             /* process QUADS */
00473                             code -= delta_tab->num_dyads;
00474                             dyad1 = code / delta_tab->quad_exp;
00475                             dyad2 = code % delta_tab->quad_exp;
00476                             if (swap_quads[line & 1])
00477                                 FFSWAP(unsigned int, dyad1, dyad2);
00478                         }
00479                         if (mode <= 4) {
00480                             APPLY_DELTA_4;
00481                         } else if (mode == 10 && !cell->mv_ptr) {
00482                             APPLY_DELTA_8;
00483                         } else {
00484                             APPLY_DELTA_1011_INTER;
00485                         }
00486                     } else {
00487                         /* process RLE codes */
00488                         switch (code) {
00489                         case RLE_ESC_FC:
00490                             skip_flag  = 0;
00491                             rle_blocks = 1;
00492                             code       = 253;
00493                             /* FALLTHROUGH */
00494                         case RLE_ESC_FF:
00495                         case RLE_ESC_FE:
00496                         case RLE_ESC_FD:
00497                             num_lines = 257 - code - line;
00498                             if (num_lines <= 0)
00499                                 return IV3_BAD_RLE;
00500                             if (mode <= 4) {
00501                                 RLE_LINES_COPY;
00502                             } else if (mode == 10 && !cell->mv_ptr) {
00503                                 RLE_LINES_COPY_M10;
00504                             }
00505                             break;
00506                         case RLE_ESC_FB:
00507                             BUFFER_PRECHECK;
00508                             code = bytestream_get_byte(data_ptr);
00509                             rle_blocks = (code & 0x1F) - 1; /* set block counter */
00510                             if (code >= 64 || rle_blocks < 0)
00511                                 return IV3_BAD_COUNTER;
00512                             skip_flag = code & 0x20;
00513                             num_lines = 4 - line; /* enforce next block processing */
00514                             if (mode >= 10 || (cell->mv_ptr || !skip_flag)) {
00515                                 if (mode <= 4) {
00516                                     RLE_LINES_COPY;
00517                                 } else if (mode == 10 && !cell->mv_ptr) {
00518                                     RLE_LINES_COPY_M10;
00519                                 }
00520                             }
00521                             break;
00522                         case RLE_ESC_F9:
00523                             skip_flag  = 1;
00524                             rle_blocks = 1;
00525                             /* FALLTHROUGH */
00526                         case RLE_ESC_FA:
00527                             if (line)
00528                                 return IV3_BAD_RLE;
00529                             num_lines = 4; /* enforce next block processing */
00530                             if (cell->mv_ptr) {
00531                                 if (mode <= 4) {
00532                                     RLE_LINES_COPY;
00533                                 } else if (mode == 10 && !cell->mv_ptr) {
00534                                     RLE_LINES_COPY_M10;
00535                                 }
00536                             }
00537                             break;
00538                         default:
00539                             return IV3_UNSUPPORTED;
00540                         }
00541                     }
00542 
00543                     line += num_lines;
00544                     ref  += row_offset * (num_lines << v_zoom);
00545                     dst  += row_offset * (num_lines << v_zoom);
00546                 }
00547             }
00548 
00549             /* move to next horizontal block */
00550             block     += 4 << h_zoom;
00551             ref_block += 4 << h_zoom;
00552         }
00553 
00554         /* move to next line of blocks */
00555         ref_block += blk_row_offset;
00556         block     += blk_row_offset;
00557     }
00558     return IV3_NOERR;
00559 }
00560 
00561 
00575 static int decode_cell(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
00576                        Plane *plane, Cell *cell, const uint8_t *data_ptr,
00577                        const uint8_t *last_ptr)
00578 {
00579     int           x, mv_x, mv_y, mode, vq_index, prim_indx, second_indx;
00580     int           zoom_fac;
00581     int           offset, error = 0, swap_quads[2];
00582     uint8_t       code, *block, *ref_block = 0;
00583     const vqEntry *delta[2];
00584     const uint8_t *data_start = data_ptr;
00585 
00586     /* get coding mode and VQ table index from the VQ descriptor byte */
00587     code     = *data_ptr++;
00588     mode     = code >> 4;
00589     vq_index = code & 0xF;
00590 
00591     /* setup output and reference pointers */
00592     offset = (cell->ypos << 2) * plane->pitch + (cell->xpos << 2);
00593     block  =  plane->pixels[ctx->buf_sel] + offset;
00594     if (!cell->mv_ptr) {
00595         /* use previous line as reference for INTRA cells */
00596         ref_block = block - plane->pitch;
00597     } else if (mode >= 10) {
00598         /* for mode 10 and 11 INTER first copy the predicted cell into the current one */
00599         /* so we don't need to do data copying for each RLE code later */
00600         int ret = copy_cell(ctx, plane, cell);
00601         if (ret < 0)
00602             return ret;
00603     } else {
00604         /* set the pointer to the reference pixels for modes 0-4 INTER */
00605         mv_y      = cell->mv_ptr[0];
00606         mv_x      = cell->mv_ptr[1];
00607 
00608         /* -1 because there is an extra line on top for prediction */
00609         if ((cell->ypos << 2) + mv_y < -1 || (cell->xpos << 2) + mv_x < 0 ||
00610             ((cell->ypos + cell->height) << 2) + mv_y > plane->height     ||
00611             ((cell->xpos + cell->width)  << 2) + mv_x > plane->width) {
00612             av_log(ctx->avctx, AV_LOG_ERROR,
00613                    "Motion vectors point out of the frame.\n");
00614             return AVERROR_INVALIDDATA;
00615         }
00616 
00617         offset   += mv_y * plane->pitch + mv_x;
00618         ref_block = plane->pixels[ctx->buf_sel ^ 1] + offset;
00619     }
00620 
00621     /* select VQ tables as follows: */
00622     /* modes 0 and 3 use only the primary table for all lines in a block */
00623     /* while modes 1 and 4 switch between primary and secondary tables on alternate lines */
00624     if (mode == 1 || mode == 4) {
00625         code        = ctx->alt_quant[vq_index];
00626         prim_indx   = (code >> 4)  + ctx->cb_offset;
00627         second_indx = (code & 0xF) + ctx->cb_offset;
00628     } else {
00629         vq_index += ctx->cb_offset;
00630         prim_indx = second_indx = vq_index;
00631     }
00632 
00633     if (prim_indx >= 24 || second_indx >= 24) {
00634         av_log(avctx, AV_LOG_ERROR, "Invalid VQ table indexes! Primary: %d, secondary: %d!\n",
00635                prim_indx, second_indx);
00636         return AVERROR_INVALIDDATA;
00637     }
00638 
00639     delta[0] = &vq_tab[second_indx];
00640     delta[1] = &vq_tab[prim_indx];
00641     swap_quads[0] = second_indx >= 16;
00642     swap_quads[1] = prim_indx   >= 16;
00643 
00644     /* requantize the prediction if VQ index of this cell differs from VQ index */
00645     /* of the predicted cell in order to avoid overflows. */
00646     if (vq_index >= 8 && ref_block) {
00647         for (x = 0; x < cell->width << 2; x++)
00648             ref_block[x] = requant_tab[vq_index & 7][ref_block[x]];
00649     }
00650 
00651     error = IV3_NOERR;
00652 
00653     switch (mode) {
00654     case 0: /*------------------ MODES 0 & 1 (4x4 block processing) --------------------*/
00655     case 1:
00656     case 3: /*------------------ MODES 3 & 4 (4x8 block processing) --------------------*/
00657     case 4:
00658         if (mode >= 3 && cell->mv_ptr) {
00659             av_log(avctx, AV_LOG_ERROR, "Attempt to apply Mode 3/4 to an INTER cell!\n");
00660             return AVERROR_INVALIDDATA;
00661         }
00662 
00663         zoom_fac = mode >= 3;
00664         error = decode_cell_data(cell, block, ref_block, plane->pitch, 0, zoom_fac,
00665                                  mode, delta, swap_quads, &data_ptr, last_ptr);
00666         break;
00667     case 10: /*-------------------- MODE 10 (8x8 block processing) ---------------------*/
00668     case 11: /*----------------- MODE 11 (4x8 INTER block processing) ------------------*/
00669         if (mode == 10 && !cell->mv_ptr) { /* MODE 10 INTRA processing */
00670             error = decode_cell_data(cell, block, ref_block, plane->pitch, 1, 1,
00671                                      mode, delta, swap_quads, &data_ptr, last_ptr);
00672         } else { /* mode 10 and 11 INTER processing */
00673             if (mode == 11 && !cell->mv_ptr) {
00674                av_log(avctx, AV_LOG_ERROR, "Attempt to use Mode 11 for an INTRA cell!\n");
00675                return AVERROR_INVALIDDATA;
00676             }
00677 
00678             zoom_fac = mode == 10;
00679             error = decode_cell_data(cell, block, ref_block, plane->pitch,
00680                                      zoom_fac, 1, mode, delta, swap_quads,
00681                                      &data_ptr, last_ptr);
00682         }
00683         break;
00684     default:
00685         av_log(avctx, AV_LOG_ERROR, "Unsupported coding mode: %d\n", mode);
00686         return AVERROR_INVALIDDATA;
00687     }//switch mode
00688 
00689     switch (error) {
00690     case IV3_BAD_RLE:
00691         av_log(avctx, AV_LOG_ERROR, "Mode %d: RLE code %X is not allowed at the current line\n",
00692                mode, data_ptr[-1]);
00693         return AVERROR_INVALIDDATA;
00694     case IV3_BAD_DATA:
00695         av_log(avctx, AV_LOG_ERROR, "Mode %d: invalid VQ data\n", mode);
00696         return AVERROR_INVALIDDATA;
00697     case IV3_BAD_COUNTER:
00698         av_log(avctx, AV_LOG_ERROR, "Mode %d: RLE-FB invalid counter: %d\n", mode, code);
00699         return AVERROR_INVALIDDATA;
00700     case IV3_UNSUPPORTED:
00701         av_log(avctx, AV_LOG_ERROR, "Mode %d: unsupported RLE code: %X\n", mode, data_ptr[-1]);
00702         return AVERROR_INVALIDDATA;
00703     case IV3_OUT_OF_DATA:
00704         av_log(avctx, AV_LOG_ERROR, "Mode %d: attempt to read past end of buffer\n", mode);
00705         return AVERROR_INVALIDDATA;
00706     }
00707 
00708     return data_ptr - data_start; /* report number of bytes consumed from the input buffer */
00709 }
00710 
00711 
00712 /* Binary tree codes. */
00713 enum {
00714     H_SPLIT    = 0,
00715     V_SPLIT    = 1,
00716     INTRA_NULL = 2,
00717     INTER_DATA = 3
00718 };
00719 
00720 
00721 #define SPLIT_CELL(size, new_size) (new_size) = ((size) > 2) ? ((((size) + 2) >> 2) << 1) : 1
00722 
00723 #define UPDATE_BITPOS(n) \
00724     ctx->skip_bits  += (n); \
00725     ctx->need_resync = 1
00726 
00727 #define RESYNC_BITSTREAM \
00728     if (ctx->need_resync && !(get_bits_count(&ctx->gb) & 7)) { \
00729         skip_bits_long(&ctx->gb, ctx->skip_bits);              \
00730         ctx->skip_bits   = 0;                                  \
00731         ctx->need_resync = 0;                                  \
00732     }
00733 
00734 #define CHECK_CELL \
00735     if (curr_cell.xpos + curr_cell.width > (plane->width >> 2) ||               \
00736         curr_cell.ypos + curr_cell.height > (plane->height >> 2)) {             \
00737         av_log(avctx, AV_LOG_ERROR, "Invalid cell: x=%d, y=%d, w=%d, h=%d\n",   \
00738                curr_cell.xpos, curr_cell.ypos, curr_cell.width, curr_cell.height); \
00739         return AVERROR_INVALIDDATA;                                                              \
00740     }
00741 
00742 
00743 static int parse_bintree(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
00744                          Plane *plane, int code, Cell *ref_cell,
00745                          const int depth, const int strip_width)
00746 {
00747     Cell    curr_cell;
00748     int     bytes_used, ret;
00749 
00750     if (depth <= 0) {
00751         av_log(avctx, AV_LOG_ERROR, "Stack overflow (corrupted binary tree)!\n");
00752         return AVERROR_INVALIDDATA; // unwind recursion
00753     }
00754 
00755     curr_cell = *ref_cell; // clone parent cell
00756     if (code == H_SPLIT) {
00757         SPLIT_CELL(ref_cell->height, curr_cell.height);
00758         ref_cell->ypos   += curr_cell.height;
00759         ref_cell->height -= curr_cell.height;
00760         if (ref_cell->height <= 0 || curr_cell.height <= 0)
00761             return AVERROR_INVALIDDATA;
00762     } else if (code == V_SPLIT) {
00763         if (curr_cell.width > strip_width) {
00764             /* split strip */
00765             curr_cell.width = (curr_cell.width <= (strip_width << 1) ? 1 : 2) * strip_width;
00766         } else
00767             SPLIT_CELL(ref_cell->width, curr_cell.width);
00768         ref_cell->xpos  += curr_cell.width;
00769         ref_cell->width -= curr_cell.width;
00770         if (ref_cell->width <= 0 || curr_cell.width <= 0)
00771             return AVERROR_INVALIDDATA;
00772     }
00773 
00774     while (1) { /* loop until return */
00775         RESYNC_BITSTREAM;
00776         switch (code = get_bits(&ctx->gb, 2)) {
00777         case H_SPLIT:
00778         case V_SPLIT:
00779             if (parse_bintree(ctx, avctx, plane, code, &curr_cell, depth - 1, strip_width))
00780                 return AVERROR_INVALIDDATA;
00781             break;
00782         case INTRA_NULL:
00783             if (!curr_cell.tree) { /* MC tree INTRA code */
00784                 curr_cell.mv_ptr = 0; /* mark the current strip as INTRA */
00785                 curr_cell.tree   = 1; /* enter the VQ tree */
00786             } else { /* VQ tree NULL code */
00787                 RESYNC_BITSTREAM;
00788                 code = get_bits(&ctx->gb, 2);
00789                 if (code >= 2) {
00790                     av_log(avctx, AV_LOG_ERROR, "Invalid VQ_NULL code: %d\n", code);
00791                     return AVERROR_INVALIDDATA;
00792                 }
00793                 if (code == 1)
00794                     av_log(avctx, AV_LOG_ERROR, "SkipCell procedure not implemented yet!\n");
00795 
00796                 CHECK_CELL
00797                 if (!curr_cell.mv_ptr)
00798                     return AVERROR_INVALIDDATA;
00799                 ret = copy_cell(ctx, plane, &curr_cell);
00800                 return ret;
00801             }
00802             break;
00803         case INTER_DATA:
00804             if (!curr_cell.tree) { /* MC tree INTER code */
00805                 unsigned mv_idx;
00806                 /* get motion vector index and setup the pointer to the mv set */
00807                 if (!ctx->need_resync)
00808                     ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];
00809                 mv_idx = *(ctx->next_cell_data++) << 1;
00810                 if (mv_idx >= ctx->num_vectors) {
00811                     av_log(avctx, AV_LOG_ERROR, "motion vector index out of range\n");
00812                     return AVERROR_INVALIDDATA;
00813                 }
00814                 curr_cell.mv_ptr = &ctx->mc_vectors[mv_idx];
00815                 curr_cell.tree   = 1; /* enter the VQ tree */
00816                 UPDATE_BITPOS(8);
00817             } else { /* VQ tree DATA code */
00818                 if (!ctx->need_resync)
00819                     ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];
00820 
00821                 CHECK_CELL
00822                 bytes_used = decode_cell(ctx, avctx, plane, &curr_cell,
00823                                          ctx->next_cell_data, ctx->last_byte);
00824                 if (bytes_used < 0)
00825                     return AVERROR_INVALIDDATA;
00826 
00827                 UPDATE_BITPOS(bytes_used << 3);
00828                 ctx->next_cell_data += bytes_used;
00829                 return 0;
00830             }
00831             break;
00832         }
00833     }//while
00834 
00835     return 0;
00836 }
00837 
00838 
00839 static int decode_plane(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
00840                         Plane *plane, const uint8_t *data, int32_t data_size,
00841                         int32_t strip_width)
00842 {
00843     Cell            curr_cell;
00844     unsigned        num_vectors;
00845 
00846     /* each plane data starts with mc_vector_count field, */
00847     /* an optional array of motion vectors followed by the vq data */
00848     num_vectors = bytestream_get_le32(&data);
00849     if (num_vectors > 256) {
00850         av_log(ctx->avctx, AV_LOG_ERROR,
00851                "Read invalid number of motion vectors %d\n", num_vectors);
00852         return AVERROR_INVALIDDATA;
00853     }
00854     if (num_vectors * 2 >= data_size)
00855         return AVERROR_INVALIDDATA;
00856 
00857     ctx->num_vectors = num_vectors;
00858     ctx->mc_vectors  = num_vectors ? data : 0;
00859 
00860     /* init the bitreader */
00861     init_get_bits(&ctx->gb, &data[num_vectors * 2], (data_size - num_vectors * 2) << 3);
00862     ctx->skip_bits   = 0;
00863     ctx->need_resync = 0;
00864 
00865     ctx->last_byte = data + data_size - 1;
00866 
00867     /* initialize the 1st cell and set its dimensions to whole plane */
00868     curr_cell.xpos   = curr_cell.ypos = 0;
00869     curr_cell.width  = plane->width  >> 2;
00870     curr_cell.height = plane->height >> 2;
00871     curr_cell.tree   = 0; // we are in the MC tree now
00872     curr_cell.mv_ptr = 0; // no motion vector = INTRA cell
00873 
00874     return parse_bintree(ctx, avctx, plane, INTRA_NULL, &curr_cell, CELL_STACK_MAX, strip_width);
00875 }
00876 
00877 
00878 #define OS_HDR_ID   MKBETAG('F', 'R', 'M', 'H')
00879 
00880 static int decode_frame_headers(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
00881                                 const uint8_t *buf, int buf_size)
00882 {
00883     GetByteContext gb;
00884     const uint8_t   *bs_hdr;
00885     uint32_t        frame_num, word2, check_sum, data_size;
00886     uint32_t        y_offset, u_offset, v_offset, starts[3], ends[3];
00887     uint16_t        height, width;
00888     int             i, j;
00889 
00890     bytestream2_init(&gb, buf, buf_size);
00891 
00892     /* parse and check the OS header */
00893     frame_num = bytestream2_get_le32(&gb);
00894     word2     = bytestream2_get_le32(&gb);
00895     check_sum = bytestream2_get_le32(&gb);
00896     data_size = bytestream2_get_le32(&gb);
00897 
00898     if ((frame_num ^ word2 ^ data_size ^ OS_HDR_ID) != check_sum) {
00899         av_log(avctx, AV_LOG_ERROR, "OS header checksum mismatch!\n");
00900         return AVERROR_INVALIDDATA;
00901     }
00902 
00903     /* parse the bitstream header */
00904     bs_hdr = gb.buffer;
00905 
00906     if (bytestream2_get_le16(&gb) != 32) {
00907         av_log(avctx, AV_LOG_ERROR, "Unsupported codec version!\n");
00908         return AVERROR_INVALIDDATA;
00909     }
00910 
00911     ctx->frame_num   =  frame_num;
00912     ctx->frame_flags =  bytestream2_get_le16(&gb);
00913     ctx->data_size   = (bytestream2_get_le32(&gb) + 7) >> 3;
00914     ctx->cb_offset   =  bytestream2_get_byte(&gb);
00915 
00916     if (ctx->data_size == 16)
00917         return 4;
00918     ctx->data_size = FFMIN(ctx->data_size, buf_size - 16);
00919 
00920     bytestream2_skip(&gb, 3); // skip reserved byte and checksum
00921 
00922     /* check frame dimensions */
00923     height = bytestream2_get_le16(&gb);
00924     width  = bytestream2_get_le16(&gb);
00925     if (av_image_check_size(width, height, 0, avctx))
00926         return AVERROR_INVALIDDATA;
00927 
00928     if (width != ctx->width || height != ctx->height) {
00929         int res;
00930 
00931         av_dlog(avctx, "Frame dimensions changed!\n");
00932 
00933         if (width  < 16 || width  > 640 ||
00934             height < 16 || height > 480 ||
00935             width  &  3 || height &   3) {
00936             av_log(avctx, AV_LOG_ERROR,
00937                    "Invalid picture dimensions: %d x %d!\n", width, height);
00938             return AVERROR_INVALIDDATA;
00939         }
00940 
00941         ctx->width  = width;
00942         ctx->height = height;
00943 
00944         free_frame_buffers(ctx);
00945         if ((res = allocate_frame_buffers(ctx, avctx)) < 0)
00946              return res;
00947         avcodec_set_dimensions(avctx, width, height);
00948     }
00949 
00950     y_offset = bytestream2_get_le32(&gb);
00951     v_offset = bytestream2_get_le32(&gb);
00952     u_offset = bytestream2_get_le32(&gb);
00953     bytestream2_skip(&gb, 4);
00954 
00955     /* unfortunately there is no common order of planes in the buffer */
00956     /* so we use that sorting algo for determining planes data sizes  */
00957     starts[0] = y_offset;
00958     starts[1] = v_offset;
00959     starts[2] = u_offset;
00960 
00961     for (j = 0; j < 3; j++) {
00962         ends[j] = ctx->data_size;
00963         for (i = 2; i >= 0; i--)
00964             if (starts[i] < ends[j] && starts[i] > starts[j])
00965                 ends[j] = starts[i];
00966     }
00967 
00968     ctx->y_data_size = ends[0] - starts[0];
00969     ctx->v_data_size = ends[1] - starts[1];
00970     ctx->u_data_size = ends[2] - starts[2];
00971     if (FFMAX3(y_offset, v_offset, u_offset) >= ctx->data_size - 16 ||
00972         FFMIN3(y_offset, v_offset, u_offset) < gb.buffer - bs_hdr + 16 ||
00973         FFMIN3(ctx->y_data_size, ctx->v_data_size, ctx->u_data_size) <= 0) {
00974         av_log(avctx, AV_LOG_ERROR, "One of the y/u/v offsets is invalid\n");
00975         return AVERROR_INVALIDDATA;
00976     }
00977 
00978     ctx->y_data_ptr = bs_hdr + y_offset;
00979     ctx->v_data_ptr = bs_hdr + v_offset;
00980     ctx->u_data_ptr = bs_hdr + u_offset;
00981     ctx->alt_quant  = gb.buffer;
00982 
00983     if (ctx->data_size == 16) {
00984         av_log(avctx, AV_LOG_DEBUG, "Sync frame encountered!\n");
00985         return 16;
00986     }
00987 
00988     if (ctx->frame_flags & BS_8BIT_PEL) {
00989         av_log_ask_for_sample(avctx, "8-bit pixel format\n");
00990         return AVERROR_PATCHWELCOME;
00991     }
00992 
00993     if (ctx->frame_flags & BS_MV_X_HALF || ctx->frame_flags & BS_MV_Y_HALF) {
00994         av_log_ask_for_sample(avctx, "halfpel motion vectors\n");
00995         return AVERROR_PATCHWELCOME;
00996     }
00997 
00998     return 0;
00999 }
01000 
01001 
01011 static void output_plane(const Plane *plane, int buf_sel, uint8_t *dst, int dst_pitch)
01012 {
01013     int             x,y;
01014     const uint8_t   *src  = plane->pixels[buf_sel];
01015     uint32_t        pitch = plane->pitch;
01016 
01017     for (y = 0; y < plane->height; y++) {
01018         /* convert four pixels at once using SWAR */
01019         for (x = 0; x < plane->width >> 2; x++) {
01020             AV_WN32A(dst, (AV_RN32A(src) & 0x7F7F7F7F) << 1);
01021             src += 4;
01022             dst += 4;
01023         }
01024 
01025         for (x <<= 2; x < plane->width; x++)
01026             *dst++ = *src++ << 1;
01027 
01028         src += pitch     - plane->width;
01029         dst += dst_pitch - plane->width;
01030     }
01031 }
01032 
01033 
01034 static av_cold int decode_init(AVCodecContext *avctx)
01035 {
01036     Indeo3DecodeContext *ctx = avctx->priv_data;
01037 
01038     ctx->avctx     = avctx;
01039     ctx->width     = avctx->width;
01040     ctx->height    = avctx->height;
01041     avctx->pix_fmt = PIX_FMT_YUV410P;
01042 
01043     build_requant_tab();
01044 
01045     dsputil_init(&ctx->dsp, avctx);
01046 
01047     allocate_frame_buffers(ctx, avctx);
01048 
01049     return 0;
01050 }
01051 
01052 
01053 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
01054                         AVPacket *avpkt)
01055 {
01056     Indeo3DecodeContext *ctx = avctx->priv_data;
01057     const uint8_t *buf = avpkt->data;
01058     int buf_size       = avpkt->size;
01059     int res;
01060 
01061     res = decode_frame_headers(ctx, avctx, buf, buf_size);
01062     if (res < 0)
01063         return res;
01064 
01065     /* skip sync(null) frames */
01066     if (res) {
01067         // we have processed 16 bytes but no data was decoded
01068         *data_size = 0;
01069         return buf_size;
01070     }
01071 
01072     /* skip droppable INTER frames if requested */
01073     if (ctx->frame_flags & BS_NONREF &&
01074        (avctx->skip_frame >= AVDISCARD_NONREF))
01075         return 0;
01076 
01077     /* skip INTER frames if requested */
01078     if (!(ctx->frame_flags & BS_KEYFRAME) && avctx->skip_frame >= AVDISCARD_NONKEY)
01079         return 0;
01080 
01081     /* use BS_BUFFER flag for buffer switching */
01082     ctx->buf_sel = (ctx->frame_flags >> BS_BUFFER) & 1;
01083 
01084     /* decode luma plane */
01085     if ((res = decode_plane(ctx, avctx, ctx->planes, ctx->y_data_ptr, ctx->y_data_size, 40)))
01086         return res;
01087 
01088     /* decode chroma planes */
01089     if ((res = decode_plane(ctx, avctx, &ctx->planes[1], ctx->u_data_ptr, ctx->u_data_size, 10)))
01090         return res;
01091 
01092     if ((res = decode_plane(ctx, avctx, &ctx->planes[2], ctx->v_data_ptr, ctx->v_data_size, 10)))
01093         return res;
01094 
01095     if (ctx->frame.data[0])
01096         avctx->release_buffer(avctx, &ctx->frame);
01097 
01098     ctx->frame.reference = 0;
01099     if ((res = ff_get_buffer(avctx, &ctx->frame)) < 0) {
01100         av_log(ctx->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
01101         return res;
01102     }
01103 
01104     output_plane(&ctx->planes[0], ctx->buf_sel, ctx->frame.data[0], ctx->frame.linesize[0]);
01105     output_plane(&ctx->planes[1], ctx->buf_sel, ctx->frame.data[1], ctx->frame.linesize[1]);
01106     output_plane(&ctx->planes[2], ctx->buf_sel, ctx->frame.data[2], ctx->frame.linesize[2]);
01107 
01108     *data_size      = sizeof(AVFrame);
01109     *(AVFrame*)data = ctx->frame;
01110 
01111     return buf_size;
01112 }
01113 
01114 
01115 static av_cold int decode_close(AVCodecContext *avctx)
01116 {
01117     Indeo3DecodeContext *ctx = avctx->priv_data;
01118 
01119     free_frame_buffers(avctx->priv_data);
01120 
01121     if (ctx->frame.data[0])
01122         avctx->release_buffer(avctx, &ctx->frame);
01123 
01124     return 0;
01125 }
01126 
01127 AVCodec ff_indeo3_decoder = {
01128     .name           = "indeo3",
01129     .type           = AVMEDIA_TYPE_VIDEO,
01130     .id             = CODEC_ID_INDEO3,
01131     .priv_data_size = sizeof(Indeo3DecodeContext),
01132     .init           = decode_init,
01133     .close          = decode_close,
01134     .decode         = decode_frame,
01135     .long_name      = NULL_IF_CONFIG_SMALL("Intel Indeo 3"),
01136 };