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