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