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