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