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