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