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