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