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