]> git.sesse.net Git - ffmpeg/blob - libavcodec/indeo3.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / indeo3.c
1 /*
2  * Indeo Video v3 compatible decoder
3  * Copyright (c) 2009 - 2011 Maxim Poliakovski
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * This is a decoder for Intel Indeo Video v3.
25  * It is based on vector quantization, run-length coding and motion compensation.
26  * Known container formats: .avi and .mov
27  * Known FOURCCs: 'IV31', 'IV32'
28  *
29  * @see http://wiki.multimedia.cx/index.php?title=Indeo_3
30  */
31
32 #include "libavutil/imgutils.h"
33 #include "libavutil/intreadwrite.h"
34 #include "avcodec.h"
35 #include "dsputil.h"
36 #include "bytestream.h"
37 #include "get_bits.h"
38
39 #include "indeo3data.h"
40
41 /* RLE opcodes. */
42 enum {
43     RLE_ESC_F9    = 249, ///< same as RLE_ESC_FA + do the same with next block
44     RLE_ESC_FA    = 250, ///< INTRA: skip block, INTER: copy data from reference
45     RLE_ESC_FB    = 251, ///< apply null delta to N blocks / skip N blocks
46     RLE_ESC_FC    = 252, ///< same as RLE_ESC_FD + do the same with next block
47     RLE_ESC_FD    = 253, ///< apply null delta to all remaining lines of this block
48     RLE_ESC_FE    = 254, ///< apply null delta to all lines up to the 3rd line
49     RLE_ESC_FF    = 255  ///< apply null delta to all lines up to the 2nd line
50 };
51
52
53 /* Some constants for parsing frame bitstream flags. */
54 #define BS_8BIT_PEL     (1 << 1) ///< 8bit pixel bitdepth indicator
55 #define BS_KEYFRAME     (1 << 2) ///< intra frame indicator
56 #define BS_MV_Y_HALF    (1 << 4) ///< vertical mv halfpel resolution indicator
57 #define BS_MV_X_HALF    (1 << 5) ///< horizontal mv halfpel resolution indicator
58 #define BS_NONREF       (1 << 8) ///< nonref (discardable) frame indicator
59 #define BS_BUFFER        9       ///< indicates which of two frame buffers should be used
60
61
62 typedef struct Plane {
63     uint8_t         *buffers[2];
64     uint8_t         *pixels[2]; ///< pointer to the actual pixel data of the buffers above
65     uint32_t        width;
66     uint32_t        height;
67     uint32_t        pitch;
68 } Plane;
69
70 #define CELL_STACK_MAX  20
71
72 typedef struct Cell {
73     int16_t         xpos;       ///< cell coordinates in 4x4 blocks
74     int16_t         ypos;
75     int16_t         width;      ///< cell width  in 4x4 blocks
76     int16_t         height;     ///< cell height in 4x4 blocks
77     uint8_t         tree;       ///< tree id: 0- MC tree, 1 - VQ tree
78     const int8_t    *mv_ptr;    ///< ptr to the motion vector if any
79 } Cell;
80
81 typedef struct Indeo3DecodeContext {
82     AVCodecContext *avctx;
83     AVFrame         frame;
84     DSPContext      dsp;
85
86     GetBitContext   gb;
87     int             need_resync;
88     int             skip_bits;
89     const uint8_t   *next_cell_data;
90     const uint8_t   *last_byte;
91     const int8_t    *mc_vectors;
92
93     int16_t         width, height;
94     uint32_t        frame_num;      ///< current frame number (zero-based)
95     uint32_t        data_size;      ///< size of the frame data in bytes
96     uint16_t        frame_flags;    ///< frame properties
97     uint8_t         cb_offset;      ///< needed for selecting VQ tables
98     uint8_t         buf_sel;        ///< active frame buffer: 0 - primary, 1 -secondary
99     const uint8_t   *y_data_ptr;
100     const uint8_t   *v_data_ptr;
101     const uint8_t   *u_data_ptr;
102     int32_t         y_data_size;
103     int32_t         v_data_size;
104     int32_t         u_data_size;
105     const uint8_t   *alt_quant;     ///< secondary VQ table set for the modes 1 and 4
106     Plane           planes[3];
107 } Indeo3DecodeContext;
108
109
110 static uint8_t requant_tab[8][128];
111
112 /*
113  *  Build the static requantization table.
114  *  This table is used to remap pixel values according to a specific
115  *  quant index and thus avoid overflows while adding deltas.
116  */
117 static av_cold void build_requant_tab(void)
118 {
119     static int8_t offsets[8] = { 1, 1, 2, -3, -3, 3, 4, 4 };
120     static int8_t deltas [8] = { 0, 1, 0,  4,  4, 1, 0, 1 };
121
122     int i, j, step;
123
124     for (i = 0; i < 8; i++) {
125         step = i + 2;
126         for (j = 0; j < 128; j++)
127                 requant_tab[i][j] = (j + offsets[i]) / step * step + deltas[i];
128     }
129
130     /* some last elements calculated above will have values >= 128 */
131     /* pixel values shall never exceed 127 so set them to non-overflowing values */
132     /* according with the quantization step of the respective section */
133     requant_tab[0][127] = 126;
134     requant_tab[1][119] = 118;
135     requant_tab[1][120] = 118;
136     requant_tab[2][126] = 124;
137     requant_tab[2][127] = 124;
138     requant_tab[6][124] = 120;
139     requant_tab[6][125] = 120;
140     requant_tab[6][126] = 120;
141     requant_tab[6][127] = 120;
142
143     /* Patch for compatibility with the Intel's binary decoders */
144     requant_tab[1][7] = 10;
145     requant_tab[4][8] = 10;
146 }
147
148
149 static av_cold int allocate_frame_buffers(Indeo3DecodeContext *ctx,
150                                           AVCodecContext *avctx)
151 {
152     int p, luma_width, luma_height, chroma_width, chroma_height;
153     int luma_pitch, chroma_pitch, luma_size, chroma_size;
154
155     luma_width  = ctx->width;
156     luma_height = ctx->height;
157
158     if (luma_width  < 16 || luma_width  > 640 ||
159         luma_height < 16 || luma_height > 480 ||
160         luma_width  &  3 || luma_height &   3) {
161         av_log(avctx, AV_LOG_ERROR, "Invalid picture dimensions: %d x %d!\n",
162                luma_width, luma_height);
163         return AVERROR_INVALIDDATA;
164     }
165
166     chroma_width  = FFALIGN(luma_width  >> 2, 4);
167     chroma_height = FFALIGN(luma_height >> 2, 4);
168
169     luma_pitch   = FFALIGN(luma_width,   16);
170     chroma_pitch = FFALIGN(chroma_width, 16);
171
172     /* Calculate size of the luminance plane.  */
173     /* Add one line more for INTRA prediction. */
174     luma_size = luma_pitch * (luma_height + 1);
175
176     /* Calculate size of a chrominance planes. */
177     /* Add one line more for INTRA prediction. */
178     chroma_size = chroma_pitch * (chroma_height + 1);
179
180     /* allocate frame buffers */
181     for (p = 0; p < 3; p++) {
182         ctx->planes[p].pitch  = !p ? luma_pitch  : chroma_pitch;
183         ctx->planes[p].width  = !p ? luma_width  : chroma_width;
184         ctx->planes[p].height = !p ? luma_height : chroma_height;
185
186         ctx->planes[p].buffers[0] = av_malloc(!p ? luma_size : chroma_size);
187         ctx->planes[p].buffers[1] = av_malloc(!p ? luma_size : chroma_size);
188
189         /* fill the INTRA prediction lines with the middle pixel value = 64 */
190         memset(ctx->planes[p].buffers[0], 0x40, ctx->planes[p].pitch);
191         memset(ctx->planes[p].buffers[1], 0x40, ctx->planes[p].pitch);
192
193         /* set buffer pointers = buf_ptr + pitch and thus skip the INTRA prediction line */
194         ctx->planes[p].pixels[0] = ctx->planes[p].buffers[0] + ctx->planes[p].pitch;
195         ctx->planes[p].pixels[1] = ctx->planes[p].buffers[1] + ctx->planes[p].pitch;
196     }
197
198     return 0;
199 }
200
201
202 static av_cold void free_frame_buffers(Indeo3DecodeContext *ctx)
203 {
204     int p;
205
206     for (p = 0; p < 3; p++) {
207         av_freep(&ctx->planes[p].buffers[0]);
208         av_freep(&ctx->planes[p].buffers[1]);
209     }
210 }
211
212
213 /**
214  *  Copy pixels of the cell(x + mv_x, y + mv_y) from the previous frame into
215  *  the cell(x, y) in the current frame.
216  *
217  *  @param ctx      pointer to the decoder context
218  *  @param plane    pointer to the plane descriptor
219  *  @param cell     pointer to the cell  descriptor
220  */
221 static void copy_cell(Indeo3DecodeContext *ctx, Plane *plane, Cell *cell)
222 {
223     int     h, w, mv_x, mv_y, offset, offset_dst;
224     uint8_t *src, *dst;
225
226     /* setup output and reference pointers */
227     offset_dst  = (cell->ypos << 2) * plane->pitch + (cell->xpos << 2);
228     dst         = plane->pixels[ctx->buf_sel] + offset_dst;
229     if(cell->mv_ptr){
230     mv_y        = cell->mv_ptr[0];
231     mv_x        = cell->mv_ptr[1];
232     }else
233         mv_x= mv_y= 0;
234     offset      = offset_dst + mv_y * plane->pitch + mv_x;
235     src         = plane->pixels[ctx->buf_sel ^ 1] + offset;
236
237     h = cell->height << 2;
238
239     for (w = cell->width; w > 0;) {
240         /* copy using 16xH blocks */
241         if (!((cell->xpos << 2) & 15) && w >= 4) {
242             for (; w >= 4; src += 16, dst += 16, w -= 4)
243                 ctx->dsp.put_no_rnd_pixels_tab[0][0](dst, src, plane->pitch, h);
244         }
245
246         /* copy using 8xH blocks */
247         if (!((cell->xpos << 2) & 7) && w >= 2) {
248             ctx->dsp.put_no_rnd_pixels_tab[1][0](dst, src, plane->pitch, h);
249             w -= 2;
250             src += 8;
251             dst += 8;
252         }
253
254         if (w >= 1) {
255             copy_block4(dst, src, plane->pitch, plane->pitch, h);
256             w--;
257             src += 4;
258             dst += 4;
259         }
260     }
261 }
262
263
264 /* Average 4/8 pixels at once without rounding using SWAR */
265 #define AVG_32(dst, src, ref) \
266     AV_WN32A(dst, ((AV_RN32A(src) + AV_RN32A(ref)) >> 1) & 0x7F7F7F7FUL)
267
268 #define AVG_64(dst, src, ref) \
269     AV_WN64A(dst, ((AV_RN64A(src) + AV_RN64A(ref)) >> 1) & 0x7F7F7F7F7F7F7F7FULL)
270
271
272 /*
273  *  Replicate each even pixel as follows:
274  *  ABCDEFGH -> AACCEEGG
275  */
276 static inline uint64_t replicate64(uint64_t a) {
277 #if HAVE_BIGENDIAN
278     a &= 0xFF00FF00FF00FF00ULL;
279     a |= a >> 8;
280 #else
281     a &= 0x00FF00FF00FF00FFULL;
282     a |= a << 8;
283 #endif
284     return a;
285 }
286
287 static inline uint32_t replicate32(uint32_t a) {
288 #if HAVE_BIGENDIAN
289     a &= 0xFF00FF00UL;
290     a |= a >> 8;
291 #else
292     a &= 0x00FF00FFUL;
293     a |= a << 8;
294 #endif
295     return a;
296 }
297
298
299 /* Fill n lines with 64bit pixel value pix */
300 static inline void fill_64(uint8_t *dst, const uint64_t pix, int32_t n,
301                            int32_t row_offset)
302 {
303     for (; n > 0; dst += row_offset, n--)
304         AV_WN64A(dst, pix);
305 }
306
307
308 /* Error codes for cell decoding. */
309 enum {
310     IV3_NOERR       = 0,
311     IV3_BAD_RLE     = 1,
312     IV3_BAD_DATA    = 2,
313     IV3_BAD_COUNTER = 3,
314     IV3_UNSUPPORTED = 4,
315     IV3_OUT_OF_DATA = 5
316 };
317
318
319 #define BUFFER_PRECHECK \
320 if (*data_ptr >= last_ptr) \
321     return IV3_OUT_OF_DATA; \
322
323 #define RLE_BLOCK_COPY \
324     if (cell->mv_ptr || !skip_flag) \
325         copy_block4(dst, ref, row_offset, row_offset, 4 << v_zoom)
326
327 #define RLE_BLOCK_COPY_8 \
328     pix64 = AV_RN64A(ref);\
329     if (is_first_row) {/* special prediction case: top line of a cell */\
330         pix64 = replicate64(pix64);\
331         fill_64(dst + row_offset, pix64, 7, row_offset);\
332         AVG_64(dst, ref, dst + row_offset);\
333     } else \
334         fill_64(dst, pix64, 8, row_offset)
335
336 #define RLE_LINES_COPY \
337     copy_block4(dst, ref, row_offset, row_offset, num_lines << v_zoom)
338
339 #define RLE_LINES_COPY_M10 \
340     pix64 = AV_RN64A(ref);\
341     if (is_top_of_cell) {\
342         pix64 = replicate64(pix64);\
343         fill_64(dst + row_offset, pix64, (num_lines << 1) - 1, row_offset);\
344         AVG_64(dst, ref, dst + row_offset);\
345     } else \
346         fill_64(dst, pix64, num_lines << 1, row_offset)
347
348 #define APPLY_DELTA_4 \
349     AV_WN16A(dst + line_offset    , AV_RN16A(ref    ) + delta_tab->deltas[dyad1]);\
350     AV_WN16A(dst + line_offset + 2, AV_RN16A(ref + 2) + delta_tab->deltas[dyad2]);\
351     if (mode >= 3) {\
352         if (is_top_of_cell && !cell->ypos) {\
353             AV_COPY32(dst, dst + row_offset);\
354         } else {\
355             AVG_32(dst, ref, dst + row_offset);\
356         }\
357     }
358
359 #define APPLY_DELTA_8 \
360     /* apply two 32-bit VQ deltas to next even line */\
361     if (is_top_of_cell) { \
362         AV_WN32A(dst + row_offset    , \
363                  replicate32(AV_RN32A(ref    )) + delta_tab->deltas_m10[dyad1]);\
364         AV_WN32A(dst + row_offset + 4, \
365                  replicate32(AV_RN32A(ref + 4)) + delta_tab->deltas_m10[dyad2]);\
366     } else { \
367         AV_WN32A(dst + row_offset    , \
368                  AV_RN32A(ref    ) + delta_tab->deltas_m10[dyad1]);\
369         AV_WN32A(dst + row_offset + 4, \
370                  AV_RN32A(ref + 4) + delta_tab->deltas_m10[dyad2]);\
371     } \
372     /* odd lines are not coded but rather interpolated/replicated */\
373     /* first line of the cell on the top of image? - replicate */\
374     /* otherwise - interpolate */\
375     if (is_top_of_cell && !cell->ypos) {\
376         AV_COPY64(dst, dst + row_offset);\
377     } else \
378         AVG_64(dst, ref, dst + row_offset);
379
380
381 #define APPLY_DELTA_1011_INTER \
382     if (mode == 10) { \
383         AV_WN32A(dst                 , \
384                  AV_RN32A(dst                 ) + delta_tab->deltas_m10[dyad1]);\
385         AV_WN32A(dst + 4             , \
386                  AV_RN32A(dst + 4             ) + delta_tab->deltas_m10[dyad2]);\
387         AV_WN32A(dst + row_offset    , \
388                  AV_RN32A(dst + row_offset    ) + delta_tab->deltas_m10[dyad1]);\
389         AV_WN32A(dst + row_offset + 4, \
390                  AV_RN32A(dst + row_offset + 4) + delta_tab->deltas_m10[dyad2]);\
391     } else { \
392         AV_WN16A(dst                 , \
393                  AV_RN16A(dst                 ) + delta_tab->deltas[dyad1]);\
394         AV_WN16A(dst + 2             , \
395                  AV_RN16A(dst + 2             ) + delta_tab->deltas[dyad2]);\
396         AV_WN16A(dst + row_offset    , \
397                  AV_RN16A(dst + row_offset    ) + delta_tab->deltas[dyad1]);\
398         AV_WN16A(dst + row_offset + 2, \
399                  AV_RN16A(dst + row_offset + 2) + delta_tab->deltas[dyad2]);\
400     }
401
402
403 static int decode_cell_data(Cell *cell, uint8_t *block, uint8_t *ref_block,
404                             int pitch, int h_zoom, int v_zoom, int mode,
405                             const vqEntry *delta[2], int swap_quads[2],
406                             const uint8_t **data_ptr, const uint8_t *last_ptr)
407 {
408     int           x, y, line, num_lines;
409     int           rle_blocks = 0;
410     uint8_t       code, *dst, *ref;
411     const vqEntry *delta_tab;
412     unsigned int  dyad1, dyad2;
413     uint64_t      pix64;
414     int           skip_flag = 0, is_top_of_cell, is_first_row = 1;
415     int           row_offset, blk_row_offset, line_offset;
416
417     row_offset     =  pitch;
418     blk_row_offset = (row_offset << (2 + v_zoom)) - (cell->width << 2);
419     line_offset    = v_zoom ? row_offset : 0;
420
421     for (y = 0; y < cell->height; is_first_row = 0, y += 1 + v_zoom) {
422         for (x = 0; x < cell->width; x += 1 + h_zoom) {
423             ref = ref_block;
424             dst = block;
425
426             if (rle_blocks > 0) {
427                 if (mode <= 4) {
428                     RLE_BLOCK_COPY;
429                 } else if (mode == 10 && !cell->mv_ptr) {
430                     RLE_BLOCK_COPY_8;
431                 }
432                 rle_blocks--;
433             } else {
434                 for (line = 0; line < 4;) {
435                     num_lines = 1;
436                     is_top_of_cell = is_first_row && !line;
437
438                     /* select primary VQ table for odd, secondary for even lines */
439                     if (mode <= 4)
440                         delta_tab = delta[line & 1];
441                     else
442                         delta_tab = delta[1];
443                     BUFFER_PRECHECK;
444                     code = bytestream_get_byte(data_ptr);
445                     if (code < 248) {
446                         if (code < delta_tab->num_dyads) {
447                             BUFFER_PRECHECK;
448                             dyad1 = bytestream_get_byte(data_ptr);
449                             dyad2 = code;
450                             if (dyad1 >= delta_tab->num_dyads || dyad1 >= 248)
451                                 return IV3_BAD_DATA;
452                         } else {
453                             /* process QUADS */
454                             code -= delta_tab->num_dyads;
455                             dyad1 = code / delta_tab->quad_exp;
456                             dyad2 = code % delta_tab->quad_exp;
457                             if (swap_quads[line & 1])
458                                 FFSWAP(unsigned int, dyad1, dyad2);
459                         }
460                         if (mode <= 4) {
461                             APPLY_DELTA_4;
462                         } else if (mode == 10 && !cell->mv_ptr) {
463                             APPLY_DELTA_8;
464                         } else {
465                             APPLY_DELTA_1011_INTER;
466                         }
467                     } else {
468                         /* process RLE codes */
469                         switch (code) {
470                         case RLE_ESC_FC:
471                             skip_flag  = 0;
472                             rle_blocks = 1;
473                             code       = 253;
474                             /* FALLTHROUGH */
475                         case RLE_ESC_FF:
476                         case RLE_ESC_FE:
477                         case RLE_ESC_FD:
478                             num_lines = 257 - code - line;
479                             if (num_lines <= 0)
480                                 return IV3_BAD_RLE;
481                             if (mode <= 4) {
482                                 RLE_LINES_COPY;
483                             } else if (mode == 10 && !cell->mv_ptr) {
484                                 RLE_LINES_COPY_M10;
485                             }
486                             break;
487                         case RLE_ESC_FB:
488                             BUFFER_PRECHECK;
489                             code = bytestream_get_byte(data_ptr);
490                             rle_blocks = (code & 0x1F) - 1; /* set block counter */
491                             if (code >= 64 || rle_blocks < 0)
492                                 return IV3_BAD_COUNTER;
493                             skip_flag = code & 0x20;
494                             num_lines = 4 - line; /* enforce next block processing */
495                             if (mode >= 10 || (cell->mv_ptr || !skip_flag)) {
496                                 if (mode <= 4) {
497                                     RLE_LINES_COPY;
498                                 } else if (mode == 10 && !cell->mv_ptr) {
499                                     RLE_LINES_COPY_M10;
500                                 }
501                             }
502                             break;
503                         case RLE_ESC_F9:
504                             skip_flag  = 1;
505                             rle_blocks = 1;
506                             /* FALLTHROUGH */
507                         case RLE_ESC_FA:
508                             if (line)
509                                 return IV3_BAD_RLE;
510                             num_lines = 4; /* enforce next block processing */
511                             if (cell->mv_ptr) {
512                                 if (mode <= 4) {
513                                     RLE_LINES_COPY;
514                                 } else if (mode == 10 && !cell->mv_ptr) {
515                                     RLE_LINES_COPY_M10;
516                                 }
517                             }
518                             break;
519                         default:
520                             return IV3_UNSUPPORTED;
521                         }
522                     }
523
524                     line += num_lines;
525                     ref  += row_offset * (num_lines << v_zoom);
526                     dst  += row_offset * (num_lines << v_zoom);
527                 }
528             }
529
530             /* move to next horizontal block */
531             block     += 4 << h_zoom;
532             ref_block += 4 << h_zoom;
533         }
534
535         /* move to next line of blocks */
536         ref_block += blk_row_offset;
537         block     += blk_row_offset;
538     }
539     return IV3_NOERR;
540 }
541
542
543 /**
544  *  Decode a vector-quantized cell.
545  *  It consists of several routines, each of which handles one or more "modes"
546  *  with which a cell can be encoded.
547  *
548  *  @param ctx      pointer to the decoder context
549  *  @param avctx    ptr to the AVCodecContext
550  *  @param plane    pointer to the plane descriptor
551  *  @param cell     pointer to the cell  descriptor
552  *  @param data_ptr pointer to the compressed data
553  *  @param last_ptr pointer to the last byte to catch reads past end of buffer
554  *  @return         number of consumed bytes or negative number in case of error
555  */
556 static int decode_cell(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
557                        Plane *plane, Cell *cell, const uint8_t *data_ptr,
558                        const uint8_t *last_ptr)
559 {
560     int           x, mv_x, mv_y, mode, vq_index, prim_indx, second_indx;
561     int           zoom_fac;
562     int           offset, error = 0, swap_quads[2];
563     uint8_t       code, *block, *ref_block = 0;
564     const vqEntry *delta[2];
565     const uint8_t *data_start = data_ptr;
566
567     /* get coding mode and VQ table index from the VQ descriptor byte */
568     code     = *data_ptr++;
569     mode     = code >> 4;
570     vq_index = code & 0xF;
571
572     /* setup output and reference pointers */
573     offset = (cell->ypos << 2) * plane->pitch + (cell->xpos << 2);
574     block  =  plane->pixels[ctx->buf_sel] + offset;
575     if (!cell->mv_ptr) {
576         /* use previous line as reference for INTRA cells */
577         ref_block = block - plane->pitch;
578     } else if (mode >= 10) {
579         /* for mode 10 and 11 INTER first copy the predicted cell into the current one */
580         /* so we don't need to do data copying for each RLE code later */
581         copy_cell(ctx, plane, cell);
582     } else {
583         /* set the pointer to the reference pixels for modes 0-4 INTER */
584         mv_y      = cell->mv_ptr[0];
585         mv_x      = cell->mv_ptr[1];
586         offset   += mv_y * plane->pitch + mv_x;
587         ref_block = plane->pixels[ctx->buf_sel ^ 1] + offset;
588     }
589
590     /* select VQ tables as follows: */
591     /* modes 0 and 3 use only the primary table for all lines in a block */
592     /* while modes 1 and 4 switch between primary and secondary tables on alternate lines */
593     if (mode == 1 || mode == 4) {
594         code        = ctx->alt_quant[vq_index];
595         prim_indx   = (code >> 4)  + ctx->cb_offset;
596         second_indx = (code & 0xF) + ctx->cb_offset;
597     } else {
598         vq_index += ctx->cb_offset;
599         prim_indx = second_indx = vq_index;
600     }
601
602     if (prim_indx >= 24 || second_indx >= 24) {
603         av_log(avctx, AV_LOG_ERROR, "Invalid VQ table indexes! Primary: %d, secondary: %d!\n",
604                prim_indx, second_indx);
605         return AVERROR_INVALIDDATA;
606     }
607
608     delta[0] = &vq_tab[second_indx];
609     delta[1] = &vq_tab[prim_indx];
610     swap_quads[0] = second_indx >= 16;
611     swap_quads[1] = prim_indx   >= 16;
612
613     /* requantize the prediction if VQ index of this cell differs from VQ index */
614     /* of the predicted cell in order to avoid overflows. */
615     if (vq_index >= 8 && ref_block) {
616         for (x = 0; x < cell->width << 2; x++)
617             ref_block[x] = requant_tab[vq_index & 7][ref_block[x]];
618     }
619
620     error = IV3_NOERR;
621
622     switch (mode) {
623     case 0: /*------------------ MODES 0 & 1 (4x4 block processing) --------------------*/
624     case 1:
625     case 3: /*------------------ MODES 3 & 4 (4x8 block processing) --------------------*/
626     case 4:
627         if (mode >= 3 && cell->mv_ptr) {
628             av_log(avctx, AV_LOG_ERROR, "Attempt to apply Mode 3/4 to an INTER cell!\n");
629             return AVERROR_INVALIDDATA;
630         }
631
632         zoom_fac = mode >= 3;
633         error = decode_cell_data(cell, block, ref_block, plane->pitch, 0, zoom_fac,
634                                  mode, delta, swap_quads, &data_ptr, last_ptr);
635         break;
636     case 10: /*-------------------- MODE 10 (8x8 block processing) ---------------------*/
637     case 11: /*----------------- MODE 11 (4x8 INTER block processing) ------------------*/
638         if (mode == 10 && !cell->mv_ptr) { /* MODE 10 INTRA processing */
639             error = decode_cell_data(cell, block, ref_block, plane->pitch, 1, 1,
640                                      mode, delta, swap_quads, &data_ptr, last_ptr);
641         } else { /* mode 10 and 11 INTER processing */
642             if (mode == 11 && !cell->mv_ptr) {
643                av_log(avctx, AV_LOG_ERROR, "Attempt to use Mode 11 for an INTRA cell!\n");
644                return AVERROR_INVALIDDATA;
645             }
646
647             zoom_fac = mode == 10;
648             error = decode_cell_data(cell, block, ref_block, plane->pitch,
649                                      zoom_fac, 1, mode, delta, swap_quads,
650                                      &data_ptr, last_ptr);
651         }
652         break;
653     default:
654         av_log(avctx, AV_LOG_ERROR, "Unsupported coding mode: %d\n", mode);
655         return AVERROR_INVALIDDATA;
656     }//switch mode
657
658     switch (error) {
659     case IV3_BAD_RLE:
660         av_log(avctx, AV_LOG_ERROR, "Mode %d: RLE code %X is not allowed at the current line\n",
661                mode, data_ptr[-1]);
662         return AVERROR_INVALIDDATA;
663     case IV3_BAD_DATA:
664         av_log(avctx, AV_LOG_ERROR, "Mode %d: invalid VQ data\n", mode);
665         return AVERROR_INVALIDDATA;
666     case IV3_BAD_COUNTER:
667         av_log(avctx, AV_LOG_ERROR, "Mode %d: RLE-FB invalid counter: %d\n", mode, code);
668         return AVERROR_INVALIDDATA;
669     case IV3_UNSUPPORTED:
670         av_log(avctx, AV_LOG_ERROR, "Mode %d: unsupported RLE code: %X\n", mode, data_ptr[-1]);
671         return AVERROR_INVALIDDATA;
672     case IV3_OUT_OF_DATA:
673         av_log(avctx, AV_LOG_ERROR, "Mode %d: attempt to read past end of buffer\n", mode);
674         return AVERROR_INVALIDDATA;
675     }
676
677     return data_ptr - data_start; /* report number of bytes consumed from the input buffer */
678 }
679
680
681 /* Binary tree codes. */
682 enum {
683     H_SPLIT    = 0,
684     V_SPLIT    = 1,
685     INTRA_NULL = 2,
686     INTER_DATA = 3
687 };
688
689
690 #define SPLIT_CELL(size, new_size) (new_size) = ((size) > 2) ? ((((size) + 2) >> 2) << 1) : 1
691
692 #define UPDATE_BITPOS(n) \
693     ctx->skip_bits  += (n); \
694     ctx->need_resync = 1
695
696 #define RESYNC_BITSTREAM \
697     if (ctx->need_resync && !(get_bits_count(&ctx->gb) & 7)) { \
698         skip_bits_long(&ctx->gb, ctx->skip_bits);              \
699         ctx->skip_bits   = 0;                                  \
700         ctx->need_resync = 0;                                  \
701     }
702
703 #define CHECK_CELL \
704     if (curr_cell.xpos + curr_cell.width > (plane->width >> 2) ||               \
705         curr_cell.ypos + curr_cell.height > (plane->height >> 2)) {             \
706         av_log(avctx, AV_LOG_ERROR, "Invalid cell: x=%d, y=%d, w=%d, h=%d\n",   \
707                curr_cell.xpos, curr_cell.ypos, curr_cell.width, curr_cell.height); \
708         return AVERROR_INVALIDDATA;                                                              \
709     }
710
711
712 static int parse_bintree(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
713                          Plane *plane, int code, Cell *ref_cell,
714                          const int depth, const int strip_width)
715 {
716     Cell    curr_cell;
717     int     bytes_used;
718
719     if (depth <= 0) {
720         av_log(avctx, AV_LOG_ERROR, "Stack overflow (corrupted binary tree)!\n");
721         return AVERROR_INVALIDDATA; // unwind recursion
722     }
723
724     curr_cell = *ref_cell; // clone parent cell
725     if (code == H_SPLIT) {
726         SPLIT_CELL(ref_cell->height, curr_cell.height);
727         ref_cell->ypos   += curr_cell.height;
728         ref_cell->height -= curr_cell.height;
729     } else if (code == V_SPLIT) {
730         if (curr_cell.width > strip_width) {
731             /* split strip */
732             curr_cell.width = (curr_cell.width <= (strip_width << 1) ? 1 : 2) * strip_width;
733         } else
734             SPLIT_CELL(ref_cell->width, curr_cell.width);
735         ref_cell->xpos  += curr_cell.width;
736         ref_cell->width -= curr_cell.width;
737     }
738
739     while (get_bits_left(&ctx->gb) >= 2) { /* loop until return */
740         RESYNC_BITSTREAM;
741         switch (code = get_bits(&ctx->gb, 2)) {
742         case H_SPLIT:
743         case V_SPLIT:
744             if (parse_bintree(ctx, avctx, plane, code, &curr_cell, depth - 1, strip_width))
745                 return AVERROR_INVALIDDATA;
746             break;
747         case INTRA_NULL:
748             if (!curr_cell.tree) { /* MC tree INTRA code */
749                 curr_cell.mv_ptr = 0; /* mark the current strip as INTRA */
750                 curr_cell.tree   = 1; /* enter the VQ tree */
751             } else { /* VQ tree NULL code */
752                 RESYNC_BITSTREAM;
753                 code = get_bits(&ctx->gb, 2);
754                 if (code >= 2) {
755                     av_log(avctx, AV_LOG_ERROR, "Invalid VQ_NULL code: %d\n", code);
756                     return AVERROR_INVALIDDATA;
757                 }
758                 if (code == 1)
759                     av_log(avctx, AV_LOG_ERROR, "SkipCell procedure not implemented yet!\n");
760
761                 CHECK_CELL
762                 if (!curr_cell.mv_ptr)
763                     return AVERROR_INVALIDDATA;
764                 copy_cell(ctx, plane, &curr_cell);
765                 return 0;
766             }
767             break;
768         case INTER_DATA:
769             if (!curr_cell.tree) { /* MC tree INTER code */
770                 /* get motion vector index and setup the pointer to the mv set */
771                 if (!ctx->need_resync)
772                     ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];
773                 if(ctx->mc_vectors)
774                     curr_cell.mv_ptr = &ctx->mc_vectors[*(ctx->next_cell_data++) << 1];
775                 curr_cell.tree   = 1; /* enter the VQ tree */
776                 UPDATE_BITPOS(8);
777             } else { /* VQ tree DATA code */
778                 if (!ctx->need_resync)
779                     ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];
780
781                 CHECK_CELL
782                 bytes_used = decode_cell(ctx, avctx, plane, &curr_cell,
783                                          ctx->next_cell_data, ctx->last_byte);
784                 if (bytes_used < 0)
785                     return AVERROR_INVALIDDATA;
786
787                 UPDATE_BITPOS(bytes_used << 3);
788                 ctx->next_cell_data += bytes_used;
789                 return 0;
790             }
791             break;
792         }
793     }//while
794
795     return AVERROR_INVALIDDATA;
796 }
797
798
799 static int decode_plane(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
800                         Plane *plane, const uint8_t *data, int32_t data_size,
801                         int32_t strip_width)
802 {
803     Cell            curr_cell;
804     uint32_t        num_vectors;
805
806     /* each plane data starts with mc_vector_count field, */
807     /* an optional array of motion vectors followed by the vq data */
808     num_vectors = bytestream_get_le32(&data);
809     if(num_vectors >= data_size/2)
810         return AVERROR_INVALIDDATA;
811     ctx->mc_vectors  = num_vectors ? data : 0;
812     data     += num_vectors * 2;
813     data_size-= num_vectors * 2;
814
815     /* init the bitreader */
816     init_get_bits(&ctx->gb, data, data_size << 3);
817     ctx->skip_bits   = 0;
818     ctx->need_resync = 0;
819
820     ctx->last_byte = data + data_size - 1;
821
822     /* initialize the 1st cell and set its dimensions to whole plane */
823     curr_cell.xpos   = curr_cell.ypos = 0;
824     curr_cell.width  = plane->width  >> 2;
825     curr_cell.height = plane->height >> 2;
826     curr_cell.tree   = 0; // we are in the MC tree now
827     curr_cell.mv_ptr = 0; // no motion vector = INTRA cell
828
829     return parse_bintree(ctx, avctx, plane, INTRA_NULL, &curr_cell, CELL_STACK_MAX, strip_width);
830 }
831
832
833 #define OS_HDR_ID   MKBETAG('F', 'R', 'M', 'H')
834
835 static int decode_frame_headers(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
836                                 const uint8_t *buf, int buf_size)
837 {
838     const uint8_t   *buf_ptr = buf, *bs_hdr;
839     uint32_t        frame_num, word2, check_sum, data_size;
840     uint32_t        y_offset, u_offset, v_offset, starts[3], ends[3];
841     uint16_t        height, width;
842     int             i, j;
843
844     /* parse and check the OS header */
845     frame_num = bytestream_get_le32(&buf_ptr);
846     word2     = bytestream_get_le32(&buf_ptr);
847     check_sum = bytestream_get_le32(&buf_ptr);
848     data_size = bytestream_get_le32(&buf_ptr);
849
850     if ((frame_num ^ word2 ^ data_size ^ OS_HDR_ID) != check_sum) {
851         av_log(avctx, AV_LOG_ERROR, "OS header checksum mismatch!\n");
852         return AVERROR_INVALIDDATA;
853     }
854
855     /* parse the bitstream header */
856     bs_hdr = buf_ptr;
857
858     if (bytestream_get_le16(&buf_ptr) != 32) {
859         av_log(avctx, AV_LOG_ERROR, "Unsupported codec version!\n");
860         return AVERROR_INVALIDDATA;
861     }
862
863     ctx->frame_num   =  frame_num;
864     ctx->frame_flags =  bytestream_get_le16(&buf_ptr);
865     ctx->data_size   = (bytestream_get_le32(&buf_ptr) + 7) >> 3;
866     ctx->cb_offset   = *buf_ptr++;
867
868     if (ctx->data_size == 16)
869         return 4;
870     if (ctx->data_size > buf_size)
871         ctx->data_size = buf_size;
872
873     buf_ptr += 3; // skip reserved byte and checksum
874
875     /* check frame dimensions */
876     height = bytestream_get_le16(&buf_ptr);
877     width  = bytestream_get_le16(&buf_ptr);
878     if (av_image_check_size(width, height, 0, avctx))
879         return AVERROR_INVALIDDATA;
880
881     if (width != ctx->width || height != ctx->height) {
882         av_dlog(avctx, "Frame dimensions changed!\n");
883
884         ctx->width  = width;
885         ctx->height = height;
886
887         free_frame_buffers(ctx);
888         if(allocate_frame_buffers(ctx, avctx) < 0)
889             return AVERROR_INVALIDDATA;
890         avcodec_set_dimensions(avctx, width, height);
891     }
892
893     y_offset = bytestream_get_le32(&buf_ptr);
894     v_offset = bytestream_get_le32(&buf_ptr);
895     u_offset = bytestream_get_le32(&buf_ptr);
896
897     /* unfortunately there is no common order of planes in the buffer */
898     /* so we use that sorting algo for determining planes data sizes  */
899     starts[0] = y_offset;
900     starts[1] = v_offset;
901     starts[2] = u_offset;
902
903     for (j = 0; j < 3; j++) {
904         ends[j] = ctx->data_size;
905         for (i = 2; i >= 0; i--)
906             if (starts[i] < ends[j] && starts[i] > starts[j])
907                 ends[j] = starts[i];
908     }
909
910     ctx->y_data_size = ends[0] - starts[0];
911     ctx->v_data_size = ends[1] - starts[1];
912     ctx->u_data_size = ends[2] - starts[2];
913     if (FFMAX3(y_offset, v_offset, u_offset) >= ctx->data_size - 16 ||
914         FFMIN3(ctx->y_data_size, ctx->v_data_size, ctx->u_data_size) <= 0) {
915         av_log(avctx, AV_LOG_ERROR, "One of the y/u/v offsets is invalid\n");
916         return AVERROR_INVALIDDATA;
917     }
918
919     ctx->y_data_ptr = bs_hdr + y_offset;
920     ctx->v_data_ptr = bs_hdr + v_offset;
921     ctx->u_data_ptr = bs_hdr + u_offset;
922     ctx->alt_quant  = buf_ptr + sizeof(uint32_t);
923
924     if (ctx->data_size == 16) {
925         av_log(avctx, AV_LOG_DEBUG, "Sync frame encountered!\n");
926         return 16;
927     }
928
929     if (ctx->frame_flags & BS_8BIT_PEL) {
930         av_log_ask_for_sample(avctx, "8-bit pixel format\n");
931         return AVERROR_PATCHWELCOME;
932     }
933
934     if (ctx->frame_flags & BS_MV_X_HALF || ctx->frame_flags & BS_MV_Y_HALF) {
935         av_log_ask_for_sample(avctx, "halfpel motion vectors\n");
936         return AVERROR_PATCHWELCOME;
937     }
938
939     return 0;
940 }
941
942
943 /**
944  *  Convert and output the current plane.
945  *  All pixel values will be upsampled by shifting right by one bit.
946  *
947  *  @param[in]  plane        pointer to the descriptor of the plane being processed
948  *  @param[in]  buf_sel      indicates which frame buffer the input data stored in
949  *  @param[out] dst          pointer to the buffer receiving converted pixels
950  *  @param[in]  dst_pitch    pitch for moving to the next y line
951  */
952 static void output_plane(const Plane *plane, int buf_sel, uint8_t *dst, int dst_pitch)
953 {
954     int             x,y;
955     const uint8_t   *src  = plane->pixels[buf_sel];
956     uint32_t        pitch = plane->pitch;
957
958     for (y = 0; y < plane->height; y++) {
959         /* convert four pixels at once using SWAR */
960         for (x = 0; x < plane->width >> 2; x++) {
961             AV_WN32A(dst, (AV_RN32A(src) & 0x7F7F7F7F) << 1);
962             src += 4;
963             dst += 4;
964         }
965
966         for (x <<= 2; x < plane->width; x++)
967             *dst++ = *src++ << 1;
968
969         src += pitch     - plane->width;
970         dst += dst_pitch - plane->width;
971     }
972 }
973
974
975 static av_cold int decode_init(AVCodecContext *avctx)
976 {
977     Indeo3DecodeContext *ctx = avctx->priv_data;
978
979     ctx->avctx     = avctx;
980     ctx->width     = avctx->width;
981     ctx->height    = avctx->height;
982     avctx->pix_fmt = PIX_FMT_YUV410P;
983     avcodec_get_frame_defaults(&ctx->frame);
984
985     build_requant_tab();
986
987     dsputil_init(&ctx->dsp, avctx);
988
989     return allocate_frame_buffers(ctx, avctx);
990 }
991
992
993 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
994                         AVPacket *avpkt)
995 {
996     Indeo3DecodeContext *ctx = avctx->priv_data;
997     const uint8_t *buf = avpkt->data;
998     int buf_size       = avpkt->size;
999     int res;
1000
1001     res = decode_frame_headers(ctx, avctx, buf, buf_size);
1002     if (res < 0)
1003         return res;
1004
1005     /* skip sync(null) frames */
1006     if (res) {
1007         // we have processed 16 bytes but no data was decoded
1008         *data_size = 0;
1009         return buf_size;
1010     }
1011
1012     /* skip droppable INTER frames if requested */
1013     if (ctx->frame_flags & BS_NONREF &&
1014        (avctx->skip_frame >= AVDISCARD_NONREF))
1015         return 0;
1016
1017     /* skip INTER frames if requested */
1018     if (!(ctx->frame_flags & BS_KEYFRAME) && avctx->skip_frame >= AVDISCARD_NONKEY)
1019         return 0;
1020
1021     /* use BS_BUFFER flag for buffer switching */
1022     ctx->buf_sel = (ctx->frame_flags >> BS_BUFFER) & 1;
1023
1024     /* decode luma plane */
1025     if ((res = decode_plane(ctx, avctx, ctx->planes, ctx->y_data_ptr, ctx->y_data_size, 40)))
1026         return res;
1027
1028     /* decode chroma planes */
1029     if ((res = decode_plane(ctx, avctx, &ctx->planes[1], ctx->u_data_ptr, ctx->u_data_size, 10)))
1030         return res;
1031
1032     if ((res = decode_plane(ctx, avctx, &ctx->planes[2], ctx->v_data_ptr, ctx->v_data_size, 10)))
1033         return res;
1034
1035     if (ctx->frame.data[0])
1036         avctx->release_buffer(avctx, &ctx->frame);
1037
1038     ctx->frame.reference = 0;
1039     if ((res = avctx->get_buffer(avctx, &ctx->frame)) < 0) {
1040         av_log(ctx->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1041         return res;
1042     }
1043
1044     output_plane(&ctx->planes[0], ctx->buf_sel, ctx->frame.data[0], ctx->frame.linesize[0]);
1045     output_plane(&ctx->planes[1], ctx->buf_sel, ctx->frame.data[1], ctx->frame.linesize[1]);
1046     output_plane(&ctx->planes[2], ctx->buf_sel, ctx->frame.data[2], ctx->frame.linesize[2]);
1047
1048     *data_size      = sizeof(AVFrame);
1049     *(AVFrame*)data = ctx->frame;
1050
1051     return buf_size;
1052 }
1053
1054
1055 static av_cold int decode_close(AVCodecContext *avctx)
1056 {
1057     Indeo3DecodeContext *ctx = avctx->priv_data;
1058
1059     free_frame_buffers(avctx->priv_data);
1060
1061     if (ctx->frame.data[0])
1062         avctx->release_buffer(avctx, &ctx->frame);
1063
1064     return 0;
1065 }
1066
1067 AVCodec ff_indeo3_decoder = {
1068     .name           = "indeo3",
1069     .type           = AVMEDIA_TYPE_VIDEO,
1070     .id             = CODEC_ID_INDEO3,
1071     .priv_data_size = sizeof(Indeo3DecodeContext),
1072     .init           = decode_init,
1073     .close          = decode_close,
1074     .decode         = decode_frame,
1075     .long_name      = NULL_IF_CONFIG_SMALL("Intel Indeo 3"),
1076 };