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