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