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