Add DXVA2 HEVC HWAccel
[ffmpeg.git] / libavcodec / mpeg4videodec.c
1 /*
2  * MPEG4 decoder.
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "error_resilience.h"
24 #include "idctdsp.h"
25 #include "internal.h"
26 #include "mpegutils.h"
27 #include "mpegvideo.h"
28 #include "mpeg4video.h"
29 #include "h263.h"
30 #include "thread.h"
31 #include "xvididct.h"
32
33 /* The defines below define the number of bits that are read at once for
34  * reading vlc values. Changing these may improve speed and data cache needs
35  * be aware though that decreasing them may need the number of stages that is
36  * passed to get_vlc* to be increased. */
37 #define SPRITE_TRAJ_VLC_BITS 6
38 #define DC_VLC_BITS 9
39 #define MB_TYPE_B_VLC_BITS 4
40
41 static VLC dc_lum, dc_chrom;
42 static VLC sprite_trajectory;
43 static VLC mb_type_b_vlc;
44
45 static const int mb_type_b_map[4] = {
46     MB_TYPE_DIRECT2 | MB_TYPE_L0L1,
47     MB_TYPE_L0L1    | MB_TYPE_16x16,
48     MB_TYPE_L1      | MB_TYPE_16x16,
49     MB_TYPE_L0      | MB_TYPE_16x16,
50 };
51
52 /**
53  * Predict the ac.
54  * @param n block index (0-3 are luma, 4-5 are chroma)
55  * @param dir the ac prediction direction
56  */
57 void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir)
58 {
59     int i;
60     int16_t *ac_val, *ac_val1;
61     int8_t *const qscale_table = s->current_picture.qscale_table;
62
63     /* find prediction */
64     ac_val  = s->ac_val[0][0] + s->block_index[n] * 16;
65     ac_val1 = ac_val;
66     if (s->ac_pred) {
67         if (dir == 0) {
68             const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
69             /* left prediction */
70             ac_val -= 16;
71
72             if (s->mb_x == 0 || s->qscale == qscale_table[xy] ||
73                 n == 1 || n == 3) {
74                 /* same qscale */
75                 for (i = 1; i < 8; i++)
76                     block[s->idsp.idct_permutation[i << 3]] += ac_val[i];
77             } else {
78                 /* different qscale, we must rescale */
79                 for (i = 1; i < 8; i++)
80                     block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
81             }
82         } else {
83             const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
84             /* top prediction */
85             ac_val -= 16 * s->block_wrap[n];
86
87             if (s->mb_y == 0 || s->qscale == qscale_table[xy] ||
88                 n == 2 || n == 3) {
89                 /* same qscale */
90                 for (i = 1; i < 8; i++)
91                     block[s->idsp.idct_permutation[i]] += ac_val[i + 8];
92             } else {
93                 /* different qscale, we must rescale */
94                 for (i = 1; i < 8; i++)
95                     block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
96             }
97         }
98     }
99     /* left copy */
100     for (i = 1; i < 8; i++)
101         ac_val1[i] = block[s->idsp.idct_permutation[i << 3]];
102
103     /* top copy */
104     for (i = 1; i < 8; i++)
105         ac_val1[8 + i] = block[s->idsp.idct_permutation[i]];
106 }
107
108 /**
109  * check if the next stuff is a resync marker or the end.
110  * @return 0 if not
111  */
112 static inline int mpeg4_is_resync(MpegEncContext *s)
113 {
114     int bits_count = get_bits_count(&s->gb);
115     int v          = show_bits(&s->gb, 16);
116
117     if (s->workaround_bugs & FF_BUG_NO_PADDING)
118         return 0;
119
120     while (v <= 0xFF) {
121         if (s->pict_type == AV_PICTURE_TYPE_B ||
122             (v >> (8 - s->pict_type) != 1) || s->partitioned_frame)
123             break;
124         skip_bits(&s->gb, 8 + s->pict_type);
125         bits_count += 8 + s->pict_type;
126         v = show_bits(&s->gb, 16);
127     }
128
129     if (bits_count + 8 >= s->gb.size_in_bits) {
130         v >>= 8;
131         v  |= 0x7F >> (7 - (bits_count & 7));
132
133         if (v == 0x7F)
134             return 1;
135     } else {
136         if (v == ff_mpeg4_resync_prefix[bits_count & 7]) {
137             int len;
138             GetBitContext gb = s->gb;
139
140             skip_bits(&s->gb, 1);
141             align_get_bits(&s->gb);
142
143             for (len = 0; len < 32; len++)
144                 if (get_bits1(&s->gb))
145                     break;
146
147             s->gb = gb;
148
149             if (len >= ff_mpeg4_get_video_packet_prefix_length(s))
150                 return 1;
151         }
152     }
153     return 0;
154 }
155
156 static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb)
157 {
158     MpegEncContext *s = &ctx->m;
159     int a     = 2 << s->sprite_warping_accuracy;
160     int rho   = 3  - s->sprite_warping_accuracy;
161     int r     = 16 / a;
162     int alpha = 0;
163     int beta  = 0;
164     int w     = s->width;
165     int h     = s->height;
166     int min_ab, i, w2, h2, w3, h3;
167     int sprite_ref[4][2];
168     int virtual_ref[2][2];
169
170     // only true for rectangle shapes
171     const int vop_ref[4][2] = { { 0, 0 },         { s->width, 0 },
172                                 { 0, s->height }, { s->width, s->height } };
173     int d[4][2]             = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
174
175     if (w <= 0 || h <= 0)
176         return AVERROR_INVALIDDATA;
177
178     for (i = 0; i < ctx->num_sprite_warping_points; i++) {
179         int length;
180         int x = 0, y = 0;
181
182         length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
183         if (length)
184             x = get_xbits(gb, length);
185
186         if (!(ctx->divx_version == 500 && ctx->divx_build == 413))
187             skip_bits1(gb);     /* marker bit */
188
189         length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
190         if (length)
191             y = get_xbits(gb, length);
192
193         skip_bits1(gb);         /* marker bit */
194         ctx->sprite_traj[i][0] = d[i][0] = x;
195         ctx->sprite_traj[i][1] = d[i][1] = y;
196     }
197     for (; i < 4; i++)
198         ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0;
199
200     while ((1 << alpha) < w)
201         alpha++;
202     while ((1 << beta) < h)
203         beta++;  /* typo in the mpeg4 std for the definition of w' and h' */
204     w2 = 1 << alpha;
205     h2 = 1 << beta;
206
207     // Note, the 4th point isn't used for GMC
208     if (ctx->divx_version == 500 && ctx->divx_build == 413) {
209         sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0];
210         sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1];
211         sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0];
212         sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1];
213         sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0];
214         sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1];
215     } else {
216         sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]);
217         sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]);
218         sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]);
219         sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]);
220         sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]);
221         sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]);
222     }
223     /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
224      * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
225
226     /* this is mostly identical to the mpeg4 std (and is totally unreadable
227      * because of that...). Perhaps it should be reordered to be more readable.
228      * The idea behind this virtual_ref mess is to be able to use shifts later
229      * per pixel instead of divides so the distance between points is converted
230      * from w&h based to w2&h2 based which are of the 2^x form. */
231     virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) +
232                          ROUNDED_DIV(((w - w2) *
233                                       (r * sprite_ref[0][0] - 16 * vop_ref[0][0]) +
234                                       w2 * (r * sprite_ref[1][0] - 16 * vop_ref[1][0])), w);
235     virtual_ref[0][1] = 16 * vop_ref[0][1] +
236                         ROUNDED_DIV(((w - w2) *
237                                      (r * sprite_ref[0][1] - 16 * vop_ref[0][1]) +
238                                      w2 * (r * sprite_ref[1][1] - 16 * vop_ref[1][1])), w);
239     virtual_ref[1][0] = 16 * vop_ref[0][0] +
240                         ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16 * vop_ref[0][0]) +
241                                      h2 * (r * sprite_ref[2][0] - 16 * vop_ref[2][0])), h);
242     virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) +
243                         ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16 * vop_ref[0][1]) +
244                                      h2 * (r * sprite_ref[2][1] - 16 * vop_ref[2][1])), h);
245
246     switch (ctx->num_sprite_warping_points) {
247     case 0:
248         s->sprite_offset[0][0] =
249         s->sprite_offset[0][1] =
250         s->sprite_offset[1][0] =
251         s->sprite_offset[1][1] = 0;
252         s->sprite_delta[0][0]  = a;
253         s->sprite_delta[0][1]  =
254         s->sprite_delta[1][0]  = 0;
255         s->sprite_delta[1][1]  = a;
256         ctx->sprite_shift[0]   =
257         ctx->sprite_shift[1]   = 0;
258         break;
259     case 1:     // GMC only
260         s->sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0];
261         s->sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1];
262         s->sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) -
263                                  a * (vop_ref[0][0] / 2);
264         s->sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) -
265                                  a * (vop_ref[0][1] / 2);
266         s->sprite_delta[0][0]  = a;
267         s->sprite_delta[0][1]  =
268         s->sprite_delta[1][0]  = 0;
269         s->sprite_delta[1][1]  = a;
270         ctx->sprite_shift[0]   =
271         ctx->sprite_shift[1]   = 0;
272         break;
273     case 2:
274         s->sprite_offset[0][0] = (sprite_ref[0][0] << (alpha + rho)) +
275                                  (-r * sprite_ref[0][0] + virtual_ref[0][0]) *
276                                  (-vop_ref[0][0]) +
277                                  (r * sprite_ref[0][1] - virtual_ref[0][1]) *
278                                  (-vop_ref[0][1]) + (1 << (alpha + rho - 1));
279         s->sprite_offset[0][1] = (sprite_ref[0][1] << (alpha + rho)) +
280                                  (-r * sprite_ref[0][1] + virtual_ref[0][1]) *
281                                  (-vop_ref[0][0]) +
282                                  (-r * sprite_ref[0][0] + virtual_ref[0][0]) *
283                                  (-vop_ref[0][1]) + (1 << (alpha + rho - 1));
284         s->sprite_offset[1][0] = ((-r * sprite_ref[0][0] + virtual_ref[0][0]) *
285                                   (-2 * vop_ref[0][0] + 1) +
286                                   (r * sprite_ref[0][1] - virtual_ref[0][1]) *
287                                   (-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
288                                   sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1)));
289         s->sprite_offset[1][1] = ((-r * sprite_ref[0][1] + virtual_ref[0][1]) *
290                                   (-2 * vop_ref[0][0] + 1) +
291                                   (-r * sprite_ref[0][0] + virtual_ref[0][0]) *
292                                   (-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
293                                   sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1)));
294         s->sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
295         s->sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]);
296         s->sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]);
297         s->sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
298
299         ctx->sprite_shift[0]  = alpha + rho;
300         ctx->sprite_shift[1]  = alpha + rho + 2;
301         break;
302     case 3:
303         min_ab = FFMIN(alpha, beta);
304         w3     = w2 >> min_ab;
305         h3     = h2 >> min_ab;
306         s->sprite_offset[0][0] = (sprite_ref[0][0] << (alpha + beta + rho - min_ab)) +
307                                  (-r * sprite_ref[0][0] + virtual_ref[0][0]) *
308                                  h3 * (-vop_ref[0][0]) +
309                                  (-r * sprite_ref[0][0] + virtual_ref[1][0]) *
310                                  w3 * (-vop_ref[0][1]) +
311                                  (1 << (alpha + beta + rho - min_ab - 1));
312         s->sprite_offset[0][1] = (sprite_ref[0][1] << (alpha + beta + rho - min_ab)) +
313                                  (-r * sprite_ref[0][1] + virtual_ref[0][1]) *
314                                  h3 * (-vop_ref[0][0]) +
315                                  (-r * sprite_ref[0][1] + virtual_ref[1][1]) *
316                                  w3 * (-vop_ref[0][1]) +
317                                  (1 << (alpha + beta + rho - min_ab - 1));
318         s->sprite_offset[1][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]) *
319                                  h3 * (-2 * vop_ref[0][0] + 1) +
320                                  (-r * sprite_ref[0][0] + virtual_ref[1][0]) *
321                                  w3 * (-2 * vop_ref[0][1] + 1) + 2 * w2 * h3 *
322                                  r * sprite_ref[0][0] - 16 * w2 * h3 +
323                                  (1 << (alpha + beta + rho - min_ab + 1));
324         s->sprite_offset[1][1] = (-r * sprite_ref[0][1] + virtual_ref[0][1]) *
325                                  h3 * (-2 * vop_ref[0][0] + 1) +
326                                  (-r * sprite_ref[0][1] + virtual_ref[1][1]) *
327                                  w3 * (-2 * vop_ref[0][1] + 1) + 2 * w2 * h3 *
328                                  r * sprite_ref[0][1] - 16 * w2 * h3 +
329                                  (1 << (alpha + beta + rho - min_ab + 1));
330         s->sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3;
331         s->sprite_delta[0][1] = (-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3;
332         s->sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3;
333         s->sprite_delta[1][1] = (-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3;
334
335         ctx->sprite_shift[0]  = alpha + beta + rho - min_ab;
336         ctx->sprite_shift[1]  = alpha + beta + rho - min_ab + 2;
337         break;
338     }
339     /* try to simplify the situation */
340     if (s->sprite_delta[0][0] == a << ctx->sprite_shift[0] &&
341         s->sprite_delta[0][1] == 0 &&
342         s->sprite_delta[1][0] == 0 &&
343         s->sprite_delta[1][1] == a << ctx->sprite_shift[0]) {
344         s->sprite_offset[0][0] >>= ctx->sprite_shift[0];
345         s->sprite_offset[0][1] >>= ctx->sprite_shift[0];
346         s->sprite_offset[1][0] >>= ctx->sprite_shift[1];
347         s->sprite_offset[1][1] >>= ctx->sprite_shift[1];
348         s->sprite_delta[0][0] = a;
349         s->sprite_delta[0][1] = 0;
350         s->sprite_delta[1][0] = 0;
351         s->sprite_delta[1][1] = a;
352         ctx->sprite_shift[0] = 0;
353         ctx->sprite_shift[1] = 0;
354         s->real_sprite_warping_points = 1;
355     } else {
356         int shift_y = 16 - ctx->sprite_shift[0];
357         int shift_c = 16 - ctx->sprite_shift[1];
358         for (i = 0; i < 2; i++) {
359             s->sprite_offset[0][i] <<= shift_y;
360             s->sprite_offset[1][i] <<= shift_c;
361             s->sprite_delta[0][i]  <<= shift_y;
362             s->sprite_delta[1][i]  <<= shift_y;
363             ctx->sprite_shift[i]     = 16;
364         }
365         s->real_sprite_warping_points = ctx->num_sprite_warping_points;
366     }
367
368     return 0;
369 }
370
371 /**
372  * Decode the next video packet.
373  * @return <0 if something went wrong
374  */
375 int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx)
376 {
377     MpegEncContext *s = &ctx->m;
378
379     int mb_num_bits      = av_log2(s->mb_num - 1) + 1;
380     int header_extension = 0, mb_num, len;
381
382     /* is there enough space left for a video packet + header */
383     if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20)
384         return -1;
385
386     for (len = 0; len < 32; len++)
387         if (get_bits1(&s->gb))
388             break;
389
390     if (len != ff_mpeg4_get_video_packet_prefix_length(s)) {
391         av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
392         return -1;
393     }
394
395     if (ctx->shape != RECT_SHAPE) {
396         header_extension = get_bits1(&s->gb);
397         // FIXME more stuff here
398     }
399
400     mb_num = get_bits(&s->gb, mb_num_bits);
401     if (mb_num >= s->mb_num) {
402         av_log(s->avctx, AV_LOG_ERROR,
403                "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
404         return -1;
405     }
406     if (s->pict_type == AV_PICTURE_TYPE_B) {
407         int mb_x = 0, mb_y = 0;
408
409         while (s->next_picture.mbskip_table[s->mb_index2xy[mb_num]]) {
410             if (!mb_x)
411                 ff_thread_await_progress(&s->next_picture_ptr->tf, mb_y++, 0);
412             mb_num++;
413             if (++mb_x == s->mb_width)
414                 mb_x = 0;
415         }
416         if (mb_num >= s->mb_num)
417             return -1;  // slice contains just skipped MBs (already decoded)
418     }
419
420     s->mb_x = mb_num % s->mb_width;
421     s->mb_y = mb_num / s->mb_width;
422
423     if (ctx->shape != BIN_ONLY_SHAPE) {
424         int qscale = get_bits(&s->gb, s->quant_precision);
425         if (qscale)
426             s->chroma_qscale = s->qscale = qscale;
427     }
428
429     if (ctx->shape == RECT_SHAPE)
430         header_extension = get_bits1(&s->gb);
431
432     if (header_extension) {
433         int time_incr = 0;
434
435         while (get_bits1(&s->gb) != 0)
436             time_incr++;
437
438         check_marker(&s->gb, "before time_increment in video packed header");
439         skip_bits(&s->gb, ctx->time_increment_bits);      /* time_increment */
440         check_marker(&s->gb, "before vop_coding_type in video packed header");
441
442         skip_bits(&s->gb, 2); /* vop coding type */
443         // FIXME not rect stuff here
444
445         if (ctx->shape != BIN_ONLY_SHAPE) {
446             skip_bits(&s->gb, 3); /* intra dc vlc threshold */
447             // FIXME don't just ignore everything
448             if (s->pict_type == AV_PICTURE_TYPE_S &&
449                 ctx->vol_sprite_usage == GMC_SPRITE) {
450                 if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0)
451                     return AVERROR_INVALIDDATA;
452                 av_log(s->avctx, AV_LOG_ERROR, "untested\n");
453             }
454
455             // FIXME reduced res stuff here
456
457             if (s->pict_type != AV_PICTURE_TYPE_I) {
458                 int f_code = get_bits(&s->gb, 3);       /* fcode_for */
459                 if (f_code == 0)
460                     av_log(s->avctx, AV_LOG_ERROR,
461                            "Error, video packet header damaged (f_code=0)\n");
462             }
463             if (s->pict_type == AV_PICTURE_TYPE_B) {
464                 int b_code = get_bits(&s->gb, 3);
465                 if (b_code == 0)
466                     av_log(s->avctx, AV_LOG_ERROR,
467                            "Error, video packet header damaged (b_code=0)\n");
468             }
469         }
470     }
471     // FIXME new-pred stuff
472
473     return 0;
474 }
475
476 /**
477  * Get the average motion vector for a GMC MB.
478  * @param n either 0 for the x component or 1 for y
479  * @return the average MV for a GMC MB
480  */
481 static inline int get_amv(Mpeg4DecContext *ctx, int n)
482 {
483     MpegEncContext *s = &ctx->m;
484     int x, y, mb_v, sum, dx, dy, shift;
485     int len     = 1 << (s->f_code + 4);
486     const int a = s->sprite_warping_accuracy;
487
488     if (s->workaround_bugs & FF_BUG_AMV)
489         len >>= s->quarter_sample;
490
491     if (s->real_sprite_warping_points == 1) {
492         if (ctx->divx_version == 500 && ctx->divx_build == 413)
493             sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample));
494         else
495             sum = RSHIFT(s->sprite_offset[0][n] << s->quarter_sample, a);
496     } else {
497         dx    = s->sprite_delta[n][0];
498         dy    = s->sprite_delta[n][1];
499         shift = ctx->sprite_shift[0];
500         if (n)
501             dy -= 1 << (shift + a + 1);
502         else
503             dx -= 1 << (shift + a + 1);
504         mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16;
505
506         sum = 0;
507         for (y = 0; y < 16; y++) {
508             int v;
509
510             v = mb_v + dy * y;
511             // FIXME optimize
512             for (x = 0; x < 16; x++) {
513                 sum += v >> shift;
514                 v   += dx;
515             }
516         }
517         sum = RSHIFT(sum, a + 8 - s->quarter_sample);
518     }
519
520     if (sum < -len)
521         sum = -len;
522     else if (sum >= len)
523         sum = len - 1;
524
525     return sum;
526 }
527
528 /**
529  * Decode the dc value.
530  * @param n block index (0-3 are luma, 4-5 are chroma)
531  * @param dir_ptr the prediction direction will be stored here
532  * @return the quantized dc
533  */
534 static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr)
535 {
536     int level, code;
537
538     if (n < 4)
539         code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
540     else
541         code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
542
543     if (code < 0 || code > 9 /* && s->nbit < 9 */) {
544         av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
545         return -1;
546     }
547
548     if (code == 0) {
549         level = 0;
550     } else {
551         if (IS_3IV1) {
552             if (code == 1)
553                 level = 2 * get_bits1(&s->gb) - 1;
554             else {
555                 if (get_bits1(&s->gb))
556                     level = get_bits(&s->gb, code - 1) + (1 << (code - 1));
557                 else
558                     level = -get_bits(&s->gb, code - 1) - (1 << (code - 1));
559             }
560         } else {
561             level = get_xbits(&s->gb, code);
562         }
563
564         if (code > 8) {
565             if (get_bits1(&s->gb) == 0) { /* marker */
566                 if (s->err_recognition & AV_EF_BITSTREAM) {
567                     av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
568                     return -1;
569                 }
570             }
571         }
572     }
573
574     return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
575 }
576
577 /**
578  * Decode first partition.
579  * @return number of MBs decoded or <0 if an error occurred
580  */
581 static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx)
582 {
583     MpegEncContext *s = &ctx->m;
584     int mb_num = 0;
585     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
586
587     /* decode first partition */
588     s->first_slice_line = 1;
589     for (; s->mb_y < s->mb_height; s->mb_y++) {
590         ff_init_block_index(s);
591         for (; s->mb_x < s->mb_width; s->mb_x++) {
592             const int xy = s->mb_x + s->mb_y * s->mb_stride;
593             int cbpc;
594             int dir = 0;
595
596             mb_num++;
597             ff_update_block_index(s);
598             if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
599                 s->first_slice_line = 0;
600
601             if (s->pict_type == AV_PICTURE_TYPE_I) {
602                 int i;
603
604                 do {
605                     if (show_bits_long(&s->gb, 19) == DC_MARKER)
606                         return mb_num - 1;
607
608                     cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
609                     if (cbpc < 0) {
610                         av_log(s->avctx, AV_LOG_ERROR,
611                                "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
612                         return -1;
613                     }
614                 } while (cbpc == 8);
615
616                 s->cbp_table[xy]               = cbpc & 3;
617                 s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
618                 s->mb_intra                    = 1;
619
620                 if (cbpc & 4)
621                     ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
622
623                 s->current_picture.qscale_table[xy] = s->qscale;
624
625                 s->mbintra_table[xy] = 1;
626                 for (i = 0; i < 6; i++) {
627                     int dc_pred_dir;
628                     int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
629                     if (dc < 0) {
630                         av_log(s->avctx, AV_LOG_ERROR,
631                                "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
632                         return -1;
633                     }
634                     dir <<= 1;
635                     if (dc_pred_dir)
636                         dir |= 1;
637                 }
638                 s->pred_dir_table[xy] = dir;
639             } else { /* P/S_TYPE */
640                 int mx, my, pred_x, pred_y, bits;
641                 int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]];
642                 const int stride       = s->b8_stride * 2;
643
644 try_again:
645                 bits = show_bits(&s->gb, 17);
646                 if (bits == MOTION_MARKER)
647                     return mb_num - 1;
648
649                 skip_bits1(&s->gb);
650                 if (bits & 0x10000) {
651                     /* skip mb */
652                     if (s->pict_type == AV_PICTURE_TYPE_S &&
653                         ctx->vol_sprite_usage == GMC_SPRITE) {
654                         s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
655                                                          MB_TYPE_16x16 |
656                                                          MB_TYPE_GMC   |
657                                                          MB_TYPE_L0;
658                         mx = get_amv(ctx, 0);
659                         my = get_amv(ctx, 1);
660                     } else {
661                         s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
662                                                          MB_TYPE_16x16 |
663                                                          MB_TYPE_L0;
664                         mx = my = 0;
665                     }
666                     mot_val[0]          =
667                     mot_val[2]          =
668                     mot_val[0 + stride] =
669                     mot_val[2 + stride] = mx;
670                     mot_val[1]          =
671                     mot_val[3]          =
672                     mot_val[1 + stride] =
673                     mot_val[3 + stride] = my;
674
675                     if (s->mbintra_table[xy])
676                         ff_clean_intra_table_entries(s);
677                     continue;
678                 }
679
680                 cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
681                 if (cbpc < 0) {
682                     av_log(s->avctx, AV_LOG_ERROR,
683                            "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
684                     return -1;
685                 }
686                 if (cbpc == 20)
687                     goto try_again;
688
689                 s->cbp_table[xy] = cbpc & (8 + 3);  // 8 is dquant
690
691                 s->mb_intra = ((cbpc & 4) != 0);
692
693                 if (s->mb_intra) {
694                     s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
695                     s->mbintra_table[xy] = 1;
696                     mot_val[0]          =
697                     mot_val[2]          =
698                     mot_val[0 + stride] =
699                     mot_val[2 + stride] = 0;
700                     mot_val[1]          =
701                     mot_val[3]          =
702                     mot_val[1 + stride] =
703                     mot_val[3 + stride] = 0;
704                 } else {
705                     if (s->mbintra_table[xy])
706                         ff_clean_intra_table_entries(s);
707
708                     if (s->pict_type == AV_PICTURE_TYPE_S &&
709                         ctx->vol_sprite_usage == GMC_SPRITE &&
710                         (cbpc & 16) == 0)
711                         s->mcsel = get_bits1(&s->gb);
712                     else
713                         s->mcsel = 0;
714
715                     if ((cbpc & 16) == 0) {
716                         /* 16x16 motion prediction */
717
718                         ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
719                         if (!s->mcsel) {
720                             mx = ff_h263_decode_motion(s, pred_x, s->f_code);
721                             if (mx >= 0xffff)
722                                 return -1;
723
724                             my = ff_h263_decode_motion(s, pred_y, s->f_code);
725                             if (my >= 0xffff)
726                                 return -1;
727                             s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
728                                                              MB_TYPE_L0;
729                         } else {
730                             mx = get_amv(ctx, 0);
731                             my = get_amv(ctx, 1);
732                             s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
733                                                              MB_TYPE_GMC   |
734                                                              MB_TYPE_L0;
735                         }
736
737                         mot_val[0]          =
738                         mot_val[2]          =
739                         mot_val[0 + stride] =
740                         mot_val[2 + stride] = mx;
741                         mot_val[1]          =
742                         mot_val[3]          =
743                         mot_val[1 + stride] =
744                         mot_val[3 + stride] = my;
745                     } else {
746                         int i;
747                         s->current_picture.mb_type[xy] = MB_TYPE_8x8 |
748                                                          MB_TYPE_L0;
749                         for (i = 0; i < 4; i++) {
750                             int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
751                             mx = ff_h263_decode_motion(s, pred_x, s->f_code);
752                             if (mx >= 0xffff)
753                                 return -1;
754
755                             my = ff_h263_decode_motion(s, pred_y, s->f_code);
756                             if (my >= 0xffff)
757                                 return -1;
758                             mot_val[0] = mx;
759                             mot_val[1] = my;
760                         }
761                     }
762                 }
763             }
764         }
765         s->mb_x = 0;
766     }
767
768     return mb_num;
769 }
770
771 /**
772  * decode second partition.
773  * @return <0 if an error occurred
774  */
775 static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count)
776 {
777     int mb_num = 0;
778     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
779
780     s->mb_x = s->resync_mb_x;
781     s->first_slice_line = 1;
782     for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) {
783         ff_init_block_index(s);
784         for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) {
785             const int xy = s->mb_x + s->mb_y * s->mb_stride;
786
787             mb_num++;
788             ff_update_block_index(s);
789             if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
790                 s->first_slice_line = 0;
791
792             if (s->pict_type == AV_PICTURE_TYPE_I) {
793                 int ac_pred = get_bits1(&s->gb);
794                 int cbpy    = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
795                 if (cbpy < 0) {
796                     av_log(s->avctx, AV_LOG_ERROR,
797                            "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
798                     return -1;
799                 }
800
801                 s->cbp_table[xy]               |= cbpy << 2;
802                 s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
803             } else { /* P || S_TYPE */
804                 if (IS_INTRA(s->current_picture.mb_type[xy])) {
805                     int i;
806                     int dir     = 0;
807                     int ac_pred = get_bits1(&s->gb);
808                     int cbpy    = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
809
810                     if (cbpy < 0) {
811                         av_log(s->avctx, AV_LOG_ERROR,
812                                "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
813                         return -1;
814                     }
815
816                     if (s->cbp_table[xy] & 8)
817                         ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
818                     s->current_picture.qscale_table[xy] = s->qscale;
819
820                     for (i = 0; i < 6; i++) {
821                         int dc_pred_dir;
822                         int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
823                         if (dc < 0) {
824                             av_log(s->avctx, AV_LOG_ERROR,
825                                    "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
826                             return -1;
827                         }
828                         dir <<= 1;
829                         if (dc_pred_dir)
830                             dir |= 1;
831                     }
832                     s->cbp_table[xy]               &= 3;  // remove dquant
833                     s->cbp_table[xy]               |= cbpy << 2;
834                     s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
835                     s->pred_dir_table[xy]           = dir;
836                 } else if (IS_SKIP(s->current_picture.mb_type[xy])) {
837                     s->current_picture.qscale_table[xy] = s->qscale;
838                     s->cbp_table[xy]                    = 0;
839                 } else {
840                     int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
841
842                     if (cbpy < 0) {
843                         av_log(s->avctx, AV_LOG_ERROR,
844                                "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
845                         return -1;
846                     }
847
848                     if (s->cbp_table[xy] & 8)
849                         ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
850                     s->current_picture.qscale_table[xy] = s->qscale;
851
852                     s->cbp_table[xy] &= 3;  // remove dquant
853                     s->cbp_table[xy] |= (cbpy ^ 0xf) << 2;
854                 }
855             }
856         }
857         if (mb_num >= mb_count)
858             return 0;
859         s->mb_x = 0;
860     }
861     return 0;
862 }
863
864 /**
865  * Decode the first and second partition.
866  * @return <0 if error (and sets error type in the error_status_table)
867  */
868 int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx)
869 {
870     MpegEncContext *s = &ctx->m;
871     int mb_num;
872     const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR;
873     const int part_a_end   = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END   | ER_MV_END)   : ER_MV_END;
874
875     mb_num = mpeg4_decode_partition_a(ctx);
876     if (mb_num < 0) {
877         ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
878                         s->mb_x, s->mb_y, part_a_error);
879         return -1;
880     }
881
882     if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) {
883         av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
884         ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
885                         s->mb_x, s->mb_y, part_a_error);
886         return -1;
887     }
888
889     s->mb_num_left = mb_num;
890
891     if (s->pict_type == AV_PICTURE_TYPE_I) {
892         while (show_bits(&s->gb, 9) == 1)
893             skip_bits(&s->gb, 9);
894         if (get_bits_long(&s->gb, 19) != DC_MARKER) {
895             av_log(s->avctx, AV_LOG_ERROR,
896                    "marker missing after first I partition at %d %d\n",
897                    s->mb_x, s->mb_y);
898             return -1;
899         }
900     } else {
901         while (show_bits(&s->gb, 10) == 1)
902             skip_bits(&s->gb, 10);
903         if (get_bits(&s->gb, 17) != MOTION_MARKER) {
904             av_log(s->avctx, AV_LOG_ERROR,
905                    "marker missing after first P partition at %d %d\n",
906                    s->mb_x, s->mb_y);
907             return -1;
908         }
909     }
910     ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
911                     s->mb_x - 1, s->mb_y, part_a_end);
912
913     if (mpeg4_decode_partition_b(s, mb_num) < 0) {
914         if (s->pict_type == AV_PICTURE_TYPE_P)
915             ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
916                             s->mb_x, s->mb_y, ER_DC_ERROR);
917         return -1;
918     } else {
919         if (s->pict_type == AV_PICTURE_TYPE_P)
920             ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
921                             s->mb_x - 1, s->mb_y, ER_DC_END);
922     }
923
924     return 0;
925 }
926
927 /**
928  * Decode a block.
929  * @return <0 if an error occurred
930  */
931 static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block,
932                                      int n, int coded, int intra, int rvlc)
933 {
934     MpegEncContext *s = &ctx->m;
935     int level, i, last, run, qmul, qadd, dc_pred_dir;
936     RLTable *rl;
937     RL_VLC_ELEM *rl_vlc;
938     const uint8_t *scan_table;
939
940     // Note intra & rvlc should be optimized away if this is inlined
941
942     if (intra) {
943         if (ctx->use_intra_dc_vlc) {
944             /* DC coef */
945             if (s->partitioned_frame) {
946                 level = s->dc_val[0][s->block_index[n]];
947                 if (n < 4)
948                     level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale);
949                 else
950                     level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale);
951                 dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32;
952             } else {
953                 level = mpeg4_decode_dc(s, n, &dc_pred_dir);
954                 if (level < 0)
955                     return -1;
956             }
957             block[0] = level;
958             i        = 0;
959         } else {
960             i = -1;
961             ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
962         }
963         if (!coded)
964             goto not_coded;
965
966         if (rvlc) {
967             rl     = &ff_rvlc_rl_intra;
968             rl_vlc = ff_rvlc_rl_intra.rl_vlc[0];
969         } else {
970             rl     = &ff_mpeg4_rl_intra;
971             rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
972         }
973         if (s->ac_pred) {
974             if (dc_pred_dir == 0)
975                 scan_table = s->intra_v_scantable.permutated;  /* left */
976             else
977                 scan_table = s->intra_h_scantable.permutated;  /* top */
978         } else {
979             scan_table = s->intra_scantable.permutated;
980         }
981         qmul = 1;
982         qadd = 0;
983     } else {
984         i = -1;
985         if (!coded) {
986             s->block_last_index[n] = i;
987             return 0;
988         }
989         if (rvlc)
990             rl = &ff_rvlc_rl_inter;
991         else
992             rl = &ff_h263_rl_inter;
993
994         scan_table = s->intra_scantable.permutated;
995
996         if (s->mpeg_quant) {
997             qmul = 1;
998             qadd = 0;
999             if (rvlc)
1000                 rl_vlc = ff_rvlc_rl_inter.rl_vlc[0];
1001             else
1002                 rl_vlc = ff_h263_rl_inter.rl_vlc[0];
1003         } else {
1004             qmul = s->qscale << 1;
1005             qadd = (s->qscale - 1) | 1;
1006             if (rvlc)
1007                 rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale];
1008             else
1009                 rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
1010         }
1011     }
1012     {
1013         OPEN_READER(re, &s->gb);
1014         for (;;) {
1015             UPDATE_CACHE(re, &s->gb);
1016             GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
1017             if (level == 0) {
1018                 /* escape */
1019                 if (rvlc) {
1020                     if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1021                         av_log(s->avctx, AV_LOG_ERROR,
1022                                "1. marker bit missing in rvlc esc\n");
1023                         return -1;
1024                     }
1025                     SKIP_CACHE(re, &s->gb, 1);
1026
1027                     last = SHOW_UBITS(re, &s->gb, 1);
1028                     SKIP_CACHE(re, &s->gb, 1);
1029                     run = SHOW_UBITS(re, &s->gb, 6);
1030                     SKIP_COUNTER(re, &s->gb, 1 + 1 + 6);
1031                     UPDATE_CACHE(re, &s->gb);
1032
1033                     if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1034                         av_log(s->avctx, AV_LOG_ERROR,
1035                                "2. marker bit missing in rvlc esc\n");
1036                         return -1;
1037                     }
1038                     SKIP_CACHE(re, &s->gb, 1);
1039
1040                     level = SHOW_UBITS(re, &s->gb, 11);
1041                     SKIP_CACHE(re, &s->gb, 11);
1042
1043                     if (SHOW_UBITS(re, &s->gb, 5) != 0x10) {
1044                         av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
1045                         return -1;
1046                     }
1047                     SKIP_CACHE(re, &s->gb, 5);
1048
1049                     level = level * qmul + qadd;
1050                     level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1051                     SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1);
1052
1053                     i += run + 1;
1054                     if (last)
1055                         i += 192;
1056                 } else {
1057                     int cache;
1058                     cache = GET_CACHE(re, &s->gb);
1059
1060                     if (IS_3IV1)
1061                         cache ^= 0xC0000000;
1062
1063                     if (cache & 0x80000000) {
1064                         if (cache & 0x40000000) {
1065                             /* third escape */
1066                             SKIP_CACHE(re, &s->gb, 2);
1067                             last = SHOW_UBITS(re, &s->gb, 1);
1068                             SKIP_CACHE(re, &s->gb, 1);
1069                             run = SHOW_UBITS(re, &s->gb, 6);
1070                             SKIP_COUNTER(re, &s->gb, 2 + 1 + 6);
1071                             UPDATE_CACHE(re, &s->gb);
1072
1073                             if (IS_3IV1) {
1074                                 level = SHOW_SBITS(re, &s->gb, 12);
1075                                 LAST_SKIP_BITS(re, &s->gb, 12);
1076                             } else {
1077                                 if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1078                                     av_log(s->avctx, AV_LOG_ERROR,
1079                                            "1. marker bit missing in 3. esc\n");
1080                                     return -1;
1081                                 }
1082                                 SKIP_CACHE(re, &s->gb, 1);
1083
1084                                 level = SHOW_SBITS(re, &s->gb, 12);
1085                                 SKIP_CACHE(re, &s->gb, 12);
1086
1087                                 if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1088                                     av_log(s->avctx, AV_LOG_ERROR,
1089                                            "2. marker bit missing in 3. esc\n");
1090                                     return -1;
1091                                 }
1092
1093                                 SKIP_COUNTER(re, &s->gb, 1 + 12 + 1);
1094                             }
1095
1096                             if (level > 0)
1097                                 level = level * qmul + qadd;
1098                             else
1099                                 level = level * qmul - qadd;
1100
1101                             if ((unsigned)(level + 2048) > 4095) {
1102                                 if (s->err_recognition & AV_EF_BITSTREAM) {
1103                                     if (level > 2560 || level < -2560) {
1104                                         av_log(s->avctx, AV_LOG_ERROR,
1105                                                "|level| overflow in 3. esc, qp=%d\n",
1106                                                s->qscale);
1107                                         return -1;
1108                                     }
1109                                 }
1110                                 level = level < 0 ? -2048 : 2047;
1111                             }
1112
1113                             i += run + 1;
1114                             if (last)
1115                                 i += 192;
1116                         } else {
1117                             /* second escape */
1118                             SKIP_BITS(re, &s->gb, 2);
1119                             GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
1120                             i    += run + rl->max_run[run >> 7][level / qmul] + 1;  // FIXME opt indexing
1121                             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1122                             LAST_SKIP_BITS(re, &s->gb, 1);
1123                         }
1124                     } else {
1125                         /* first escape */
1126                         SKIP_BITS(re, &s->gb, 1);
1127                         GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
1128                         i    += run;
1129                         level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul;  // FIXME opt indexing
1130                         level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1131                         LAST_SKIP_BITS(re, &s->gb, 1);
1132                     }
1133                 }
1134             } else {
1135                 i    += run;
1136                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1137                 LAST_SKIP_BITS(re, &s->gb, 1);
1138             }
1139             if (i > 62) {
1140                 i -= 192;
1141                 if (i & (~63)) {
1142                     av_log(s->avctx, AV_LOG_ERROR,
1143                            "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1144                     return -1;
1145                 }
1146
1147                 block[scan_table[i]] = level;
1148                 break;
1149             }
1150
1151             block[scan_table[i]] = level;
1152         }
1153         CLOSE_READER(re, &s->gb);
1154     }
1155
1156 not_coded:
1157     if (intra) {
1158         if (!ctx->use_intra_dc_vlc) {
1159             block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
1160
1161             i -= i >> 31;  // if (i == -1) i = 0;
1162         }
1163
1164         ff_mpeg4_pred_ac(s, block, n, dc_pred_dir);
1165         if (s->ac_pred)
1166             i = 63;  // FIXME not optimal
1167     }
1168     s->block_last_index[n] = i;
1169     return 0;
1170 }
1171
1172 /**
1173  * decode partition C of one MB.
1174  * @return <0 if an error occurred
1175  */
1176 static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64])
1177 {
1178     Mpeg4DecContext *ctx = (Mpeg4DecContext *)s;
1179     int cbp, mb_type;
1180     const int xy = s->mb_x + s->mb_y * s->mb_stride;
1181
1182     mb_type = s->current_picture.mb_type[xy];
1183     cbp     = s->cbp_table[xy];
1184
1185     ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
1186
1187     if (s->current_picture.qscale_table[xy] != s->qscale)
1188         ff_set_qscale(s, s->current_picture.qscale_table[xy]);
1189
1190     if (s->pict_type == AV_PICTURE_TYPE_P ||
1191         s->pict_type == AV_PICTURE_TYPE_S) {
1192         int i;
1193         for (i = 0; i < 4; i++) {
1194             s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
1195             s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
1196         }
1197         s->mb_intra = IS_INTRA(mb_type);
1198
1199         if (IS_SKIP(mb_type)) {
1200             /* skip mb */
1201             for (i = 0; i < 6; i++)
1202                 s->block_last_index[i] = -1;
1203             s->mv_dir  = MV_DIR_FORWARD;
1204             s->mv_type = MV_TYPE_16X16;
1205             if (s->pict_type == AV_PICTURE_TYPE_S
1206                 && ctx->vol_sprite_usage == GMC_SPRITE) {
1207                 s->mcsel      = 1;
1208                 s->mb_skipped = 0;
1209             } else {
1210                 s->mcsel      = 0;
1211                 s->mb_skipped = 1;
1212             }
1213         } else if (s->mb_intra) {
1214             s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
1215         } else if (!s->mb_intra) {
1216             // s->mcsel = 0;  // FIXME do we need to init that?
1217
1218             s->mv_dir = MV_DIR_FORWARD;
1219             if (IS_8X8(mb_type)) {
1220                 s->mv_type = MV_TYPE_8X8;
1221             } else {
1222                 s->mv_type = MV_TYPE_16X16;
1223             }
1224         }
1225     } else { /* I-Frame */
1226         s->mb_intra = 1;
1227         s->ac_pred  = IS_ACPRED(s->current_picture.mb_type[xy]);
1228     }
1229
1230     if (!IS_SKIP(mb_type)) {
1231         int i;
1232         s->bdsp.clear_blocks(s->block[0]);
1233         /* decode each block */
1234         for (i = 0; i < 6; i++) {
1235             if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) {
1236                 av_log(s->avctx, AV_LOG_ERROR,
1237                        "texture corrupted at %d %d %d\n",
1238                        s->mb_x, s->mb_y, s->mb_intra);
1239                 return -1;
1240             }
1241             cbp += cbp;
1242         }
1243     }
1244
1245     /* per-MB end of slice check */
1246     if (--s->mb_num_left <= 0) {
1247         if (mpeg4_is_resync(s))
1248             return SLICE_END;
1249         else
1250             return SLICE_NOEND;
1251     } else {
1252         if (mpeg4_is_resync(s)) {
1253             const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
1254             if (s->cbp_table[xy + delta])
1255                 return SLICE_END;
1256         }
1257         return SLICE_OK;
1258     }
1259 }
1260
1261 static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64])
1262 {
1263     Mpeg4DecContext *ctx = (Mpeg4DecContext *)s;
1264     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
1265     int16_t *mot_val;
1266     static int8_t quant_tab[4] = { -1, -2, 1, 2 };
1267     const int xy = s->mb_x + s->mb_y * s->mb_stride;
1268
1269     assert(s->h263_pred);
1270
1271     if (s->pict_type == AV_PICTURE_TYPE_P ||
1272         s->pict_type == AV_PICTURE_TYPE_S) {
1273         do {
1274             if (get_bits1(&s->gb)) {
1275                 /* skip mb */
1276                 s->mb_intra = 0;
1277                 for (i = 0; i < 6; i++)
1278                     s->block_last_index[i] = -1;
1279                 s->mv_dir  = MV_DIR_FORWARD;
1280                 s->mv_type = MV_TYPE_16X16;
1281                 if (s->pict_type == AV_PICTURE_TYPE_S &&
1282                     ctx->vol_sprite_usage == GMC_SPRITE) {
1283                     s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
1284                                                      MB_TYPE_GMC   |
1285                                                      MB_TYPE_16x16 |
1286                                                      MB_TYPE_L0;
1287                     s->mcsel       = 1;
1288                     s->mv[0][0][0] = get_amv(ctx, 0);
1289                     s->mv[0][0][1] = get_amv(ctx, 1);
1290                     s->mb_skipped  = 0;
1291                 } else {
1292                     s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
1293                                                      MB_TYPE_16x16 |
1294                                                      MB_TYPE_L0;
1295                     s->mcsel       = 0;
1296                     s->mv[0][0][0] = 0;
1297                     s->mv[0][0][1] = 0;
1298                     s->mb_skipped  = 1;
1299                 }
1300                 goto end;
1301             }
1302             cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
1303             if (cbpc < 0) {
1304                 av_log(s->avctx, AV_LOG_ERROR,
1305                        "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1306                 return -1;
1307             }
1308         } while (cbpc == 20);
1309
1310         s->bdsp.clear_blocks(s->block[0]);
1311         dquant      = cbpc & 8;
1312         s->mb_intra = ((cbpc & 4) != 0);
1313         if (s->mb_intra)
1314             goto intra;
1315
1316         if (s->pict_type == AV_PICTURE_TYPE_S &&
1317             ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0)
1318             s->mcsel = get_bits1(&s->gb);
1319         else
1320             s->mcsel = 0;
1321         cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
1322
1323         cbp = (cbpc & 3) | (cbpy << 2);
1324         if (dquant)
1325             ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1326         if ((!s->progressive_sequence) &&
1327             (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE)))
1328             s->interlaced_dct = get_bits1(&s->gb);
1329
1330         s->mv_dir = MV_DIR_FORWARD;
1331         if ((cbpc & 16) == 0) {
1332             if (s->mcsel) {
1333                 s->current_picture.mb_type[xy] = MB_TYPE_GMC   |
1334                                                  MB_TYPE_16x16 |
1335                                                  MB_TYPE_L0;
1336                 /* 16x16 global motion prediction */
1337                 s->mv_type     = MV_TYPE_16X16;
1338                 mx             = get_amv(ctx, 0);
1339                 my             = get_amv(ctx, 1);
1340                 s->mv[0][0][0] = mx;
1341                 s->mv[0][0][1] = my;
1342             } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) {
1343                 s->current_picture.mb_type[xy] = MB_TYPE_16x8 |
1344                                                  MB_TYPE_L0   |
1345                                                  MB_TYPE_INTERLACED;
1346                 /* 16x8 field motion prediction */
1347                 s->mv_type = MV_TYPE_FIELD;
1348
1349                 s->field_select[0][0] = get_bits1(&s->gb);
1350                 s->field_select[0][1] = get_bits1(&s->gb);
1351
1352                 ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1353
1354                 for (i = 0; i < 2; i++) {
1355                     mx = ff_h263_decode_motion(s, pred_x, s->f_code);
1356                     if (mx >= 0xffff)
1357                         return -1;
1358
1359                     my = ff_h263_decode_motion(s, pred_y / 2, s->f_code);
1360                     if (my >= 0xffff)
1361                         return -1;
1362
1363                     s->mv[0][i][0] = mx;
1364                     s->mv[0][i][1] = my;
1365                 }
1366             } else {
1367                 s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
1368                 /* 16x16 motion prediction */
1369                 s->mv_type = MV_TYPE_16X16;
1370                 ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1371                 mx = ff_h263_decode_motion(s, pred_x, s->f_code);
1372
1373                 if (mx >= 0xffff)
1374                     return -1;
1375
1376                 my = ff_h263_decode_motion(s, pred_y, s->f_code);
1377
1378                 if (my >= 0xffff)
1379                     return -1;
1380                 s->mv[0][0][0] = mx;
1381                 s->mv[0][0][1] = my;
1382             }
1383         } else {
1384             s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
1385             s->mv_type                     = MV_TYPE_8X8;
1386             for (i = 0; i < 4; i++) {
1387                 mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1388                 mx      = ff_h263_decode_motion(s, pred_x, s->f_code);
1389                 if (mx >= 0xffff)
1390                     return -1;
1391
1392                 my = ff_h263_decode_motion(s, pred_y, s->f_code);
1393                 if (my >= 0xffff)
1394                     return -1;
1395                 s->mv[0][i][0] = mx;
1396                 s->mv[0][i][1] = my;
1397                 mot_val[0]     = mx;
1398                 mot_val[1]     = my;
1399             }
1400         }
1401     } else if (s->pict_type == AV_PICTURE_TYPE_B) {
1402         int modb1;   // first bit of modb
1403         int modb2;   // second bit of modb
1404         int mb_type;
1405
1406         s->mb_intra = 0;  // B-frames never contain intra blocks
1407         s->mcsel    = 0;  //      ...               true gmc blocks
1408
1409         if (s->mb_x == 0) {
1410             for (i = 0; i < 2; i++) {
1411                 s->last_mv[i][0][0] =
1412                 s->last_mv[i][0][1] =
1413                 s->last_mv[i][1][0] =
1414                 s->last_mv[i][1][1] = 0;
1415             }
1416
1417             ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0);
1418         }
1419
1420         /* if we skipped it in the future P Frame than skip it now too */
1421         s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x];  // Note, skiptab=0 if last was GMC
1422
1423         if (s->mb_skipped) {
1424             /* skip mb */
1425             for (i = 0; i < 6; i++)
1426                 s->block_last_index[i] = -1;
1427
1428             s->mv_dir      = MV_DIR_FORWARD;
1429             s->mv_type     = MV_TYPE_16X16;
1430             s->mv[0][0][0] =
1431             s->mv[0][0][1] =
1432             s->mv[1][0][0] =
1433             s->mv[1][0][1] = 0;
1434             s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
1435                                              MB_TYPE_16x16 |
1436                                              MB_TYPE_L0;
1437             goto end;
1438         }
1439
1440         modb1 = get_bits1(&s->gb);
1441         if (modb1) {
1442             // like MB_TYPE_B_DIRECT but no vectors coded
1443             mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1;
1444             cbp     = 0;
1445         } else {
1446             modb2   = get_bits1(&s->gb);
1447             mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
1448             if (mb_type < 0) {
1449                 av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
1450                 return -1;
1451             }
1452             mb_type = mb_type_b_map[mb_type];
1453             if (modb2) {
1454                 cbp = 0;
1455             } else {
1456                 s->bdsp.clear_blocks(s->block[0]);
1457                 cbp = get_bits(&s->gb, 6);
1458             }
1459
1460             if ((!IS_DIRECT(mb_type)) && cbp) {
1461                 if (get_bits1(&s->gb))
1462                     ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2);
1463             }
1464
1465             if (!s->progressive_sequence) {
1466                 if (cbp)
1467                     s->interlaced_dct = get_bits1(&s->gb);
1468
1469                 if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) {
1470                     mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
1471                     mb_type &= ~MB_TYPE_16x16;
1472
1473                     if (USES_LIST(mb_type, 0)) {
1474                         s->field_select[0][0] = get_bits1(&s->gb);
1475                         s->field_select[0][1] = get_bits1(&s->gb);
1476                     }
1477                     if (USES_LIST(mb_type, 1)) {
1478                         s->field_select[1][0] = get_bits1(&s->gb);
1479                         s->field_select[1][1] = get_bits1(&s->gb);
1480                     }
1481                 }
1482             }
1483
1484             s->mv_dir = 0;
1485             if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) {
1486                 s->mv_type = MV_TYPE_16X16;
1487
1488                 if (USES_LIST(mb_type, 0)) {
1489                     s->mv_dir = MV_DIR_FORWARD;
1490
1491                     mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1492                     my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1493                     s->last_mv[0][1][0] =
1494                     s->last_mv[0][0][0] =
1495                     s->mv[0][0][0]      = mx;
1496                     s->last_mv[0][1][1] =
1497                     s->last_mv[0][0][1] =
1498                     s->mv[0][0][1]      = my;
1499                 }
1500
1501                 if (USES_LIST(mb_type, 1)) {
1502                     s->mv_dir |= MV_DIR_BACKWARD;
1503
1504                     mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1505                     my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1506                     s->last_mv[1][1][0] =
1507                     s->last_mv[1][0][0] =
1508                     s->mv[1][0][0]      = mx;
1509                     s->last_mv[1][1][1] =
1510                     s->last_mv[1][0][1] =
1511                     s->mv[1][0][1]      = my;
1512                 }
1513             } else if (!IS_DIRECT(mb_type)) {
1514                 s->mv_type = MV_TYPE_FIELD;
1515
1516                 if (USES_LIST(mb_type, 0)) {
1517                     s->mv_dir = MV_DIR_FORWARD;
1518
1519                     for (i = 0; i < 2; i++) {
1520                         mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code);
1521                         my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code);
1522                         s->last_mv[0][i][0] =
1523                         s->mv[0][i][0]      = mx;
1524                         s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2;
1525                     }
1526                 }
1527
1528                 if (USES_LIST(mb_type, 1)) {
1529                     s->mv_dir |= MV_DIR_BACKWARD;
1530
1531                     for (i = 0; i < 2; i++) {
1532                         mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code);
1533                         my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code);
1534                         s->last_mv[1][i][0] =
1535                         s->mv[1][i][0]      = mx;
1536                         s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2;
1537                     }
1538                 }
1539             }
1540         }
1541
1542         if (IS_DIRECT(mb_type)) {
1543             if (IS_SKIP(mb_type)) {
1544                 mx =
1545                 my = 0;
1546             } else {
1547                 mx = ff_h263_decode_motion(s, 0, 1);
1548                 my = ff_h263_decode_motion(s, 0, 1);
1549             }
1550
1551             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1552             mb_type  |= ff_mpeg4_set_direct_mv(s, mx, my);
1553         }
1554         s->current_picture.mb_type[xy] = mb_type;
1555     } else { /* I-Frame */
1556         do {
1557             cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
1558             if (cbpc < 0) {
1559                 av_log(s->avctx, AV_LOG_ERROR,
1560                        "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1561                 return -1;
1562             }
1563         } while (cbpc == 8);
1564
1565         dquant = cbpc & 4;
1566         s->mb_intra = 1;
1567
1568 intra:
1569         s->ac_pred = get_bits1(&s->gb);
1570         if (s->ac_pred)
1571             s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
1572         else
1573             s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
1574
1575         cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
1576         if (cbpy < 0) {
1577             av_log(s->avctx, AV_LOG_ERROR,
1578                    "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
1579             return -1;
1580         }
1581         cbp = (cbpc & 3) | (cbpy << 2);
1582
1583         ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
1584
1585         if (dquant)
1586             ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1587
1588         if (!s->progressive_sequence)
1589             s->interlaced_dct = get_bits1(&s->gb);
1590
1591         s->bdsp.clear_blocks(s->block[0]);
1592         /* decode each block */
1593         for (i = 0; i < 6; i++) {
1594             if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0)
1595                 return -1;
1596             cbp += cbp;
1597         }
1598         goto end;
1599     }
1600
1601     /* decode each block */
1602     for (i = 0; i < 6; i++) {
1603         if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0)
1604             return -1;
1605         cbp += cbp;
1606     }
1607
1608 end:
1609     /* per-MB end of slice check */
1610     if (s->codec_id == AV_CODEC_ID_MPEG4) {
1611         if (mpeg4_is_resync(s)) {
1612             const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
1613
1614             if (s->pict_type == AV_PICTURE_TYPE_B &&
1615                 s->next_picture.mbskip_table[xy + delta]) {
1616                 ff_thread_await_progress(&s->next_picture_ptr->tf,
1617                                          (s->mb_x + delta >= s->mb_width)
1618                                          ? FFMIN(s->mb_y + 1, s->mb_height - 1)
1619                                          : s->mb_y, 0);
1620             }
1621
1622             if (s->pict_type == AV_PICTURE_TYPE_B &&
1623                 s->next_picture.mbskip_table[xy + delta])
1624                 return SLICE_OK;
1625             return SLICE_END;
1626         }
1627     }
1628
1629     return SLICE_OK;
1630 }
1631
1632 static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb)
1633 {
1634     int hours, minutes, seconds;
1635     unsigned time_code = show_bits(gb, 18);
1636
1637     if (time_code & 0x40) {     /* marker_bit */
1638         hours   = time_code >> 13;
1639         minutes = time_code >> 7 & 0x3f;
1640         seconds = time_code & 0x3f;
1641         s->time_base = seconds + 60 * (minutes + 60 * hours);
1642         skip_bits(gb, 20);      /* time_code, closed_gov, broken_link */
1643     } else {
1644         av_log(s->avctx, AV_LOG_WARNING, "GOP header missing marker_bit\n");
1645     }
1646
1647     return 0;
1648 }
1649
1650 static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb)
1651 {
1652     int profile_and_level_indication;
1653
1654     profile_and_level_indication = get_bits(gb, 8);
1655
1656     s->avctx->profile = (profile_and_level_indication & 0xf0) >> 4;
1657     s->avctx->level   = (profile_and_level_indication & 0x0f);
1658
1659     // for Simple profile, level 0
1660     if (s->avctx->profile == 0 && s->avctx->level == 8) {
1661         s->avctx->level = 0;
1662     }
1663
1664     return 0;
1665 }
1666
1667 static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
1668 {
1669     MpegEncContext *s = &ctx->m;
1670     int width, height, vo_ver_id;
1671
1672     /* vol header */
1673     skip_bits(gb, 1);                   /* random access */
1674     s->vo_type = get_bits(gb, 8);
1675     if (get_bits1(gb) != 0) {           /* is_ol_id */
1676         vo_ver_id = get_bits(gb, 4);    /* vo_ver_id */
1677         skip_bits(gb, 3);               /* vo_priority */
1678     } else {
1679         vo_ver_id = 1;
1680     }
1681     s->aspect_ratio_info = get_bits(gb, 4);
1682     if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
1683         s->avctx->sample_aspect_ratio.num = get_bits(gb, 8);  // par_width
1684         s->avctx->sample_aspect_ratio.den = get_bits(gb, 8);  // par_height
1685     } else {
1686         s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
1687     }
1688
1689     if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */
1690         int chroma_format = get_bits(gb, 2);
1691         if (chroma_format != CHROMA_420)
1692             av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
1693
1694         s->low_delay = get_bits1(gb);
1695         if (get_bits1(gb)) {    /* vbv parameters */
1696             get_bits(gb, 15);   /* first_half_bitrate */
1697             skip_bits1(gb);     /* marker */
1698             get_bits(gb, 15);   /* latter_half_bitrate */
1699             skip_bits1(gb);     /* marker */
1700             get_bits(gb, 15);   /* first_half_vbv_buffer_size */
1701             skip_bits1(gb);     /* marker */
1702             get_bits(gb, 3);    /* latter_half_vbv_buffer_size */
1703             get_bits(gb, 11);   /* first_half_vbv_occupancy */
1704             skip_bits1(gb);     /* marker */
1705             get_bits(gb, 15);   /* latter_half_vbv_occupancy */
1706             skip_bits1(gb);     /* marker */
1707         }
1708     } else {
1709         /* is setting low delay flag only once the smartest thing to do?
1710          * low delay detection won't be overriden. */
1711         if (s->picture_number == 0)
1712             s->low_delay = 0;
1713     }
1714
1715     ctx->shape = get_bits(gb, 2); /* vol shape */
1716     if (ctx->shape != RECT_SHAPE)
1717         av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
1718     if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
1719         av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
1720         skip_bits(gb, 4);  /* video_object_layer_shape_extension */
1721     }
1722
1723     check_marker(gb, "before time_increment_resolution");
1724
1725     s->avctx->framerate.num = get_bits(gb, 16);
1726     if (!s->avctx->framerate.num) {
1727         av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n");
1728         return -1;
1729     }
1730
1731     ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1;
1732     if (ctx->time_increment_bits < 1)
1733         ctx->time_increment_bits = 1;
1734
1735     check_marker(gb, "before fixed_vop_rate");
1736
1737     if (get_bits1(gb) != 0)     /* fixed_vop_rate  */
1738         s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
1739     else
1740         s->avctx->framerate.den = 1;
1741
1742     ctx->t_frame = 0;
1743
1744     if (ctx->shape != BIN_ONLY_SHAPE) {
1745         if (ctx->shape == RECT_SHAPE) {
1746             skip_bits1(gb);   /* marker */
1747             width = get_bits(gb, 13);
1748             skip_bits1(gb);   /* marker */
1749             height = get_bits(gb, 13);
1750             skip_bits1(gb);   /* marker */
1751             if (width && height &&  /* they should be non zero but who knows */
1752                 !(s->width && s->codec_tag == AV_RL32("MP4S"))) {
1753                 if (s->width && s->height &&
1754                     (s->width != width || s->height != height))
1755                     s->context_reinit = 1;
1756                 s->width  = width;
1757                 s->height = height;
1758             }
1759         }
1760
1761         s->progressive_sequence  =
1762         s->progressive_frame     = get_bits1(gb) ^ 1;
1763         s->interlaced_dct        = 0;
1764         if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
1765             av_log(s->avctx, AV_LOG_INFO,           /* OBMC Disable */
1766                    "MPEG4 OBMC not supported (very likely buggy encoder)\n");
1767         if (vo_ver_id == 1)
1768             ctx->vol_sprite_usage = get_bits1(gb);    /* vol_sprite_usage */
1769         else
1770             ctx->vol_sprite_usage = get_bits(gb, 2);  /* vol_sprite_usage */
1771
1772         if (ctx->vol_sprite_usage == STATIC_SPRITE)
1773             av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
1774         if (ctx->vol_sprite_usage == STATIC_SPRITE ||
1775             ctx->vol_sprite_usage == GMC_SPRITE) {
1776             if (ctx->vol_sprite_usage == STATIC_SPRITE) {
1777                 skip_bits(gb, 13); // sprite_width
1778                 skip_bits1(gb); /* marker */
1779                 skip_bits(gb, 13); // sprite_height
1780                 skip_bits1(gb); /* marker */
1781                 skip_bits(gb, 13); // sprite_left
1782                 skip_bits1(gb); /* marker */
1783                 skip_bits(gb, 13); // sprite_top
1784                 skip_bits1(gb); /* marker */
1785             }
1786             ctx->num_sprite_warping_points = get_bits(gb, 6);
1787             if (ctx->num_sprite_warping_points > 3) {
1788                 av_log(s->avctx, AV_LOG_ERROR,
1789                        "%d sprite_warping_points\n",
1790                        ctx->num_sprite_warping_points);
1791                 ctx->num_sprite_warping_points = 0;
1792                 return -1;
1793             }
1794             s->sprite_warping_accuracy  = get_bits(gb, 2);
1795             ctx->sprite_brightness_change = get_bits1(gb);
1796             if (ctx->vol_sprite_usage == STATIC_SPRITE)
1797                 skip_bits1(gb); // low_latency_sprite
1798         }
1799         // FIXME sadct disable bit if verid!=1 && shape not rect
1800
1801         if (get_bits1(gb) == 1) {                   /* not_8_bit */
1802             s->quant_precision = get_bits(gb, 4);   /* quant_precision */
1803             if (get_bits(gb, 4) != 8)               /* bits_per_pixel */
1804                 av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
1805             if (s->quant_precision != 5)
1806                 av_log(s->avctx, AV_LOG_ERROR,
1807                        "quant precision %d\n", s->quant_precision);
1808         } else {
1809             s->quant_precision = 5;
1810         }
1811
1812         // FIXME a bunch of grayscale shape things
1813
1814         if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
1815             int i, v;
1816
1817             /* load default matrixes */
1818             for (i = 0; i < 64; i++) {
1819                 int j = s->idsp.idct_permutation[i];
1820                 v = ff_mpeg4_default_intra_matrix[i];
1821                 s->intra_matrix[j]        = v;
1822                 s->chroma_intra_matrix[j] = v;
1823
1824                 v = ff_mpeg4_default_non_intra_matrix[i];
1825                 s->inter_matrix[j]        = v;
1826                 s->chroma_inter_matrix[j] = v;
1827             }
1828
1829             /* load custom intra matrix */
1830             if (get_bits1(gb)) {
1831                 int last = 0;
1832                 for (i = 0; i < 64; i++) {
1833                     int j;
1834                     v = get_bits(gb, 8);
1835                     if (v == 0)
1836                         break;
1837
1838                     last = v;
1839                     j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
1840                     s->intra_matrix[j]        = last;
1841                     s->chroma_intra_matrix[j] = last;
1842                 }
1843
1844                 /* replicate last value */
1845                 for (; i < 64; i++) {
1846                     int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
1847                     s->intra_matrix[j]        = last;
1848                     s->chroma_intra_matrix[j] = last;
1849                 }
1850             }
1851
1852             /* load custom non intra matrix */
1853             if (get_bits1(gb)) {
1854                 int last = 0;
1855                 for (i = 0; i < 64; i++) {
1856                     int j;
1857                     v = get_bits(gb, 8);
1858                     if (v == 0)
1859                         break;
1860
1861                     last = v;
1862                     j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
1863                     s->inter_matrix[j]        = v;
1864                     s->chroma_inter_matrix[j] = v;
1865                 }
1866
1867                 /* replicate last value */
1868                 for (; i < 64; i++) {
1869                     int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
1870                     s->inter_matrix[j]        = last;
1871                     s->chroma_inter_matrix[j] = last;
1872                 }
1873             }
1874
1875             // FIXME a bunch of grayscale shape things
1876         }
1877
1878         if (vo_ver_id != 1)
1879             s->quarter_sample = get_bits1(gb);
1880         else
1881             s->quarter_sample = 0;
1882
1883         if (!get_bits1(gb)) {
1884             int pos               = get_bits_count(gb);
1885             int estimation_method = get_bits(gb, 2);
1886             if (estimation_method < 2) {
1887                 if (!get_bits1(gb)) {
1888                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* opaque */
1889                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* transparent */
1890                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_cae */
1891                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* inter_cae */
1892                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* no_update */
1893                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* upampling */
1894                 }
1895                 if (!get_bits1(gb)) {
1896                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_blocks */
1897                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter_blocks */
1898                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter4v_blocks */
1899                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* not coded blocks */
1900                 }
1901                 if (!check_marker(gb, "in complexity estimation part 1")) {
1902                     skip_bits_long(gb, pos - get_bits_count(gb));
1903                     goto no_cplx_est;
1904                 }
1905                 if (!get_bits1(gb)) {
1906                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_coeffs */
1907                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_lines */
1908                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* vlc_syms */
1909                     ctx->cplx_estimation_trash_i += 4 * get_bits1(gb);  /* vlc_bits */
1910                 }
1911                 if (!get_bits1(gb)) {
1912                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* apm */
1913                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* npm */
1914                     ctx->cplx_estimation_trash_b += 8 * get_bits1(gb);  /* interpolate_mc_q */
1915                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* forwback_mc_q */
1916                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel2 */
1917                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel4 */
1918                 }
1919                 if (!check_marker(gb, "in complexity estimation part 2")) {
1920                     skip_bits_long(gb, pos - get_bits_count(gb));
1921                     goto no_cplx_est;
1922                 }
1923                 if (estimation_method == 1) {
1924                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* sadct */
1925                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* qpel */
1926                 }
1927             } else
1928                 av_log(s->avctx, AV_LOG_ERROR,
1929                        "Invalid Complexity estimation method %d\n",
1930                        estimation_method);
1931         } else {
1932
1933 no_cplx_est:
1934             ctx->cplx_estimation_trash_i =
1935             ctx->cplx_estimation_trash_p =
1936             ctx->cplx_estimation_trash_b = 0;
1937         }
1938
1939         ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
1940
1941         s->data_partitioning = get_bits1(gb);
1942         if (s->data_partitioning)
1943             ctx->rvlc = get_bits1(gb);
1944
1945         if (vo_ver_id != 1) {
1946             ctx->new_pred = get_bits1(gb);
1947             if (ctx->new_pred) {
1948                 av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
1949                 skip_bits(gb, 2); /* requested upstream message type */
1950                 skip_bits1(gb);   /* newpred segment type */
1951             }
1952             if (get_bits1(gb)) // reduced_res_vop
1953                 av_log(s->avctx, AV_LOG_ERROR,
1954                        "reduced resolution VOP not supported\n");
1955         } else {
1956             ctx->new_pred = 0;
1957         }
1958
1959         ctx->scalability = get_bits1(gb);
1960
1961         if (ctx->scalability) {
1962             GetBitContext bak = *gb;
1963             int h_sampling_factor_n;
1964             int h_sampling_factor_m;
1965             int v_sampling_factor_n;
1966             int v_sampling_factor_m;
1967
1968             skip_bits1(gb);    // hierarchy_type
1969             skip_bits(gb, 4);  /* ref_layer_id */
1970             skip_bits1(gb);    /* ref_layer_sampling_dir */
1971             h_sampling_factor_n = get_bits(gb, 5);
1972             h_sampling_factor_m = get_bits(gb, 5);
1973             v_sampling_factor_n = get_bits(gb, 5);
1974             v_sampling_factor_m = get_bits(gb, 5);
1975             ctx->enhancement_type = get_bits1(gb);
1976
1977             if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
1978                 v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
1979                 /* illegal scalability header (VERY broken encoder),
1980                  * trying to workaround */
1981                 ctx->scalability = 0;
1982                 *gb            = bak;
1983             } else
1984                 av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
1985
1986             // bin shape stuff FIXME
1987         }
1988     }
1989
1990     return 0;
1991 }
1992
1993 /**
1994  * Decode the user data stuff in the header.
1995  * Also initializes divx/xvid/lavc_version/build.
1996  */
1997 static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
1998 {
1999     MpegEncContext *s = &ctx->m;
2000     char buf[256];
2001     int i;
2002     int e;
2003     int ver = 0, build = 0, ver2 = 0, ver3 = 0;
2004     char last;
2005
2006     for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
2007         if (show_bits(gb, 23) == 0)
2008             break;
2009         buf[i] = get_bits(gb, 8);
2010     }
2011     buf[i] = 0;
2012
2013     /* divx detection */
2014     e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
2015     if (e < 2)
2016         e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
2017     if (e >= 2) {
2018         ctx->divx_version = ver;
2019         ctx->divx_build   = build;
2020         s->divx_packed  = e == 3 && last == 'p';
2021         if (s->divx_packed && !ctx->showed_packed_warning) {
2022             av_log(s->avctx, AV_LOG_WARNING,
2023                    "Invalid and inefficient vfw-avi packed B frames detected\n");
2024             ctx->showed_packed_warning = 1;
2025         }
2026     }
2027
2028     /* libavcodec detection */
2029     e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
2030     if (e != 4)
2031         e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
2032     if (e != 4) {
2033         e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
2034         if (e > 1)
2035             build = (ver << 16) + (ver2 << 8) + ver3;
2036     }
2037     if (e != 4) {
2038         if (strcmp(buf, "ffmpeg") == 0)
2039             ctx->lavc_build = 4600;
2040     }
2041     if (e == 4)
2042         ctx->lavc_build = build;
2043
2044     /* Xvid detection */
2045     e = sscanf(buf, "XviD%d", &build);
2046     if (e == 1)
2047         ctx->xvid_build = build;
2048
2049     if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
2050         if (s->stream_codec_tag == AV_RL32("XVID") ||
2051             s->codec_tag        == AV_RL32("XVID") ||
2052             s->codec_tag        == AV_RL32("XVIX") ||
2053             s->codec_tag        == AV_RL32("RMP4") ||
2054             s->codec_tag        == AV_RL32("ZMP4") ||
2055             s->codec_tag        == AV_RL32("SIPP"))
2056             ctx->xvid_build = 0;
2057     }
2058
2059     if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
2060         if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 &&
2061             ctx->vol_control_parameters == 0)
2062             ctx->divx_version = 400;  // divx 4
2063
2064     if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
2065         ctx->divx_version =
2066         ctx->divx_build   = -1;
2067     }
2068
2069     if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0)
2070         ff_xvid_idct_init(&s->idsp, s->avctx);
2071
2072     return 0;
2073 }
2074
2075 static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
2076 {
2077     MpegEncContext *s = &ctx->m;
2078     int time_incr, time_increment;
2079
2080     s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I;        /* pict type: I = 0 , P = 1 */
2081     if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
2082         ctx->vol_control_parameters == 0 && !(s->flags & CODEC_FLAG_LOW_DELAY)) {
2083         av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n");
2084         s->low_delay = 0;
2085     }
2086
2087     s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
2088     if (s->partitioned_frame)
2089         s->decode_mb = mpeg4_decode_partitioned_mb;
2090     else
2091         s->decode_mb = mpeg4_decode_mb;
2092
2093     time_incr = 0;
2094     while (get_bits1(gb) != 0)
2095         time_incr++;
2096
2097     check_marker(gb, "before time_increment");
2098
2099     if (ctx->time_increment_bits == 0 ||
2100         !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
2101         av_log(s->avctx, AV_LOG_ERROR,
2102                "hmm, seems the headers are not complete, trying to guess time_increment_bits\n");
2103
2104         for (ctx->time_increment_bits = 1;
2105              ctx->time_increment_bits < 16;
2106              ctx->time_increment_bits++) {
2107             if (s->pict_type == AV_PICTURE_TYPE_P ||
2108                 (s->pict_type == AV_PICTURE_TYPE_S &&
2109                  ctx->vol_sprite_usage == GMC_SPRITE)) {
2110                 if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
2111                     break;
2112             } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
2113                 break;
2114         }
2115
2116         av_log(s->avctx, AV_LOG_ERROR,
2117                "my guess is %d bits ;)\n", ctx->time_increment_bits);
2118     }
2119
2120     if (IS_3IV1)
2121         time_increment = get_bits1(gb);        // FIXME investigate further
2122     else
2123         time_increment = get_bits(gb, ctx->time_increment_bits);
2124
2125     if (s->pict_type != AV_PICTURE_TYPE_B) {
2126         s->last_time_base = s->time_base;
2127         s->time_base     += time_incr;
2128         s->time = s->time_base * s->avctx->framerate.num + time_increment;
2129         if (s->workaround_bugs & FF_BUG_UMP4) {
2130             if (s->time < s->last_non_b_time) {
2131                 /* header is not mpeg-4-compatible, broken encoder,
2132                  * trying to workaround */
2133                 s->time_base++;
2134                 s->time += s->avctx->framerate.num;
2135             }
2136         }
2137         s->pp_time         = s->time - s->last_non_b_time;
2138         s->last_non_b_time = s->time;
2139     } else {
2140         s->time    = (s->last_time_base + time_incr) * s->avctx->framerate.num + time_increment;
2141         s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
2142         if (s->pp_time <= s->pb_time ||
2143             s->pp_time <= s->pp_time - s->pb_time ||
2144             s->pp_time <= 0) {
2145             /* messed up order, maybe after seeking? skipping current b-frame */
2146             return FRAME_SKIPPED;
2147         }
2148         ff_mpeg4_init_direct_mv(s);
2149
2150         if (ctx->t_frame == 0)
2151             ctx->t_frame = s->pb_time;
2152         if (ctx->t_frame == 0)
2153             ctx->t_frame = 1;  // 1/0 protection
2154         s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
2155                             ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
2156         s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
2157                             ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
2158         if (!s->progressive_sequence) {
2159             if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1)
2160                 return FRAME_SKIPPED;
2161         }
2162     }
2163
2164     check_marker(gb, "before vop_coded");
2165
2166     /* vop coded */
2167     if (get_bits1(gb) != 1) {
2168         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2169             av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
2170         return FRAME_SKIPPED;
2171     }
2172     if (ctx->shape != BIN_ONLY_SHAPE &&
2173                     (s->pict_type == AV_PICTURE_TYPE_P ||
2174                      (s->pict_type == AV_PICTURE_TYPE_S &&
2175                       ctx->vol_sprite_usage == GMC_SPRITE))) {
2176         /* rounding type for motion estimation */
2177         s->no_rounding = get_bits1(gb);
2178     } else {
2179         s->no_rounding = 0;
2180     }
2181     // FIXME reduced res stuff
2182
2183     if (ctx->shape != RECT_SHAPE) {
2184         if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
2185             skip_bits(gb, 13);  /* width */
2186             skip_bits1(gb);     /* marker */
2187             skip_bits(gb, 13);  /* height */
2188             skip_bits1(gb);     /* marker */
2189             skip_bits(gb, 13);  /* hor_spat_ref */
2190             skip_bits1(gb);     /* marker */
2191             skip_bits(gb, 13);  /* ver_spat_ref */
2192         }
2193         skip_bits1(gb);         /* change_CR_disable */
2194
2195         if (get_bits1(gb) != 0)
2196             skip_bits(gb, 8);   /* constant_alpha_value */
2197     }
2198
2199     // FIXME complexity estimation stuff
2200
2201     if (ctx->shape != BIN_ONLY_SHAPE) {
2202         skip_bits_long(gb, ctx->cplx_estimation_trash_i);
2203         if (s->pict_type != AV_PICTURE_TYPE_I)
2204             skip_bits_long(gb, ctx->cplx_estimation_trash_p);
2205         if (s->pict_type == AV_PICTURE_TYPE_B)
2206             skip_bits_long(gb, ctx->cplx_estimation_trash_b);
2207
2208         ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
2209         if (!s->progressive_sequence) {
2210             s->top_field_first = get_bits1(gb);
2211             s->alternate_scan  = get_bits1(gb);
2212         } else
2213             s->alternate_scan = 0;
2214     }
2215
2216     if (s->alternate_scan) {
2217         ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_alternate_vertical_scan);
2218         ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_alternate_vertical_scan);
2219         ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
2220         ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2221     } else {
2222         ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_zigzag_direct);
2223         ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_zigzag_direct);
2224         ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
2225         ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2226     }
2227
2228     if (s->pict_type == AV_PICTURE_TYPE_S &&
2229         (ctx->vol_sprite_usage == STATIC_SPRITE ||
2230          ctx->vol_sprite_usage == GMC_SPRITE)) {
2231         if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
2232             return AVERROR_INVALIDDATA;
2233         if (ctx->sprite_brightness_change)
2234             av_log(s->avctx, AV_LOG_ERROR,
2235                    "sprite_brightness_change not supported\n");
2236         if (ctx->vol_sprite_usage == STATIC_SPRITE)
2237             av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
2238     }
2239
2240     if (ctx->shape != BIN_ONLY_SHAPE) {
2241         s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);
2242         if (s->qscale == 0) {
2243             av_log(s->avctx, AV_LOG_ERROR,
2244                    "Error, header damaged or not MPEG4 header (qscale=0)\n");
2245             return -1;  // makes no sense to continue, as there is nothing left from the image then
2246         }
2247
2248         if (s->pict_type != AV_PICTURE_TYPE_I) {
2249             s->f_code = get_bits(gb, 3);        /* fcode_for */
2250             if (s->f_code == 0) {
2251                 av_log(s->avctx, AV_LOG_ERROR,
2252                        "Error, header damaged or not MPEG4 header (f_code=0)\n");
2253                 return -1;  // makes no sense to continue, as there is nothing left from the image then
2254             }
2255         } else
2256             s->f_code = 1;
2257
2258         if (s->pict_type == AV_PICTURE_TYPE_B) {
2259             s->b_code = get_bits(gb, 3);
2260         } else
2261             s->b_code = 1;
2262
2263         if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
2264             av_log(s->avctx, AV_LOG_DEBUG,
2265                    "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d\n",
2266                    s->qscale, s->f_code, s->b_code,
2267                    s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
2268                    gb->size_in_bits, s->progressive_sequence, s->alternate_scan,
2269                    s->top_field_first, s->quarter_sample ? "q" : "h",
2270                    s->data_partitioning, ctx->resync_marker,
2271                    ctx->num_sprite_warping_points, s->sprite_warping_accuracy,
2272                    1 - s->no_rounding, s->vo_type,
2273                    ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
2274                    ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
2275                    ctx->cplx_estimation_trash_b);
2276         }
2277
2278         if (!ctx->scalability) {
2279             if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
2280                 skip_bits1(gb);  // vop shape coding type
2281         } else {
2282             if (ctx->enhancement_type) {
2283                 int load_backward_shape = get_bits1(gb);
2284                 if (load_backward_shape)
2285                     av_log(s->avctx, AV_LOG_ERROR,
2286                            "load backward shape isn't supported\n");
2287             }
2288             skip_bits(gb, 2);  // ref_select_code
2289         }
2290     }
2291     /* detect buggy encoders which don't set the low_delay flag
2292      * (divx4/xvid/opendivx). Note we cannot detect divx5 without b-frames
2293      * easily (although it's buggy too) */
2294     if (s->vo_type == 0 && ctx->vol_control_parameters == 0 &&
2295         ctx->divx_version == -1 && s->picture_number == 0) {
2296         av_log(s->avctx, AV_LOG_WARNING,
2297                "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
2298         s->low_delay = 1;
2299     }
2300
2301     s->picture_number++;  // better than pic number==0 always ;)
2302
2303     // FIXME add short header support
2304     s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
2305     s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
2306
2307     if (s->workaround_bugs & FF_BUG_EDGE) {
2308         s->h_edge_pos = s->width;
2309         s->v_edge_pos = s->height;
2310     }
2311     return 0;
2312 }
2313
2314 /**
2315  * Decode mpeg4 headers.
2316  * @return <0 if no VOP found (or a damaged one)
2317  *         FRAME_SKIPPED if a not coded VOP is found
2318  *         0 if a VOP is found
2319  */
2320 int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
2321 {
2322     MpegEncContext *s = &ctx->m;
2323     unsigned startcode, v;
2324
2325     /* search next start code */
2326     align_get_bits(gb);
2327
2328     if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
2329         skip_bits(gb, 24);
2330         if (get_bits(gb, 8) == 0xF0)
2331             goto end;
2332     }
2333
2334     startcode = 0xff;
2335     for (;;) {
2336         if (get_bits_count(gb) >= gb->size_in_bits) {
2337             if (gb->size_in_bits == 8 &&
2338                 (ctx->divx_version >= 0 || ctx->xvid_build >= 0)) {
2339                 av_log(s->avctx, AV_LOG_WARNING, "frame skip %d\n", gb->size_in_bits);
2340                 return FRAME_SKIPPED;  // divx bug
2341             } else
2342                 return -1;  // end of stream
2343         }
2344
2345         /* use the bits after the test */
2346         v = get_bits(gb, 8);
2347         startcode = ((startcode << 8) | v) & 0xffffffff;
2348
2349         if ((startcode & 0xFFFFFF00) != 0x100)
2350             continue;  // no startcode
2351
2352         if (s->avctx->debug & FF_DEBUG_STARTCODE) {
2353             av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
2354             if (startcode <= 0x11F)
2355                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
2356             else if (startcode <= 0x12F)
2357                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
2358             else if (startcode <= 0x13F)
2359                 av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2360             else if (startcode <= 0x15F)
2361                 av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
2362             else if (startcode <= 0x1AF)
2363                 av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2364             else if (startcode == 0x1B0)
2365                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
2366             else if (startcode == 0x1B1)
2367                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
2368             else if (startcode == 0x1B2)
2369                 av_log(s->avctx, AV_LOG_DEBUG, "User Data");
2370             else if (startcode == 0x1B3)
2371                 av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
2372             else if (startcode == 0x1B4)
2373                 av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
2374             else if (startcode == 0x1B5)
2375                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
2376             else if (startcode == 0x1B6)
2377                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
2378             else if (startcode == 0x1B7)
2379                 av_log(s->avctx, AV_LOG_DEBUG, "slice start");
2380             else if (startcode == 0x1B8)
2381                 av_log(s->avctx, AV_LOG_DEBUG, "extension start");
2382             else if (startcode == 0x1B9)
2383                 av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
2384             else if (startcode == 0x1BA)
2385                 av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
2386             else if (startcode == 0x1BB)
2387                 av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
2388             else if (startcode == 0x1BC)
2389                 av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
2390             else if (startcode == 0x1BD)
2391                 av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
2392             else if (startcode == 0x1BE)
2393                 av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
2394             else if (startcode == 0x1BF)
2395                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
2396             else if (startcode == 0x1C0)
2397                 av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
2398             else if (startcode == 0x1C1)
2399                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
2400             else if (startcode == 0x1C2)
2401                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
2402             else if (startcode == 0x1C3)
2403                 av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
2404             else if (startcode <= 0x1C5)
2405                 av_log(s->avctx, AV_LOG_DEBUG, "reserved");
2406             else if (startcode <= 0x1FF)
2407                 av_log(s->avctx, AV_LOG_DEBUG, "System start");
2408             av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
2409         }
2410
2411         if (startcode >= 0x120 && startcode <= 0x12F) {
2412             if (decode_vol_header(ctx, gb) < 0)
2413                 return -1;
2414         } else if (startcode == USER_DATA_STARTCODE) {
2415             decode_user_data(ctx, gb);
2416         } else if (startcode == GOP_STARTCODE) {
2417             mpeg4_decode_gop_header(s, gb);
2418         } else if (startcode == VOS_STARTCODE) {
2419             mpeg4_decode_profile_level(s, gb);
2420         } else if (startcode == VOP_STARTCODE) {
2421             break;
2422         }
2423
2424         align_get_bits(gb);
2425         startcode = 0xff;
2426     }
2427
2428 end:
2429     if (s->flags & CODEC_FLAG_LOW_DELAY)
2430         s->low_delay = 1;
2431     s->avctx->has_b_frames = !s->low_delay;
2432
2433     if (s->workaround_bugs & FF_BUG_AUTODETECT) {
2434         if (s->codec_tag == AV_RL32("XVIX"))
2435             s->workaround_bugs |= FF_BUG_XVID_ILACE;
2436
2437         if (s->codec_tag == AV_RL32("UMP4"))
2438             s->workaround_bugs |= FF_BUG_UMP4;
2439
2440         if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
2441             s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
2442
2443         if (ctx->divx_version > 502 && ctx->divx_build < 1814)
2444             s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
2445
2446         if (ctx->xvid_build <= 3U)
2447             s->padding_bug_score = 256 * 256 * 256 * 64;
2448
2449         if (ctx->xvid_build <= 1U)
2450             s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
2451
2452         if (ctx->xvid_build <= 12U)
2453             s->workaround_bugs |= FF_BUG_EDGE;
2454
2455         if (ctx->xvid_build <= 32U)
2456             s->workaround_bugs |= FF_BUG_DC_CLIP;
2457
2458         if (ctx->lavc_build < 4653U)
2459             s->workaround_bugs |= FF_BUG_STD_QPEL;
2460
2461         if (ctx->lavc_build < 4655U)
2462             s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
2463
2464         if (ctx->lavc_build < 4670U)
2465             s->workaround_bugs |= FF_BUG_EDGE;
2466
2467         if (ctx->lavc_build <= 4712U)
2468             s->workaround_bugs |= FF_BUG_DC_CLIP;
2469
2470         if (ctx->divx_version >= 0)
2471             s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
2472
2473         if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
2474             s->padding_bug_score = 256 * 256 * 256 * 64;
2475
2476         if (ctx->divx_version < 500U)
2477             s->workaround_bugs |= FF_BUG_EDGE;
2478
2479         if (ctx->divx_version >= 0)
2480             s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
2481     }
2482
2483
2484     if (s->avctx->debug & FF_DEBUG_BUGS)
2485         av_log(s->avctx, AV_LOG_DEBUG,
2486                "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
2487                s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
2488                ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
2489
2490     return decode_vop_header(ctx, gb);
2491 }
2492
2493 int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
2494 {
2495     Mpeg4DecContext *ctx = avctx->priv_data;
2496     MpegEncContext    *s = &ctx->m;
2497
2498     /* divx 5.01+ bistream reorder stuff */
2499     if (s->divx_packed) {
2500         int current_pos     = get_bits_count(&s->gb) >> 3;
2501         int startcode_found = 0;
2502
2503         if (buf_size - current_pos > 5) {
2504             int i;
2505             for (i = current_pos; i < buf_size - 3; i++)
2506                 if (buf[i]     == 0 &&
2507                     buf[i + 1] == 0 &&
2508                     buf[i + 2] == 1 &&
2509                     buf[i + 3] == 0xB6) {
2510                     startcode_found = 1;
2511                     break;
2512                 }
2513         }
2514         if (s->gb.buffer == s->bitstream_buffer && buf_size > 7 &&
2515             ctx->xvid_build >= 0) {       // xvid style
2516             startcode_found = 1;
2517             current_pos     = 0;
2518         }
2519
2520         if (startcode_found) {
2521             av_fast_malloc(&s->bitstream_buffer,
2522                            &s->allocated_bitstream_buffer_size,
2523                            buf_size - current_pos +
2524                            FF_INPUT_BUFFER_PADDING_SIZE);
2525             if (!s->bitstream_buffer)
2526                 return AVERROR(ENOMEM);
2527             memcpy(s->bitstream_buffer, buf + current_pos,
2528                    buf_size - current_pos);
2529             s->bitstream_buffer_size = buf_size - current_pos;
2530         }
2531     }
2532
2533     return 0;
2534 }
2535
2536 static int mpeg4_update_thread_context(AVCodecContext *dst,
2537                                        const AVCodecContext *src)
2538 {
2539     Mpeg4DecContext *s = dst->priv_data;
2540     const Mpeg4DecContext *s1 = src->priv_data;
2541     int init = s->m.context_initialized;
2542
2543     int ret = ff_mpeg_update_thread_context(dst, src);
2544
2545     if (ret < 0)
2546         return ret;
2547
2548     if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0)
2549         ff_xvid_idct_init(&s->m.idsp, dst);
2550
2551     s->shape               = s1->shape;
2552     s->time_increment_bits = s1->time_increment_bits;
2553     s->xvid_build          = s1->xvid_build;
2554
2555     return 0;
2556 }
2557
2558 static av_cold int decode_init(AVCodecContext *avctx)
2559 {
2560     Mpeg4DecContext *ctx = avctx->priv_data;
2561     MpegEncContext *s = &ctx->m;
2562     int ret;
2563     static int done = 0;
2564
2565     ctx->divx_version =
2566     ctx->divx_build   =
2567     ctx->xvid_build   =
2568     ctx->lavc_build   = -1;
2569
2570     if ((ret = ff_h263_decode_init(avctx)) < 0)
2571         return ret;
2572
2573     if (!done) {
2574         done = 1;
2575
2576         ff_init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
2577         ff_init_rl(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
2578         ff_init_rl(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
2579         INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
2580         INIT_VLC_RL(ff_rvlc_rl_inter, 1072);
2581         INIT_VLC_RL(ff_rvlc_rl_intra, 1072);
2582         INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2583                         &ff_mpeg4_DCtab_lum[0][1], 2, 1,
2584                         &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
2585         INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2586                         &ff_mpeg4_DCtab_chrom[0][1], 2, 1,
2587                         &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
2588         INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2589                         &ff_sprite_trajectory_tab[0][1], 4, 2,
2590                         &ff_sprite_trajectory_tab[0][0], 4, 2, 128);
2591         INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2592                         &ff_mb_type_b_tab[0][1], 2, 1,
2593                         &ff_mb_type_b_tab[0][0], 2, 1, 16);
2594     }
2595
2596     s->h263_pred = 1;
2597     s->low_delay = 0; /* default, might be overriden in the vol header during header parsing */
2598     s->decode_mb = mpeg4_decode_mb;
2599     ctx->time_increment_bits = 4; /* default value for broken headers */
2600
2601     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
2602     avctx->internal->allocate_progress = 1;
2603
2604     return 0;
2605 }
2606
2607 static const AVProfile mpeg4_video_profiles[] = {
2608     { FF_PROFILE_MPEG4_SIMPLE,                    "Simple Profile" },
2609     { FF_PROFILE_MPEG4_SIMPLE_SCALABLE,           "Simple Scalable Profile" },
2610     { FF_PROFILE_MPEG4_CORE,                      "Core Profile" },
2611     { FF_PROFILE_MPEG4_MAIN,                      "Main Profile" },
2612     { FF_PROFILE_MPEG4_N_BIT,                     "N-bit Profile" },
2613     { FF_PROFILE_MPEG4_SCALABLE_TEXTURE,          "Scalable Texture Profile" },
2614     { FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION,     "Simple Face Animation Profile" },
2615     { FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE,    "Basic Animated Texture Profile" },
2616     { FF_PROFILE_MPEG4_HYBRID,                    "Hybrid Profile" },
2617     { FF_PROFILE_MPEG4_ADVANCED_REAL_TIME,        "Advanced Real Time Simple Profile" },
2618     { FF_PROFILE_MPEG4_CORE_SCALABLE,             "Code Scalable Profile" },
2619     { FF_PROFILE_MPEG4_ADVANCED_CODING,           "Advanced Coding Profile" },
2620     { FF_PROFILE_MPEG4_ADVANCED_CORE,             "Advanced Core Profile" },
2621     { FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE, "Advanced Scalable Texture Profile" },
2622     { FF_PROFILE_MPEG4_SIMPLE_STUDIO,             "Simple Studio Profile" },
2623     { FF_PROFILE_MPEG4_ADVANCED_SIMPLE,           "Advanced Simple Profile" },
2624 };
2625
2626 AVCodec ff_mpeg4_decoder = {
2627     .name                  = "mpeg4",
2628     .long_name             = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
2629     .type                  = AVMEDIA_TYPE_VIDEO,
2630     .id                    = AV_CODEC_ID_MPEG4,
2631     .priv_data_size        = sizeof(Mpeg4DecContext),
2632     .init                  = decode_init,
2633     .close                 = ff_h263_decode_end,
2634     .decode                = ff_h263_decode_frame,
2635     .capabilities          = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2636                              CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2637                              CODEC_CAP_FRAME_THREADS,
2638     .flush                 = ff_mpeg_flush,
2639     .pix_fmts              = ff_h263_hwaccel_pixfmt_list_420,
2640     .profiles              = NULL_IF_CONFIG_SMALL(mpeg4_video_profiles),
2641     .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context),
2642 };