]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpeg4videodec.c
Merge commit '0372e73f917e72c40b09270f771046fc142be4a7'
[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             s->low_delay = 0;
1759     }
1760
1761     ctx->shape = get_bits(gb, 2); /* vol shape */
1762     if (ctx->shape != RECT_SHAPE)
1763         av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
1764     if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
1765         av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
1766         skip_bits(gb, 4);  /* video_object_layer_shape_extension */
1767     }
1768
1769     check_marker(gb, "before time_increment_resolution");
1770
1771     s->avctx->framerate.num = get_bits(gb, 16);
1772     if (!s->avctx->framerate.num) {
1773         av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n");
1774         return AVERROR_INVALIDDATA;
1775     }
1776
1777     ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1;
1778     if (ctx->time_increment_bits < 1)
1779         ctx->time_increment_bits = 1;
1780
1781     check_marker(gb, "before fixed_vop_rate");
1782
1783     if (get_bits1(gb) != 0)     /* fixed_vop_rate  */
1784         s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
1785     else
1786         s->avctx->framerate.den = 1;
1787
1788     s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
1789
1790     ctx->t_frame = 0;
1791
1792     if (ctx->shape != BIN_ONLY_SHAPE) {
1793         if (ctx->shape == RECT_SHAPE) {
1794             check_marker(gb, "before width");
1795             width = get_bits(gb, 13);
1796             check_marker(gb, "before height");
1797             height = get_bits(gb, 13);
1798             check_marker(gb, "after height");
1799             if (width && height &&  /* they should be non zero but who knows */
1800                 !(s->width && s->codec_tag == AV_RL32("MP4S"))) {
1801                 if (s->width && s->height &&
1802                     (s->width != width || s->height != height))
1803                     s->context_reinit = 1;
1804                 s->width  = width;
1805                 s->height = height;
1806             }
1807         }
1808
1809         s->progressive_sequence  =
1810         s->progressive_frame     = get_bits1(gb) ^ 1;
1811         s->interlaced_dct        = 0;
1812         if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
1813             av_log(s->avctx, AV_LOG_INFO,           /* OBMC Disable */
1814                    "MPEG4 OBMC not supported (very likely buggy encoder)\n");
1815         if (vo_ver_id == 1)
1816             ctx->vol_sprite_usage = get_bits1(gb);    /* vol_sprite_usage */
1817         else
1818             ctx->vol_sprite_usage = get_bits(gb, 2);  /* vol_sprite_usage */
1819
1820         if (ctx->vol_sprite_usage == STATIC_SPRITE)
1821             av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
1822         if (ctx->vol_sprite_usage == STATIC_SPRITE ||
1823             ctx->vol_sprite_usage == GMC_SPRITE) {
1824             if (ctx->vol_sprite_usage == STATIC_SPRITE) {
1825                 skip_bits(gb, 13); // sprite_width
1826                 check_marker(gb, "after sprite_width");
1827                 skip_bits(gb, 13); // sprite_height
1828                 check_marker(gb, "after sprite_height");
1829                 skip_bits(gb, 13); // sprite_left
1830                 check_marker(gb, "after sprite_left");
1831                 skip_bits(gb, 13); // sprite_top
1832                 check_marker(gb, "after sprite_top");
1833             }
1834             ctx->num_sprite_warping_points = get_bits(gb, 6);
1835             if (ctx->num_sprite_warping_points > 3) {
1836                 av_log(s->avctx, AV_LOG_ERROR,
1837                        "%d sprite_warping_points\n",
1838                        ctx->num_sprite_warping_points);
1839                 ctx->num_sprite_warping_points = 0;
1840                 return AVERROR_INVALIDDATA;
1841             }
1842             s->sprite_warping_accuracy  = get_bits(gb, 2);
1843             ctx->sprite_brightness_change = get_bits1(gb);
1844             if (ctx->vol_sprite_usage == STATIC_SPRITE)
1845                 skip_bits1(gb); // low_latency_sprite
1846         }
1847         // FIXME sadct disable bit if verid!=1 && shape not rect
1848
1849         if (get_bits1(gb) == 1) {                   /* not_8_bit */
1850             s->quant_precision = get_bits(gb, 4);   /* quant_precision */
1851             if (get_bits(gb, 4) != 8)               /* bits_per_pixel */
1852                 av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
1853             if (s->quant_precision != 5)
1854                 av_log(s->avctx, AV_LOG_ERROR,
1855                        "quant precision %d\n", s->quant_precision);
1856             if (s->quant_precision<3 || s->quant_precision>9) {
1857                 s->quant_precision = 5;
1858             }
1859         } else {
1860             s->quant_precision = 5;
1861         }
1862
1863         // FIXME a bunch of grayscale shape things
1864
1865         if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
1866             int i, v;
1867
1868             /* load default matrixes */
1869             for (i = 0; i < 64; i++) {
1870                 int j = s->idsp.idct_permutation[i];
1871                 v = ff_mpeg4_default_intra_matrix[i];
1872                 s->intra_matrix[j]        = v;
1873                 s->chroma_intra_matrix[j] = v;
1874
1875                 v = ff_mpeg4_default_non_intra_matrix[i];
1876                 s->inter_matrix[j]        = v;
1877                 s->chroma_inter_matrix[j] = v;
1878             }
1879
1880             /* load custom intra matrix */
1881             if (get_bits1(gb)) {
1882                 int last = 0;
1883                 for (i = 0; i < 64; i++) {
1884                     int j;
1885                     if (get_bits_left(gb) < 8) {
1886                         av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
1887                         return AVERROR_INVALIDDATA;
1888                     }
1889                     v = get_bits(gb, 8);
1890                     if (v == 0)
1891                         break;
1892
1893                     last = v;
1894                     j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
1895                     s->intra_matrix[j]        = last;
1896                     s->chroma_intra_matrix[j] = last;
1897                 }
1898
1899                 /* replicate last value */
1900                 for (; i < 64; i++) {
1901                     int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
1902                     s->intra_matrix[j]        = last;
1903                     s->chroma_intra_matrix[j] = last;
1904                 }
1905             }
1906
1907             /* load custom non intra matrix */
1908             if (get_bits1(gb)) {
1909                 int last = 0;
1910                 for (i = 0; i < 64; i++) {
1911                     int j;
1912                     if (get_bits_left(gb) < 8) {
1913                         av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
1914                         return AVERROR_INVALIDDATA;
1915                     }
1916                     v = get_bits(gb, 8);
1917                     if (v == 0)
1918                         break;
1919
1920                     last = v;
1921                     j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
1922                     s->inter_matrix[j]        = v;
1923                     s->chroma_inter_matrix[j] = v;
1924                 }
1925
1926                 /* replicate last value */
1927                 for (; i < 64; i++) {
1928                     int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
1929                     s->inter_matrix[j]        = last;
1930                     s->chroma_inter_matrix[j] = last;
1931                 }
1932             }
1933
1934             // FIXME a bunch of grayscale shape things
1935         }
1936
1937         if (vo_ver_id != 1)
1938             s->quarter_sample = get_bits1(gb);
1939         else
1940             s->quarter_sample = 0;
1941
1942         if (get_bits_left(gb) < 4) {
1943             av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n");
1944             return AVERROR_INVALIDDATA;
1945         }
1946
1947         if (!get_bits1(gb)) {
1948             int pos               = get_bits_count(gb);
1949             int estimation_method = get_bits(gb, 2);
1950             if (estimation_method < 2) {
1951                 if (!get_bits1(gb)) {
1952                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* opaque */
1953                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* transparent */
1954                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_cae */
1955                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* inter_cae */
1956                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* no_update */
1957                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* upampling */
1958                 }
1959                 if (!get_bits1(gb)) {
1960                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_blocks */
1961                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter_blocks */
1962                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter4v_blocks */
1963                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* not coded blocks */
1964                 }
1965                 if (!check_marker(gb, "in complexity estimation part 1")) {
1966                     skip_bits_long(gb, pos - get_bits_count(gb));
1967                     goto no_cplx_est;
1968                 }
1969                 if (!get_bits1(gb)) {
1970                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_coeffs */
1971                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_lines */
1972                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* vlc_syms */
1973                     ctx->cplx_estimation_trash_i += 4 * get_bits1(gb);  /* vlc_bits */
1974                 }
1975                 if (!get_bits1(gb)) {
1976                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* apm */
1977                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* npm */
1978                     ctx->cplx_estimation_trash_b += 8 * get_bits1(gb);  /* interpolate_mc_q */
1979                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* forwback_mc_q */
1980                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel2 */
1981                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel4 */
1982                 }
1983                 if (!check_marker(gb, "in complexity estimation part 2")) {
1984                     skip_bits_long(gb, pos - get_bits_count(gb));
1985                     goto no_cplx_est;
1986                 }
1987                 if (estimation_method == 1) {
1988                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* sadct */
1989                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* qpel */
1990                 }
1991             } else
1992                 av_log(s->avctx, AV_LOG_ERROR,
1993                        "Invalid Complexity estimation method %d\n",
1994                        estimation_method);
1995         } else {
1996
1997 no_cplx_est:
1998             ctx->cplx_estimation_trash_i =
1999             ctx->cplx_estimation_trash_p =
2000             ctx->cplx_estimation_trash_b = 0;
2001         }
2002
2003         ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
2004
2005         s->data_partitioning = get_bits1(gb);
2006         if (s->data_partitioning)
2007             ctx->rvlc = get_bits1(gb);
2008
2009         if (vo_ver_id != 1) {
2010             ctx->new_pred = get_bits1(gb);
2011             if (ctx->new_pred) {
2012                 av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
2013                 skip_bits(gb, 2); /* requested upstream message type */
2014                 skip_bits1(gb);   /* newpred segment type */
2015             }
2016             if (get_bits1(gb)) // reduced_res_vop
2017                 av_log(s->avctx, AV_LOG_ERROR,
2018                        "reduced resolution VOP not supported\n");
2019         } else {
2020             ctx->new_pred = 0;
2021         }
2022
2023         ctx->scalability = get_bits1(gb);
2024
2025         if (ctx->scalability) {
2026             GetBitContext bak = *gb;
2027             int h_sampling_factor_n;
2028             int h_sampling_factor_m;
2029             int v_sampling_factor_n;
2030             int v_sampling_factor_m;
2031
2032             skip_bits1(gb);    // hierarchy_type
2033             skip_bits(gb, 4);  /* ref_layer_id */
2034             skip_bits1(gb);    /* ref_layer_sampling_dir */
2035             h_sampling_factor_n = get_bits(gb, 5);
2036             h_sampling_factor_m = get_bits(gb, 5);
2037             v_sampling_factor_n = get_bits(gb, 5);
2038             v_sampling_factor_m = get_bits(gb, 5);
2039             ctx->enhancement_type = get_bits1(gb);
2040
2041             if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
2042                 v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
2043                 /* illegal scalability header (VERY broken encoder),
2044                  * trying to workaround */
2045                 ctx->scalability = 0;
2046                 *gb            = bak;
2047             } else
2048                 av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
2049
2050             // bin shape stuff FIXME
2051         }
2052     }
2053
2054     if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
2055         av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d,  %s%s%s%s\n",
2056                s->avctx->framerate.den, s->avctx->framerate.num,
2057                ctx->time_increment_bits,
2058                s->quant_precision,
2059                s->progressive_sequence,
2060                ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
2061                s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
2062         );
2063     }
2064
2065     return 0;
2066 }
2067
2068 /**
2069  * Decode the user data stuff in the header.
2070  * Also initializes divx/xvid/lavc_version/build.
2071  */
2072 static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
2073 {
2074     MpegEncContext *s = &ctx->m;
2075     char buf[256];
2076     int i;
2077     int e;
2078     int ver = 0, build = 0, ver2 = 0, ver3 = 0;
2079     char last;
2080
2081     for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
2082         if (show_bits(gb, 23) == 0)
2083             break;
2084         buf[i] = get_bits(gb, 8);
2085     }
2086     buf[i] = 0;
2087
2088     /* divx detection */
2089     e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
2090     if (e < 2)
2091         e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
2092     if (e >= 2) {
2093         ctx->divx_version = ver;
2094         ctx->divx_build   = build;
2095         s->divx_packed  = e == 3 && last == 'p';
2096     }
2097
2098     /* libavcodec detection */
2099     e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
2100     if (e != 4)
2101         e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
2102     if (e != 4) {
2103         e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
2104         if (e > 1)
2105             build = (ver << 16) + (ver2 << 8) + ver3;
2106     }
2107     if (e != 4) {
2108         if (strcmp(buf, "ffmpeg") == 0)
2109             ctx->lavc_build = 4600;
2110     }
2111     if (e == 4)
2112         ctx->lavc_build = build;
2113
2114     /* Xvid detection */
2115     e = sscanf(buf, "XviD%d", &build);
2116     if (e == 1)
2117         ctx->xvid_build = build;
2118
2119     return 0;
2120 }
2121
2122 int ff_mpeg4_workaround_bugs(AVCodecContext *avctx)
2123 {
2124     Mpeg4DecContext *ctx = avctx->priv_data;
2125     MpegEncContext *s = &ctx->m;
2126
2127     if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
2128         if (s->codec_tag        == AV_RL32("XVID") ||
2129             s->codec_tag        == AV_RL32("XVIX") ||
2130             s->codec_tag        == AV_RL32("RMP4") ||
2131             s->codec_tag        == AV_RL32("ZMP4") ||
2132             s->codec_tag        == AV_RL32("SIPP"))
2133             ctx->xvid_build = 0;
2134     }
2135
2136     if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
2137         if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 &&
2138             ctx->vol_control_parameters == 0)
2139             ctx->divx_version = 400;  // divx 4
2140
2141     if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
2142         ctx->divx_version =
2143         ctx->divx_build   = -1;
2144     }
2145
2146     if (s->workaround_bugs & FF_BUG_AUTODETECT) {
2147         if (s->codec_tag == AV_RL32("XVIX"))
2148             s->workaround_bugs |= FF_BUG_XVID_ILACE;
2149
2150         if (s->codec_tag == AV_RL32("UMP4"))
2151             s->workaround_bugs |= FF_BUG_UMP4;
2152
2153         if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
2154             s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
2155
2156         if (ctx->divx_version > 502 && ctx->divx_build < 1814)
2157             s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
2158
2159         if (ctx->xvid_build <= 3U)
2160             s->padding_bug_score = 256 * 256 * 256 * 64;
2161
2162         if (ctx->xvid_build <= 1U)
2163             s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
2164
2165         if (ctx->xvid_build <= 12U)
2166             s->workaround_bugs |= FF_BUG_EDGE;
2167
2168         if (ctx->xvid_build <= 32U)
2169             s->workaround_bugs |= FF_BUG_DC_CLIP;
2170
2171 #define SET_QPEL_FUNC(postfix1, postfix2)                           \
2172     s->qdsp.put_        ## postfix1 = ff_put_        ## postfix2;   \
2173     s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2;   \
2174     s->qdsp.avg_        ## postfix1 = ff_avg_        ## postfix2;
2175
2176         if (ctx->lavc_build < 4653U)
2177             s->workaround_bugs |= FF_BUG_STD_QPEL;
2178
2179         if (ctx->lavc_build < 4655U)
2180             s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
2181
2182         if (ctx->lavc_build < 4670U)
2183             s->workaround_bugs |= FF_BUG_EDGE;
2184
2185         if (ctx->lavc_build <= 4712U)
2186             s->workaround_bugs |= FF_BUG_DC_CLIP;
2187
2188         if (ctx->divx_version >= 0)
2189             s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
2190         if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
2191             s->padding_bug_score = 256 * 256 * 256 * 64;
2192
2193         if (ctx->divx_version < 500U)
2194             s->workaround_bugs |= FF_BUG_EDGE;
2195
2196         if (ctx->divx_version >= 0)
2197             s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
2198     }
2199
2200     if (s->workaround_bugs & FF_BUG_STD_QPEL) {
2201         SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)
2202         SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)
2203         SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)
2204         SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
2205         SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
2206         SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
2207
2208         SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)
2209         SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)
2210         SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)
2211         SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
2212         SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
2213         SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
2214     }
2215
2216     if (avctx->debug & FF_DEBUG_BUGS)
2217         av_log(s->avctx, AV_LOG_DEBUG,
2218                "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
2219                s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
2220                ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
2221
2222     if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 &&
2223         s->codec_id == AV_CODEC_ID_MPEG4 &&
2224         avctx->idct_algo == FF_IDCT_AUTO) {
2225         avctx->idct_algo = FF_IDCT_XVID;
2226         ff_mpv_idct_init(s);
2227         return 1;
2228     }
2229
2230     return 0;
2231 }
2232
2233 static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
2234 {
2235     MpegEncContext *s = &ctx->m;
2236     int time_incr, time_increment;
2237     int64_t pts;
2238
2239     s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I;        /* pict type: I = 0 , P = 1 */
2240     if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
2241         ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) {
2242         av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n");
2243         s->low_delay = 0;
2244     }
2245
2246     s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
2247     if (s->partitioned_frame)
2248         s->decode_mb = mpeg4_decode_partitioned_mb;
2249     else
2250         s->decode_mb = mpeg4_decode_mb;
2251
2252     time_incr = 0;
2253     while (get_bits1(gb) != 0)
2254         time_incr++;
2255
2256     check_marker(gb, "before time_increment");
2257
2258     if (ctx->time_increment_bits == 0 ||
2259         !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
2260         av_log(s->avctx, AV_LOG_WARNING,
2261                "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);
2262
2263         for (ctx->time_increment_bits = 1;
2264              ctx->time_increment_bits < 16;
2265              ctx->time_increment_bits++) {
2266             if (s->pict_type == AV_PICTURE_TYPE_P ||
2267                 (s->pict_type == AV_PICTURE_TYPE_S &&
2268                  ctx->vol_sprite_usage == GMC_SPRITE)) {
2269                 if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
2270                     break;
2271             } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
2272                 break;
2273         }
2274
2275         av_log(s->avctx, AV_LOG_WARNING,
2276                "time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits);
2277         if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) {
2278             s->avctx->framerate.num = 1<<ctx->time_increment_bits;
2279             s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
2280         }
2281     }
2282
2283     if (IS_3IV1)
2284         time_increment = get_bits1(gb);        // FIXME investigate further
2285     else
2286         time_increment = get_bits(gb, ctx->time_increment_bits);
2287
2288     if (s->pict_type != AV_PICTURE_TYPE_B) {
2289         s->last_time_base = s->time_base;
2290         s->time_base     += time_incr;
2291         s->time = s->time_base * s->avctx->framerate.num + time_increment;
2292         if (s->workaround_bugs & FF_BUG_UMP4) {
2293             if (s->time < s->last_non_b_time) {
2294                 /* header is not mpeg-4-compatible, broken encoder,
2295                  * trying to workaround */
2296                 s->time_base++;
2297                 s->time += s->avctx->framerate.num;
2298             }
2299         }
2300         s->pp_time         = s->time - s->last_non_b_time;
2301         s->last_non_b_time = s->time;
2302     } else {
2303         s->time    = (s->last_time_base + time_incr) * s->avctx->framerate.num + time_increment;
2304         s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
2305         if (s->pp_time <= s->pb_time ||
2306             s->pp_time <= s->pp_time - s->pb_time ||
2307             s->pp_time <= 0) {
2308             /* messed up order, maybe after seeking? skipping current b-frame */
2309             return FRAME_SKIPPED;
2310         }
2311         ff_mpeg4_init_direct_mv(s);
2312
2313         if (ctx->t_frame == 0)
2314             ctx->t_frame = s->pb_time;
2315         if (ctx->t_frame == 0)
2316             ctx->t_frame = 1;  // 1/0 protection
2317         s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
2318                             ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
2319         s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
2320                             ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
2321         if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) {
2322             s->pb_field_time = 2;
2323             s->pp_field_time = 4;
2324             if (!s->progressive_sequence)
2325                 return FRAME_SKIPPED;
2326         }
2327     }
2328
2329     if (s->avctx->framerate.den)
2330         pts = ROUNDED_DIV(s->time, s->avctx->framerate.den);
2331     else
2332         pts = AV_NOPTS_VALUE;
2333     ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts);
2334
2335     check_marker(gb, "before vop_coded");
2336
2337     /* vop coded */
2338     if (get_bits1(gb) != 1) {
2339         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2340             av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
2341         return FRAME_SKIPPED;
2342     }
2343     if (ctx->new_pred)
2344         decode_new_pred(ctx, gb);
2345
2346     if (ctx->shape != BIN_ONLY_SHAPE &&
2347                     (s->pict_type == AV_PICTURE_TYPE_P ||
2348                      (s->pict_type == AV_PICTURE_TYPE_S &&
2349                       ctx->vol_sprite_usage == GMC_SPRITE))) {
2350         /* rounding type for motion estimation */
2351         s->no_rounding = get_bits1(gb);
2352     } else {
2353         s->no_rounding = 0;
2354     }
2355     // FIXME reduced res stuff
2356
2357     if (ctx->shape != RECT_SHAPE) {
2358         if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
2359             skip_bits(gb, 13);  /* width */
2360             check_marker(gb, "after width");
2361             skip_bits(gb, 13);  /* height */
2362             check_marker(gb, "after height");
2363             skip_bits(gb, 13);  /* hor_spat_ref */
2364             check_marker(gb, "after hor_spat_ref");
2365             skip_bits(gb, 13);  /* ver_spat_ref */
2366         }
2367         skip_bits1(gb);         /* change_CR_disable */
2368
2369         if (get_bits1(gb) != 0)
2370             skip_bits(gb, 8);   /* constant_alpha_value */
2371     }
2372
2373     // FIXME complexity estimation stuff
2374
2375     if (ctx->shape != BIN_ONLY_SHAPE) {
2376         skip_bits_long(gb, ctx->cplx_estimation_trash_i);
2377         if (s->pict_type != AV_PICTURE_TYPE_I)
2378             skip_bits_long(gb, ctx->cplx_estimation_trash_p);
2379         if (s->pict_type == AV_PICTURE_TYPE_B)
2380             skip_bits_long(gb, ctx->cplx_estimation_trash_b);
2381
2382         if (get_bits_left(gb) < 3) {
2383             av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");
2384             return AVERROR_INVALIDDATA;
2385         }
2386         ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
2387         if (!s->progressive_sequence) {
2388             s->top_field_first = get_bits1(gb);
2389             s->alternate_scan  = get_bits1(gb);
2390         } else
2391             s->alternate_scan = 0;
2392     }
2393
2394     if (s->alternate_scan) {
2395         ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_alternate_vertical_scan);
2396         ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_alternate_vertical_scan);
2397         ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
2398         ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2399     } else {
2400         ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_zigzag_direct);
2401         ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_zigzag_direct);
2402         ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
2403         ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2404     }
2405
2406     if (s->pict_type == AV_PICTURE_TYPE_S &&
2407         (ctx->vol_sprite_usage == STATIC_SPRITE ||
2408          ctx->vol_sprite_usage == GMC_SPRITE)) {
2409         if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
2410             return AVERROR_INVALIDDATA;
2411         if (ctx->sprite_brightness_change)
2412             av_log(s->avctx, AV_LOG_ERROR,
2413                    "sprite_brightness_change not supported\n");
2414         if (ctx->vol_sprite_usage == STATIC_SPRITE)
2415             av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
2416     }
2417
2418     if (ctx->shape != BIN_ONLY_SHAPE) {
2419         s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);
2420         if (s->qscale == 0) {
2421             av_log(s->avctx, AV_LOG_ERROR,
2422                    "Error, header damaged or not MPEG4 header (qscale=0)\n");
2423             return AVERROR_INVALIDDATA;  // makes no sense to continue, as there is nothing left from the image then
2424         }
2425
2426         if (s->pict_type != AV_PICTURE_TYPE_I) {
2427             s->f_code = get_bits(gb, 3);        /* fcode_for */
2428             if (s->f_code == 0) {
2429                 av_log(s->avctx, AV_LOG_ERROR,
2430                        "Error, header damaged or not MPEG4 header (f_code=0)\n");
2431                 s->f_code = 1;
2432                 return AVERROR_INVALIDDATA;  // makes no sense to continue, as there is nothing left from the image then
2433             }
2434         } else
2435             s->f_code = 1;
2436
2437         if (s->pict_type == AV_PICTURE_TYPE_B) {
2438             s->b_code = get_bits(gb, 3);
2439             if (s->b_code == 0) {
2440                 av_log(s->avctx, AV_LOG_ERROR,
2441                        "Error, header damaged or not MPEG4 header (b_code=0)\n");
2442                 s->b_code=1;
2443                 return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly
2444             }
2445         } else
2446             s->b_code = 1;
2447
2448         if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
2449             av_log(s->avctx, AV_LOG_DEBUG,
2450                    "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",
2451                    s->qscale, s->f_code, s->b_code,
2452                    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")),
2453                    gb->size_in_bits,s->progressive_sequence, s->alternate_scan,
2454                    s->top_field_first, s->quarter_sample ? "q" : "h",
2455                    s->data_partitioning, ctx->resync_marker,
2456                    ctx->num_sprite_warping_points, s->sprite_warping_accuracy,
2457                    1 - s->no_rounding, s->vo_type,
2458                    ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
2459                    ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
2460                    ctx->cplx_estimation_trash_b,
2461                    s->time,
2462                    time_increment
2463                   );
2464         }
2465
2466         if (!ctx->scalability) {
2467             if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
2468                 skip_bits1(gb);  // vop shape coding type
2469         } else {
2470             if (ctx->enhancement_type) {
2471                 int load_backward_shape = get_bits1(gb);
2472                 if (load_backward_shape)
2473                     av_log(s->avctx, AV_LOG_ERROR,
2474                            "load backward shape isn't supported\n");
2475             }
2476             skip_bits(gb, 2);  // ref_select_code
2477         }
2478     }
2479     /* detect buggy encoders which don't set the low_delay flag
2480      * (divx4/xvid/opendivx). Note we cannot detect divx5 without b-frames
2481      * easily (although it's buggy too) */
2482     if (s->vo_type == 0 && ctx->vol_control_parameters == 0 &&
2483         ctx->divx_version == -1 && s->picture_number == 0) {
2484         av_log(s->avctx, AV_LOG_WARNING,
2485                "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
2486         s->low_delay = 1;
2487     }
2488
2489     s->picture_number++;  // better than pic number==0 always ;)
2490
2491     // FIXME add short header support
2492     s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
2493     s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
2494
2495     if (s->workaround_bugs & FF_BUG_EDGE) {
2496         s->h_edge_pos = s->width;
2497         s->v_edge_pos = s->height;
2498     }
2499     return 0;
2500 }
2501
2502 /**
2503  * Decode mpeg4 headers.
2504  * @return <0 if no VOP found (or a damaged one)
2505  *         FRAME_SKIPPED if a not coded VOP is found
2506  *         0 if a VOP is found
2507  */
2508 int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
2509 {
2510     MpegEncContext *s = &ctx->m;
2511     unsigned startcode, v;
2512     int ret;
2513
2514     /* search next start code */
2515     align_get_bits(gb);
2516
2517     if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
2518         skip_bits(gb, 24);
2519         if (get_bits(gb, 8) == 0xF0)
2520             goto end;
2521     }
2522
2523     startcode = 0xff;
2524     for (;;) {
2525         if (get_bits_count(gb) >= gb->size_in_bits) {
2526             if (gb->size_in_bits == 8 &&
2527                 (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
2528                 av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
2529                 return FRAME_SKIPPED;  // divx bug
2530             } else
2531                 return -1;  // end of stream
2532         }
2533
2534         /* use the bits after the test */
2535         v = get_bits(gb, 8);
2536         startcode = ((startcode << 8) | v) & 0xffffffff;
2537
2538         if ((startcode & 0xFFFFFF00) != 0x100)
2539             continue;  // no startcode
2540
2541         if (s->avctx->debug & FF_DEBUG_STARTCODE) {
2542             av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
2543             if (startcode <= 0x11F)
2544                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
2545             else if (startcode <= 0x12F)
2546                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
2547             else if (startcode <= 0x13F)
2548                 av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2549             else if (startcode <= 0x15F)
2550                 av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
2551             else if (startcode <= 0x1AF)
2552                 av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2553             else if (startcode == 0x1B0)
2554                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
2555             else if (startcode == 0x1B1)
2556                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
2557             else if (startcode == 0x1B2)
2558                 av_log(s->avctx, AV_LOG_DEBUG, "User Data");
2559             else if (startcode == 0x1B3)
2560                 av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
2561             else if (startcode == 0x1B4)
2562                 av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
2563             else if (startcode == 0x1B5)
2564                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
2565             else if (startcode == 0x1B6)
2566                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
2567             else if (startcode == 0x1B7)
2568                 av_log(s->avctx, AV_LOG_DEBUG, "slice start");
2569             else if (startcode == 0x1B8)
2570                 av_log(s->avctx, AV_LOG_DEBUG, "extension start");
2571             else if (startcode == 0x1B9)
2572                 av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
2573             else if (startcode == 0x1BA)
2574                 av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
2575             else if (startcode == 0x1BB)
2576                 av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
2577             else if (startcode == 0x1BC)
2578                 av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
2579             else if (startcode == 0x1BD)
2580                 av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
2581             else if (startcode == 0x1BE)
2582                 av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
2583             else if (startcode == 0x1BF)
2584                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
2585             else if (startcode == 0x1C0)
2586                 av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
2587             else if (startcode == 0x1C1)
2588                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
2589             else if (startcode == 0x1C2)
2590                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
2591             else if (startcode == 0x1C3)
2592                 av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
2593             else if (startcode <= 0x1C5)
2594                 av_log(s->avctx, AV_LOG_DEBUG, "reserved");
2595             else if (startcode <= 0x1FF)
2596                 av_log(s->avctx, AV_LOG_DEBUG, "System start");
2597             av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
2598         }
2599
2600         if (startcode >= 0x120 && startcode <= 0x12F) {
2601             if ((ret = decode_vol_header(ctx, gb)) < 0)
2602                 return ret;
2603         } else if (startcode == USER_DATA_STARTCODE) {
2604             decode_user_data(ctx, gb);
2605         } else if (startcode == GOP_STARTCODE) {
2606             mpeg4_decode_gop_header(s, gb);
2607         } else if (startcode == VOS_STARTCODE) {
2608             mpeg4_decode_profile_level(s, gb);
2609         } else if (startcode == VOP_STARTCODE) {
2610             break;
2611         }
2612
2613         align_get_bits(gb);
2614         startcode = 0xff;
2615     }
2616
2617 end:
2618     if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
2619         s->low_delay = 1;
2620     s->avctx->has_b_frames = !s->low_delay;
2621
2622     return decode_vop_header(ctx, gb);
2623 }
2624
2625 av_cold void ff_mpeg4videodec_static_init(void) {
2626     static int done = 0;
2627
2628     if (!done) {
2629         ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
2630         ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
2631         ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
2632         INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
2633         INIT_VLC_RL(ff_rvlc_rl_inter, 1072);
2634         INIT_VLC_RL(ff_rvlc_rl_intra, 1072);
2635         INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2636                         &ff_mpeg4_DCtab_lum[0][1], 2, 1,
2637                         &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
2638         INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2639                         &ff_mpeg4_DCtab_chrom[0][1], 2, 1,
2640                         &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
2641         INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2642                         &ff_sprite_trajectory_tab[0][1], 4, 2,
2643                         &ff_sprite_trajectory_tab[0][0], 4, 2, 128);
2644         INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2645                         &ff_mb_type_b_tab[0][1], 2, 1,
2646                         &ff_mb_type_b_tab[0][0], 2, 1, 16);
2647         done = 1;
2648     }
2649 }
2650
2651 int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
2652 {
2653     Mpeg4DecContext *ctx = avctx->priv_data;
2654     MpegEncContext    *s = &ctx->m;
2655
2656     /* divx 5.01+ bitstream reorder stuff */
2657     /* Since this clobbers the input buffer and hwaccel codecs still need the
2658      * data during hwaccel->end_frame we should not do this any earlier */
2659     if (s->divx_packed) {
2660         int current_pos     = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);
2661         int startcode_found = 0;
2662
2663         if (buf_size - current_pos > 7) {
2664
2665             int i;
2666             for (i = current_pos; i < buf_size - 4; i++)
2667
2668                 if (buf[i]     == 0 &&
2669                     buf[i + 1] == 0 &&
2670                     buf[i + 2] == 1 &&
2671                     buf[i + 3] == 0xB6) {
2672                     startcode_found = !(buf[i + 4] & 0x40);
2673                     break;
2674                 }
2675         }
2676
2677         if (startcode_found) {
2678             if (!ctx->showed_packed_warning) {
2679                 av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and "
2680                        "wasteful way to store B-frames ('packed B-frames'). "
2681                        "Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n");
2682                 ctx->showed_packed_warning = 1;
2683             }
2684             av_fast_padded_malloc(&s->bitstream_buffer,
2685                            &s->allocated_bitstream_buffer_size,
2686                            buf_size - current_pos);
2687             if (!s->bitstream_buffer) {
2688                 s->bitstream_buffer_size = 0;
2689                 return AVERROR(ENOMEM);
2690             }
2691             memcpy(s->bitstream_buffer, buf + current_pos,
2692                    buf_size - current_pos);
2693             s->bitstream_buffer_size = buf_size - current_pos;
2694         }
2695     }
2696
2697     return 0;
2698 }
2699
2700 #if HAVE_THREADS
2701 static int mpeg4_update_thread_context(AVCodecContext *dst,
2702                                        const AVCodecContext *src)
2703 {
2704     Mpeg4DecContext *s = dst->priv_data;
2705     const Mpeg4DecContext *s1 = src->priv_data;
2706     int init = s->m.context_initialized;
2707
2708     int ret = ff_mpeg_update_thread_context(dst, src);
2709
2710     if (ret < 0)
2711         return ret;
2712
2713     memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext));
2714
2715     if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0)
2716         ff_xvid_idct_init(&s->m.idsp, dst);
2717
2718     return 0;
2719 }
2720 #endif
2721
2722 static av_cold int decode_init(AVCodecContext *avctx)
2723 {
2724     Mpeg4DecContext *ctx = avctx->priv_data;
2725     MpegEncContext *s = &ctx->m;
2726     int ret;
2727
2728     ctx->divx_version =
2729     ctx->divx_build   =
2730     ctx->xvid_build   =
2731     ctx->lavc_build   = -1;
2732
2733     if ((ret = ff_h263_decode_init(avctx)) < 0)
2734         return ret;
2735
2736     ff_mpeg4videodec_static_init();
2737
2738     s->h263_pred = 1;
2739     s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */
2740     s->decode_mb = mpeg4_decode_mb;
2741     ctx->time_increment_bits = 4; /* default value for broken headers */
2742
2743     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
2744     avctx->internal->allocate_progress = 1;
2745
2746     return 0;
2747 }
2748
2749 static const AVOption mpeg4_options[] = {
2750     {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
2751     {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
2752     {NULL}
2753 };
2754
2755 static const AVClass mpeg4_class = {
2756     "MPEG4 Video Decoder",
2757     av_default_item_name,
2758     mpeg4_options,
2759     LIBAVUTIL_VERSION_INT,
2760 };
2761
2762 AVCodec ff_mpeg4_decoder = {
2763     .name                  = "mpeg4",
2764     .long_name             = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
2765     .type                  = AVMEDIA_TYPE_VIDEO,
2766     .id                    = AV_CODEC_ID_MPEG4,
2767     .priv_data_size        = sizeof(Mpeg4DecContext),
2768     .init                  = decode_init,
2769     .close                 = ff_h263_decode_end,
2770     .decode                = ff_h263_decode_frame,
2771     .capabilities          = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
2772                              AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY |
2773                              AV_CODEC_CAP_FRAME_THREADS,
2774     .flush                 = ff_mpeg_flush,
2775     .max_lowres            = 3,
2776     .pix_fmts              = ff_h263_hwaccel_pixfmt_list_420,
2777     .profiles              = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles),
2778     .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context),
2779     .priv_class = &mpeg4_class,
2780 };
2781
2782
2783 #if CONFIG_MPEG4_VDPAU_DECODER && FF_API_VDPAU
2784 static const AVClass mpeg4_vdpau_class = {
2785     "MPEG4 Video VDPAU Decoder",
2786     av_default_item_name,
2787     mpeg4_options,
2788     LIBAVUTIL_VERSION_INT,
2789 };
2790
2791 AVCodec ff_mpeg4_vdpau_decoder = {
2792     .name           = "mpeg4_vdpau",
2793     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 part 2 (VDPAU)"),
2794     .type           = AVMEDIA_TYPE_VIDEO,
2795     .id             = AV_CODEC_ID_MPEG4,
2796     .priv_data_size = sizeof(Mpeg4DecContext),
2797     .init           = decode_init,
2798     .close          = ff_h263_decode_end,
2799     .decode         = ff_h263_decode_frame,
2800     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY |
2801                       AV_CODEC_CAP_HWACCEL_VDPAU,
2802     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_MPEG4,
2803                                                   AV_PIX_FMT_NONE },
2804     .priv_class     = &mpeg4_vdpau_class,
2805 };
2806 #endif