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