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