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