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