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 "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         memset(ctx->planes[p].pixels[0], 0, ctx->planes[p].pitch * ctx->planes[p].height);
00198         memset(ctx->planes[p].pixels[1], 0, ctx->planes[p].pitch * ctx->planes[p].height);
00199     }
00200 
00201     return 0;
00202 }
00203 
00204 
00205 static av_cold void free_frame_buffers(Indeo3DecodeContext *ctx)
00206 {
00207     int p;
00208 
00209     for (p = 0; p < 3; p++) {
00210         av_freep(&ctx->planes[p].buffers[0]);
00211         av_freep(&ctx->planes[p].buffers[1]);
00212         ctx->planes[p].pixels[0] = ctx->planes[p].pixels[1] = 0;
00213     }
00214 }
00215 
00216 
00225 static void copy_cell(Indeo3DecodeContext *ctx, Plane *plane, Cell *cell)
00226 {
00227     int     h, w, mv_x, mv_y, offset, offset_dst;
00228     uint8_t *src, *dst;
00229 
00230     /* setup output and reference pointers */
00231     offset_dst  = (cell->ypos << 2) * plane->pitch + (cell->xpos << 2);
00232     dst         = plane->pixels[ctx->buf_sel] + offset_dst;
00233     mv_y        = cell->mv_ptr[0];
00234     mv_x        = cell->mv_ptr[1];
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    ,\
00351              (AV_RN16A(ref    ) + delta_tab->deltas[dyad1]) & 0x7F7F);\
00352     AV_WN16A(dst + line_offset + 2,\
00353              (AV_RN16A(ref + 2) + delta_tab->deltas[dyad2]) & 0x7F7F);\
00354     if (mode >= 3) {\
00355         if (is_top_of_cell && !cell->ypos) {\
00356             AV_COPY32(dst, dst + row_offset);\
00357         } else {\
00358             AVG_32(dst, ref, dst + row_offset);\
00359         }\
00360     }
00361 
00362 #define APPLY_DELTA_8 \
00363     /* apply two 32-bit VQ deltas to next even line */\
00364     if (is_top_of_cell) { \
00365         AV_WN32A(dst + row_offset    , \
00366                  (replicate32(AV_RN32A(ref    )) + delta_tab->deltas_m10[dyad1]) & 0x7F7F7F7F);\
00367         AV_WN32A(dst + row_offset + 4, \
00368                  (replicate32(AV_RN32A(ref + 4)) + delta_tab->deltas_m10[dyad2]) & 0x7F7F7F7F);\
00369     } else { \
00370         AV_WN32A(dst + row_offset    , \
00371                  (AV_RN32A(ref    ) + delta_tab->deltas_m10[dyad1]) & 0x7F7F7F7F);\
00372         AV_WN32A(dst + row_offset + 4, \
00373                  (AV_RN32A(ref + 4) + delta_tab->deltas_m10[dyad2]) & 0x7F7F7F7F);\
00374     } \
00375     /* odd lines are not coded but rather interpolated/replicated */\
00376     /* first line of the cell on the top of image? - replicate */\
00377     /* otherwise - interpolate */\
00378     if (is_top_of_cell && !cell->ypos) {\
00379         AV_COPY64(dst, dst + row_offset);\
00380     } else \
00381         AVG_64(dst, ref, dst + row_offset);
00382 
00383 
00384 #define APPLY_DELTA_1011_INTER \
00385     if (mode == 10) { \
00386         AV_WN32A(dst                 , \
00387                  (AV_RN32A(dst                 ) + delta_tab->deltas_m10[dyad1]) & 0x7F7F7F7F);\
00388         AV_WN32A(dst + 4             , \
00389                  (AV_RN32A(dst + 4             ) + delta_tab->deltas_m10[dyad2]) & 0x7F7F7F7F);\
00390         AV_WN32A(dst + row_offset    , \
00391                  (AV_RN32A(dst + row_offset    ) + delta_tab->deltas_m10[dyad1]) & 0x7F7F7F7F);\
00392         AV_WN32A(dst + row_offset + 4, \
00393                  (AV_RN32A(dst + row_offset + 4) + delta_tab->deltas_m10[dyad2]) & 0x7F7F7F7F);\
00394     } else { \
00395         AV_WN16A(dst                 , \
00396                  (AV_RN16A(dst                 ) + delta_tab->deltas[dyad1]) & 0x7F7F);\
00397         AV_WN16A(dst + 2             , \
00398                  (AV_RN16A(dst + 2             ) + delta_tab->deltas[dyad2]) & 0x7F7F);\
00399         AV_WN16A(dst + row_offset    , \
00400                  (AV_RN16A(dst + row_offset    ) + delta_tab->deltas[dyad1]) & 0x7F7F);\
00401         AV_WN16A(dst + row_offset + 2, \
00402                  (AV_RN16A(dst + row_offset + 2) + delta_tab->deltas[dyad2]) & 0x7F7F);\
00403     }
00404 
00405 
00406 static int decode_cell_data(Cell *cell, uint8_t *block, uint8_t *ref_block,
00407                             int pitch, int h_zoom, int v_zoom, int mode,
00408                             const vqEntry *delta[2], int swap_quads[2],
00409                             const uint8_t **data_ptr, const uint8_t *last_ptr)
00410 {
00411     int           x, y, line, num_lines;
00412     int           rle_blocks = 0;
00413     uint8_t       code, *dst, *ref;
00414     const vqEntry *delta_tab;
00415     unsigned int  dyad1, dyad2;
00416     uint64_t      pix64;
00417     int           skip_flag = 0, is_top_of_cell, is_first_row = 1;
00418     int           row_offset, blk_row_offset, line_offset;
00419 
00420     row_offset     =  pitch;
00421     blk_row_offset = (row_offset << (2 + v_zoom)) - (cell->width << 2);
00422     line_offset    = v_zoom ? row_offset : 0;
00423 
00424     if (cell->height & v_zoom || cell->width & h_zoom)
00425         return IV3_BAD_DATA;
00426 
00427     for (y = 0; y < cell->height; is_first_row = 0, y += 1 + v_zoom) {
00428         for (x = 0; x < cell->width; x += 1 + h_zoom) {
00429             ref = ref_block;
00430             dst = block;
00431 
00432             if (rle_blocks > 0) {
00433                 if (mode <= 4) {
00434                     RLE_BLOCK_COPY;
00435                 } else if (mode == 10 && !cell->mv_ptr) {
00436                     RLE_BLOCK_COPY_8;
00437                 }
00438                 rle_blocks--;
00439             } else {
00440                 for (line = 0; line < 4;) {
00441                     num_lines = 1;
00442                     is_top_of_cell = is_first_row && !line;
00443 
00444                     /* select primary VQ table for odd, secondary for even lines */
00445                     if (mode <= 4)
00446                         delta_tab = delta[line & 1];
00447                     else
00448                         delta_tab = delta[1];
00449                     BUFFER_PRECHECK;
00450                     code = bytestream_get_byte(data_ptr);
00451                     if (code < 248) {
00452                         if (code < delta_tab->num_dyads) {
00453                             BUFFER_PRECHECK;
00454                             dyad1 = bytestream_get_byte(data_ptr);
00455                             dyad2 = code;
00456                             if (dyad1 >= delta_tab->num_dyads || dyad1 >= 248)
00457                                 return IV3_BAD_DATA;
00458                         } else {
00459                             /* process QUADS */
00460                             code -= delta_tab->num_dyads;
00461                             dyad1 = code / delta_tab->quad_exp;
00462                             dyad2 = code % delta_tab->quad_exp;
00463                             if (swap_quads[line & 1])
00464                                 FFSWAP(unsigned int, dyad1, dyad2);
00465                         }
00466                         if (mode <= 4) {
00467                             APPLY_DELTA_4;
00468                         } else if (mode == 10 && !cell->mv_ptr) {
00469                             APPLY_DELTA_8;
00470                         } else {
00471                             APPLY_DELTA_1011_INTER;
00472                         }
00473                     } else {
00474                         /* process RLE codes */
00475                         switch (code) {
00476                         case RLE_ESC_FC:
00477                             skip_flag  = 0;
00478                             rle_blocks = 1;
00479                             code       = 253;
00480                             /* FALLTHROUGH */
00481                         case RLE_ESC_FF:
00482                         case RLE_ESC_FE:
00483                         case RLE_ESC_FD:
00484                             num_lines = 257 - code - line;
00485                             if (num_lines <= 0)
00486                                 return IV3_BAD_RLE;
00487                             if (mode <= 4) {
00488                                 RLE_LINES_COPY;
00489                             } else if (mode == 10 && !cell->mv_ptr) {
00490                                 RLE_LINES_COPY_M10;
00491                             }
00492                             break;
00493                         case RLE_ESC_FB:
00494                             BUFFER_PRECHECK;
00495                             code = bytestream_get_byte(data_ptr);
00496                             rle_blocks = (code & 0x1F) - 1; /* set block counter */
00497                             if (code >= 64 || rle_blocks < 0)
00498                                 return IV3_BAD_COUNTER;
00499                             skip_flag = code & 0x20;
00500                             num_lines = 4 - line; /* enforce next block processing */
00501                             if (mode >= 10 || (cell->mv_ptr || !skip_flag)) {
00502                                 if (mode <= 4) {
00503                                     RLE_LINES_COPY;
00504                                 } else if (mode == 10 && !cell->mv_ptr) {
00505                                     RLE_LINES_COPY_M10;
00506                                 }
00507                             }
00508                             break;
00509                         case RLE_ESC_F9:
00510                             skip_flag  = 1;
00511                             rle_blocks = 1;
00512                             /* FALLTHROUGH */
00513                         case RLE_ESC_FA:
00514                             if (line)
00515                                 return IV3_BAD_RLE;
00516                             num_lines = 4; /* enforce next block processing */
00517                             if (cell->mv_ptr) {
00518                                 if (mode <= 4) {
00519                                     RLE_LINES_COPY;
00520                                 } else if (mode == 10 && !cell->mv_ptr) {
00521                                     RLE_LINES_COPY_M10;
00522                                 }
00523                             }
00524                             break;
00525                         default:
00526                             return IV3_UNSUPPORTED;
00527                         }
00528                     }
00529 
00530                     line += num_lines;
00531                     ref  += row_offset * (num_lines << v_zoom);
00532                     dst  += row_offset * (num_lines << v_zoom);
00533                 }
00534             }
00535 
00536             /* move to next horizontal block */
00537             block     += 4 << h_zoom;
00538             ref_block += 4 << h_zoom;
00539         }
00540 
00541         /* move to next line of blocks */
00542         ref_block += blk_row_offset;
00543         block     += blk_row_offset;
00544     }
00545     return IV3_NOERR;
00546 }
00547 
00548 
00562 static int decode_cell(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
00563                        Plane *plane, Cell *cell, const uint8_t *data_ptr,
00564                        const uint8_t *last_ptr)
00565 {
00566     int           x, mv_x, mv_y, mode, vq_index, prim_indx, second_indx;
00567     int           zoom_fac;
00568     int           offset, error = 0, swap_quads[2];
00569     uint8_t       code, *block, *ref_block = 0;
00570     const vqEntry *delta[2];
00571     const uint8_t *data_start = data_ptr;
00572 
00573     /* get coding mode and VQ table index from the VQ descriptor byte */
00574     code     = *data_ptr++;
00575     mode     = code >> 4;
00576     vq_index = code & 0xF;
00577 
00578     /* setup output and reference pointers */
00579     offset = (cell->ypos << 2) * plane->pitch + (cell->xpos << 2);
00580     block  =  plane->pixels[ctx->buf_sel] + offset;
00581     if (!cell->mv_ptr) {
00582         /* use previous line as reference for INTRA cells */
00583         ref_block = block - plane->pitch;
00584     } else if (mode >= 10) {
00585         /* for mode 10 and 11 INTER first copy the predicted cell into the current one */
00586         /* so we don't need to do data copying for each RLE code later */
00587         copy_cell(ctx, plane, cell);
00588     } else {
00589         /* set the pointer to the reference pixels for modes 0-4 INTER */
00590         mv_y      = cell->mv_ptr[0];
00591         mv_x      = cell->mv_ptr[1];
00592         offset   += mv_y * plane->pitch + mv_x;
00593         ref_block = plane->pixels[ctx->buf_sel ^ 1] + offset;
00594     }
00595 
00596     /* select VQ tables as follows: */
00597     /* modes 0 and 3 use only the primary table for all lines in a block */
00598     /* while modes 1 and 4 switch between primary and secondary tables on alternate lines */
00599     if (mode == 1 || mode == 4) {
00600         code        = ctx->alt_quant[vq_index];
00601         prim_indx   = (code >> 4)  + ctx->cb_offset;
00602         second_indx = (code & 0xF) + ctx->cb_offset;
00603     } else {
00604         vq_index += ctx->cb_offset;
00605         prim_indx = second_indx = vq_index;
00606     }
00607 
00608     if (prim_indx >= 24 || second_indx >= 24) {
00609         av_log(avctx, AV_LOG_ERROR, "Invalid VQ table indexes! Primary: %d, secondary: %d!\n",
00610                prim_indx, second_indx);
00611         return AVERROR_INVALIDDATA;
00612     }
00613 
00614     delta[0] = &vq_tab[second_indx];
00615     delta[1] = &vq_tab[prim_indx];
00616     swap_quads[0] = second_indx >= 16;
00617     swap_quads[1] = prim_indx   >= 16;
00618 
00619     /* requantize the prediction if VQ index of this cell differs from VQ index */
00620     /* of the predicted cell in order to avoid overflows. */
00621     if (vq_index >= 8 && ref_block) {
00622         for (x = 0; x < cell->width << 2; x++)
00623             ref_block[x] = requant_tab[vq_index & 7][ref_block[x]];
00624     }
00625 
00626     error = IV3_NOERR;
00627 
00628     switch (mode) {
00629     case 0: /*------------------ MODES 0 & 1 (4x4 block processing) --------------------*/
00630     case 1:
00631     case 3: /*------------------ MODES 3 & 4 (4x8 block processing) --------------------*/
00632     case 4:
00633         if (mode >= 3 && cell->mv_ptr) {
00634             av_log(avctx, AV_LOG_ERROR, "Attempt to apply Mode 3/4 to an INTER cell!\n");
00635             return AVERROR_INVALIDDATA;
00636         }
00637 
00638         zoom_fac = mode >= 3;
00639         error = decode_cell_data(cell, block, ref_block, plane->pitch, 0, zoom_fac,
00640                                  mode, delta, swap_quads, &data_ptr, last_ptr);
00641         break;
00642     case 10: /*-------------------- MODE 10 (8x8 block processing) ---------------------*/
00643     case 11: /*----------------- MODE 11 (4x8 INTER block processing) ------------------*/
00644         if (mode == 10 && !cell->mv_ptr) { /* MODE 10 INTRA processing */
00645             error = decode_cell_data(cell, block, ref_block, plane->pitch, 1, 1,
00646                                      mode, delta, swap_quads, &data_ptr, last_ptr);
00647         } else { /* mode 10 and 11 INTER processing */
00648             if (mode == 11 && !cell->mv_ptr) {
00649                av_log(avctx, AV_LOG_ERROR, "Attempt to use Mode 11 for an INTRA cell!\n");
00650                return AVERROR_INVALIDDATA;
00651             }
00652 
00653             zoom_fac = mode == 10;
00654             error = decode_cell_data(cell, block, ref_block, plane->pitch,
00655                                      zoom_fac, 1, mode, delta, swap_quads,
00656                                      &data_ptr, last_ptr);
00657         }
00658         break;
00659     default:
00660         av_log(avctx, AV_LOG_ERROR, "Unsupported coding mode: %d\n", mode);
00661         return AVERROR_INVALIDDATA;
00662     }//switch mode
00663 
00664     switch (error) {
00665     case IV3_BAD_RLE:
00666         av_log(avctx, AV_LOG_ERROR, "Mode %d: RLE code %X is not allowed at the current line\n",
00667                mode, data_ptr[-1]);
00668         return AVERROR_INVALIDDATA;
00669     case IV3_BAD_DATA:
00670         av_log(avctx, AV_LOG_ERROR, "Mode %d: invalid VQ data\n", mode);
00671         return AVERROR_INVALIDDATA;
00672     case IV3_BAD_COUNTER:
00673         av_log(avctx, AV_LOG_ERROR, "Mode %d: RLE-FB invalid counter: %d\n", mode, code);
00674         return AVERROR_INVALIDDATA;
00675     case IV3_UNSUPPORTED:
00676         av_log(avctx, AV_LOG_ERROR, "Mode %d: unsupported RLE code: %X\n", mode, data_ptr[-1]);
00677         return AVERROR_INVALIDDATA;
00678     case IV3_OUT_OF_DATA:
00679         av_log(avctx, AV_LOG_ERROR, "Mode %d: attempt to read past end of buffer\n", mode);
00680         return AVERROR_INVALIDDATA;
00681     }
00682 
00683     return data_ptr - data_start; /* report number of bytes consumed from the input buffer */
00684 }
00685 
00686 
00687 /* Binary tree codes. */
00688 enum {
00689     H_SPLIT    = 0,
00690     V_SPLIT    = 1,
00691     INTRA_NULL = 2,
00692     INTER_DATA = 3
00693 };
00694 
00695 
00696 #define SPLIT_CELL(size, new_size) (new_size) = ((size) > 2) ? ((((size) + 2) >> 2) << 1) : 1
00697 
00698 #define UPDATE_BITPOS(n) \
00699     ctx->skip_bits  += (n); \
00700     ctx->need_resync = 1
00701 
00702 #define RESYNC_BITSTREAM \
00703     if (ctx->need_resync && !(get_bits_count(&ctx->gb) & 7)) { \
00704         skip_bits_long(&ctx->gb, ctx->skip_bits);              \
00705         ctx->skip_bits   = 0;                                  \
00706         ctx->need_resync = 0;                                  \
00707     }
00708 
00709 #define CHECK_CELL \
00710     if (curr_cell.xpos + curr_cell.width > (plane->width >> 2) ||               \
00711         curr_cell.ypos + curr_cell.height > (plane->height >> 2)) {             \
00712         av_log(avctx, AV_LOG_ERROR, "Invalid cell: x=%d, y=%d, w=%d, h=%d\n",   \
00713                curr_cell.xpos, curr_cell.ypos, curr_cell.width, curr_cell.height); \
00714         return AVERROR_INVALIDDATA;                                                              \
00715     }
00716 
00717 
00718 static int parse_bintree(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
00719                          Plane *plane, int code, Cell *ref_cell,
00720                          const int depth, const int strip_width)
00721 {
00722     Cell    curr_cell;
00723     int     bytes_used;
00724 
00725     if (depth <= 0) {
00726         av_log(avctx, AV_LOG_ERROR, "Stack overflow (corrupted binary tree)!\n");
00727         return AVERROR_INVALIDDATA; // unwind recursion
00728     }
00729 
00730     curr_cell = *ref_cell; // clone parent cell
00731     if (code == H_SPLIT) {
00732         SPLIT_CELL(ref_cell->height, curr_cell.height);
00733         ref_cell->ypos   += curr_cell.height;
00734         ref_cell->height -= curr_cell.height;
00735         if (ref_cell->height <= 0 || curr_cell.height <= 0)
00736             return AVERROR_INVALIDDATA;
00737     } else if (code == V_SPLIT) {
00738         if (curr_cell.width > strip_width) {
00739             /* split strip */
00740             curr_cell.width = (curr_cell.width <= (strip_width << 1) ? 1 : 2) * strip_width;
00741         } else
00742             SPLIT_CELL(ref_cell->width, curr_cell.width);
00743         ref_cell->xpos  += curr_cell.width;
00744         ref_cell->width -= curr_cell.width;
00745         if (ref_cell->width <= 0 || curr_cell.width <= 0)
00746             return AVERROR_INVALIDDATA;
00747     }
00748 
00749     while (1) { /* loop until return */
00750         RESYNC_BITSTREAM;
00751         switch (code = get_bits(&ctx->gb, 2)) {
00752         case H_SPLIT:
00753         case V_SPLIT:
00754             if (parse_bintree(ctx, avctx, plane, code, &curr_cell, depth - 1, strip_width))
00755                 return AVERROR_INVALIDDATA;
00756             break;
00757         case INTRA_NULL:
00758             if (!curr_cell.tree) { /* MC tree INTRA code */
00759                 curr_cell.mv_ptr = 0; /* mark the current strip as INTRA */
00760                 curr_cell.tree   = 1; /* enter the VQ tree */
00761             } else { /* VQ tree NULL code */
00762                 RESYNC_BITSTREAM;
00763                 code = get_bits(&ctx->gb, 2);
00764                 if (code >= 2) {
00765                     av_log(avctx, AV_LOG_ERROR, "Invalid VQ_NULL code: %d\n", code);
00766                     return AVERROR_INVALIDDATA;
00767                 }
00768                 if (code == 1)
00769                     av_log(avctx, AV_LOG_ERROR, "SkipCell procedure not implemented yet!\n");
00770 
00771                 CHECK_CELL
00772                 if (!curr_cell.mv_ptr)
00773                     return AVERROR_INVALIDDATA;
00774                 copy_cell(ctx, plane, &curr_cell);
00775                 return 0;
00776             }
00777             break;
00778         case INTER_DATA:
00779             if (!curr_cell.tree) { /* MC tree INTER code */
00780                 unsigned mv_idx;
00781                 /* get motion vector index and setup the pointer to the mv set */
00782                 if (!ctx->need_resync)
00783                     ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];
00784                 mv_idx = *(ctx->next_cell_data++) << 1;
00785                 if (mv_idx >= ctx->num_vectors) {
00786                     av_log(avctx, AV_LOG_ERROR, "motion vector index out of range\n");
00787                     return AVERROR_INVALIDDATA;
00788                 }
00789                 curr_cell.mv_ptr = &ctx->mc_vectors[mv_idx];
00790                 curr_cell.tree   = 1; /* enter the VQ tree */
00791                 UPDATE_BITPOS(8);
00792             } else { /* VQ tree DATA code */
00793                 if (!ctx->need_resync)
00794                     ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];
00795 
00796                 CHECK_CELL
00797                 bytes_used = decode_cell(ctx, avctx, plane, &curr_cell,
00798                                          ctx->next_cell_data, ctx->last_byte);
00799                 if (bytes_used < 0)
00800                     return AVERROR_INVALIDDATA;
00801 
00802                 UPDATE_BITPOS(bytes_used << 3);
00803                 ctx->next_cell_data += bytes_used;
00804                 return 0;
00805             }
00806             break;
00807         }
00808     }//while
00809 
00810     return 0;
00811 }
00812 
00813 
00814 static int decode_plane(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
00815                         Plane *plane, const uint8_t *data, int32_t data_size,
00816                         int32_t strip_width)
00817 {
00818     Cell            curr_cell;
00819     unsigned        num_vectors;
00820 
00821     /* each plane data starts with mc_vector_count field, */
00822     /* an optional array of motion vectors followed by the vq data */
00823     num_vectors = bytestream_get_le32(&data);
00824     if (num_vectors > 256) {
00825         av_log(ctx->avctx, AV_LOG_ERROR,
00826                "Read invalid number of motion vectors %d\n", num_vectors);
00827         return AVERROR_INVALIDDATA;
00828     }
00829     if (num_vectors * 2 >= data_size)
00830         return AVERROR_INVALIDDATA;
00831 
00832     ctx->num_vectors = num_vectors;
00833     ctx->mc_vectors  = num_vectors ? data : 0;
00834 
00835     /* init the bitreader */
00836     init_get_bits(&ctx->gb, &data[num_vectors * 2], (data_size - num_vectors * 2) << 3);
00837     ctx->skip_bits   = 0;
00838     ctx->need_resync = 0;
00839 
00840     ctx->last_byte = data + data_size - 1;
00841 
00842     /* initialize the 1st cell and set its dimensions to whole plane */
00843     curr_cell.xpos   = curr_cell.ypos = 0;
00844     curr_cell.width  = plane->width  >> 2;
00845     curr_cell.height = plane->height >> 2;
00846     curr_cell.tree   = 0; // we are in the MC tree now
00847     curr_cell.mv_ptr = 0; // no motion vector = INTRA cell
00848 
00849     return parse_bintree(ctx, avctx, plane, INTRA_NULL, &curr_cell, CELL_STACK_MAX, strip_width);
00850 }
00851 
00852 
00853 #define OS_HDR_ID   MKBETAG('F', 'R', 'M', 'H')
00854 
00855 static int decode_frame_headers(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
00856                                 const uint8_t *buf, int buf_size)
00857 {
00858     const uint8_t   *buf_ptr = buf, *bs_hdr;
00859     uint32_t        frame_num, word2, check_sum, data_size;
00860     uint32_t        y_offset, u_offset, v_offset, starts[3], ends[3];
00861     uint16_t        height, width;
00862     int             i, j;
00863 
00864     /* parse and check the OS header */
00865     frame_num = bytestream_get_le32(&buf_ptr);
00866     word2     = bytestream_get_le32(&buf_ptr);
00867     check_sum = bytestream_get_le32(&buf_ptr);
00868     data_size = bytestream_get_le32(&buf_ptr);
00869 
00870     if ((frame_num ^ word2 ^ data_size ^ OS_HDR_ID) != check_sum) {
00871         av_log(avctx, AV_LOG_ERROR, "OS header checksum mismatch!\n");
00872         return AVERROR_INVALIDDATA;
00873     }
00874 
00875     /* parse the bitstream header */
00876     bs_hdr = buf_ptr;
00877 
00878     if (bytestream_get_le16(&buf_ptr) != 32) {
00879         av_log(avctx, AV_LOG_ERROR, "Unsupported codec version!\n");
00880         return AVERROR_INVALIDDATA;
00881     }
00882 
00883     ctx->frame_num   =  frame_num;
00884     ctx->frame_flags =  bytestream_get_le16(&buf_ptr);
00885     ctx->data_size   = (bytestream_get_le32(&buf_ptr) + 7) >> 3;
00886     ctx->cb_offset   = *buf_ptr++;
00887 
00888     if (ctx->data_size == 16)
00889         return 4;
00890     if (ctx->data_size > buf_size)
00891         ctx->data_size = buf_size;
00892 
00893     buf_ptr += 3; // skip reserved byte and checksum
00894 
00895     /* check frame dimensions */
00896     height = bytestream_get_le16(&buf_ptr);
00897     width  = bytestream_get_le16(&buf_ptr);
00898     if (av_image_check_size(width, height, 0, avctx))
00899         return AVERROR_INVALIDDATA;
00900 
00901     if (width != ctx->width || height != ctx->height) {
00902         int res;
00903 
00904         av_dlog(avctx, "Frame dimensions changed!\n");
00905 
00906         if (width  < 16 || width  > 640 ||
00907             height < 16 || height > 480 ||
00908             width  &  3 || height &   3) {
00909             av_log(avctx, AV_LOG_ERROR,
00910                    "Invalid picture dimensions: %d x %d!\n", width, height);
00911             return AVERROR_INVALIDDATA;
00912         }
00913 
00914         ctx->width  = width;
00915         ctx->height = height;
00916 
00917         free_frame_buffers(ctx);
00918         if ((res = allocate_frame_buffers(ctx, avctx)) < 0)
00919              return res;
00920         avcodec_set_dimensions(avctx, width, height);
00921     }
00922 
00923     y_offset = bytestream_get_le32(&buf_ptr);
00924     v_offset = bytestream_get_le32(&buf_ptr);
00925     u_offset = bytestream_get_le32(&buf_ptr);
00926 
00927     /* unfortunately there is no common order of planes in the buffer */
00928     /* so we use that sorting algo for determining planes data sizes  */
00929     starts[0] = y_offset;
00930     starts[1] = v_offset;
00931     starts[2] = u_offset;
00932 
00933     for (j = 0; j < 3; j++) {
00934         ends[j] = ctx->data_size;
00935         for (i = 2; i >= 0; i--)
00936             if (starts[i] < ends[j] && starts[i] > starts[j])
00937                 ends[j] = starts[i];
00938     }
00939 
00940     ctx->y_data_size = ends[0] - starts[0];
00941     ctx->v_data_size = ends[1] - starts[1];
00942     ctx->u_data_size = ends[2] - starts[2];
00943     if (FFMAX3(y_offset, v_offset, u_offset) >= ctx->data_size - 16 ||
00944         FFMIN3(ctx->y_data_size, ctx->v_data_size, ctx->u_data_size) <= 0) {
00945         av_log(avctx, AV_LOG_ERROR, "One of the y/u/v offsets is invalid\n");
00946         return AVERROR_INVALIDDATA;
00947     }
00948 
00949     ctx->y_data_ptr = bs_hdr + y_offset;
00950     ctx->v_data_ptr = bs_hdr + v_offset;
00951     ctx->u_data_ptr = bs_hdr + u_offset;
00952     ctx->alt_quant  = buf_ptr + sizeof(uint32_t);
00953 
00954     if (ctx->data_size == 16) {
00955         av_log(avctx, AV_LOG_DEBUG, "Sync frame encountered!\n");
00956         return 16;
00957     }
00958 
00959     if (ctx->frame_flags & BS_8BIT_PEL) {
00960         av_log_ask_for_sample(avctx, "8-bit pixel format\n");
00961         return AVERROR_PATCHWELCOME;
00962     }
00963 
00964     if (ctx->frame_flags & BS_MV_X_HALF || ctx->frame_flags & BS_MV_Y_HALF) {
00965         av_log_ask_for_sample(avctx, "halfpel motion vectors\n");
00966         return AVERROR_PATCHWELCOME;
00967     }
00968 
00969     return 0;
00970 }
00971 
00972 
00982 static void output_plane(const Plane *plane, int buf_sel, uint8_t *dst, int dst_pitch)
00983 {
00984     int             x,y;
00985     const uint8_t   *src  = plane->pixels[buf_sel];
00986     uint32_t        pitch = plane->pitch;
00987 
00988     for (y = 0; y < plane->height; y++) {
00989         /* convert four pixels at once using SWAR */
00990         for (x = 0; x < plane->width >> 2; x++) {
00991             AV_WN32A(dst, (AV_RN32A(src) & 0x7F7F7F7F) << 1);
00992             src += 4;
00993             dst += 4;
00994         }
00995 
00996         for (x <<= 2; x < plane->width; x++)
00997             *dst++ = *src++ << 1;
00998 
00999         src += pitch     - plane->width;
01000         dst += dst_pitch - plane->width;
01001     }
01002 }
01003 
01004 
01005 static av_cold int decode_init(AVCodecContext *avctx)
01006 {
01007     Indeo3DecodeContext *ctx = avctx->priv_data;
01008 
01009     ctx->avctx     = avctx;
01010     ctx->width     = avctx->width;
01011     ctx->height    = avctx->height;
01012     avctx->pix_fmt = PIX_FMT_YUV410P;
01013 
01014     build_requant_tab();
01015 
01016     dsputil_init(&ctx->dsp, avctx);
01017 
01018     allocate_frame_buffers(ctx, avctx);
01019 
01020     return 0;
01021 }
01022 
01023 
01024 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
01025                         AVPacket *avpkt)
01026 {
01027     Indeo3DecodeContext *ctx = avctx->priv_data;
01028     const uint8_t *buf = avpkt->data;
01029     int buf_size       = avpkt->size;
01030     int res;
01031 
01032     res = decode_frame_headers(ctx, avctx, buf, buf_size);
01033     if (res < 0)
01034         return res;
01035 
01036     /* skip sync(null) frames */
01037     if (res) {
01038         // we have processed 16 bytes but no data was decoded
01039         *data_size = 0;
01040         return buf_size;
01041     }
01042 
01043     /* skip droppable INTER frames if requested */
01044     if (ctx->frame_flags & BS_NONREF &&
01045        (avctx->skip_frame >= AVDISCARD_NONREF))
01046         return 0;
01047 
01048     /* skip INTER frames if requested */
01049     if (!(ctx->frame_flags & BS_KEYFRAME) && avctx->skip_frame >= AVDISCARD_NONKEY)
01050         return 0;
01051 
01052     /* use BS_BUFFER flag for buffer switching */
01053     ctx->buf_sel = (ctx->frame_flags >> BS_BUFFER) & 1;
01054 
01055     /* decode luma plane */
01056     if ((res = decode_plane(ctx, avctx, ctx->planes, ctx->y_data_ptr, ctx->y_data_size, 40)))
01057         return res;
01058 
01059     /* decode chroma planes */
01060     if ((res = decode_plane(ctx, avctx, &ctx->planes[1], ctx->u_data_ptr, ctx->u_data_size, 10)))
01061         return res;
01062 
01063     if ((res = decode_plane(ctx, avctx, &ctx->planes[2], ctx->v_data_ptr, ctx->v_data_size, 10)))
01064         return res;
01065 
01066     if (ctx->frame.data[0])
01067         avctx->release_buffer(avctx, &ctx->frame);
01068 
01069     ctx->frame.reference = 0;
01070     if ((res = avctx->get_buffer(avctx, &ctx->frame)) < 0) {
01071         av_log(ctx->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
01072         return res;
01073     }
01074 
01075     output_plane(&ctx->planes[0], ctx->buf_sel, ctx->frame.data[0], ctx->frame.linesize[0]);
01076     output_plane(&ctx->planes[1], ctx->buf_sel, ctx->frame.data[1], ctx->frame.linesize[1]);
01077     output_plane(&ctx->planes[2], ctx->buf_sel, ctx->frame.data[2], ctx->frame.linesize[2]);
01078 
01079     *data_size      = sizeof(AVFrame);
01080     *(AVFrame*)data = ctx->frame;
01081 
01082     return buf_size;
01083 }
01084 
01085 
01086 static av_cold int decode_close(AVCodecContext *avctx)
01087 {
01088     Indeo3DecodeContext *ctx = avctx->priv_data;
01089 
01090     free_frame_buffers(avctx->priv_data);
01091 
01092     if (ctx->frame.data[0])
01093         avctx->release_buffer(avctx, &ctx->frame);
01094 
01095     return 0;
01096 }
01097 
01098 AVCodec ff_indeo3_decoder = {
01099     .name           = "indeo3",
01100     .type           = AVMEDIA_TYPE_VIDEO,
01101     .id             = CODEC_ID_INDEO3,
01102     .priv_data_size = sizeof(Indeo3DecodeContext),
01103     .init           = decode_init,
01104     .close          = decode_close,
01105     .decode         = decode_frame,
01106     .long_name      = NULL_IF_CONFIG_SMALL("Intel Indeo 3"),
01107 };