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