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