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