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