]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpeg4videodec.c
Merge commit 'd6a27f885b5d4cba7a82e50af423c741d2f37c3e'
[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_bits_left(gb) < 4) {
1920             av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n");
1921             return AVERROR_INVALIDDATA;
1922         }
1923
1924         if (!get_bits1(gb)) {
1925             int pos               = get_bits_count(gb);
1926             int estimation_method = get_bits(gb, 2);
1927             if (estimation_method < 2) {
1928                 if (!get_bits1(gb)) {
1929                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* opaque */
1930                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* transparent */
1931                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_cae */
1932                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* inter_cae */
1933                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* no_update */
1934                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* upampling */
1935                 }
1936                 if (!get_bits1(gb)) {
1937                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_blocks */
1938                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter_blocks */
1939                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter4v_blocks */
1940                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* not coded blocks */
1941                 }
1942                 if (!check_marker(gb, "in complexity estimation part 1")) {
1943                     skip_bits_long(gb, pos - get_bits_count(gb));
1944                     goto no_cplx_est;
1945                 }
1946                 if (!get_bits1(gb)) {
1947                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_coeffs */
1948                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_lines */
1949                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* vlc_syms */
1950                     ctx->cplx_estimation_trash_i += 4 * get_bits1(gb);  /* vlc_bits */
1951                 }
1952                 if (!get_bits1(gb)) {
1953                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* apm */
1954                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* npm */
1955                     ctx->cplx_estimation_trash_b += 8 * get_bits1(gb);  /* interpolate_mc_q */
1956                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* forwback_mc_q */
1957                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel2 */
1958                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel4 */
1959                 }
1960                 if (!check_marker(gb, "in complexity estimation part 2")) {
1961                     skip_bits_long(gb, pos - get_bits_count(gb));
1962                     goto no_cplx_est;
1963                 }
1964                 if (estimation_method == 1) {
1965                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* sadct */
1966                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* qpel */
1967                 }
1968             } else
1969                 av_log(s->avctx, AV_LOG_ERROR,
1970                        "Invalid Complexity estimation method %d\n",
1971                        estimation_method);
1972         } else {
1973
1974 no_cplx_est:
1975             ctx->cplx_estimation_trash_i =
1976             ctx->cplx_estimation_trash_p =
1977             ctx->cplx_estimation_trash_b = 0;
1978         }
1979
1980         ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
1981
1982         s->data_partitioning = get_bits1(gb);
1983         if (s->data_partitioning)
1984             ctx->rvlc = get_bits1(gb);
1985
1986         if (vo_ver_id != 1) {
1987             ctx->new_pred = get_bits1(gb);
1988             if (ctx->new_pred) {
1989                 av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
1990                 skip_bits(gb, 2); /* requested upstream message type */
1991                 skip_bits1(gb);   /* newpred segment type */
1992             }
1993             if (get_bits1(gb)) // reduced_res_vop
1994                 av_log(s->avctx, AV_LOG_ERROR,
1995                        "reduced resolution VOP not supported\n");
1996         } else {
1997             ctx->new_pred = 0;
1998         }
1999
2000         ctx->scalability = get_bits1(gb);
2001
2002         if (ctx->scalability) {
2003             GetBitContext bak = *gb;
2004             int h_sampling_factor_n;
2005             int h_sampling_factor_m;
2006             int v_sampling_factor_n;
2007             int v_sampling_factor_m;
2008
2009             skip_bits1(gb);    // hierarchy_type
2010             skip_bits(gb, 4);  /* ref_layer_id */
2011             skip_bits1(gb);    /* ref_layer_sampling_dir */
2012             h_sampling_factor_n = get_bits(gb, 5);
2013             h_sampling_factor_m = get_bits(gb, 5);
2014             v_sampling_factor_n = get_bits(gb, 5);
2015             v_sampling_factor_m = get_bits(gb, 5);
2016             ctx->enhancement_type = get_bits1(gb);
2017
2018             if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
2019                 v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
2020                 /* illegal scalability header (VERY broken encoder),
2021                  * trying to workaround */
2022                 ctx->scalability = 0;
2023                 *gb            = bak;
2024             } else
2025                 av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
2026
2027             // bin shape stuff FIXME
2028         }
2029     }
2030
2031     if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
2032         av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d,  %s%s%s%s\n",
2033                s->avctx->time_base.num, s->avctx->time_base.den,
2034                ctx->time_increment_bits,
2035                s->quant_precision,
2036                s->progressive_sequence,
2037                ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
2038                s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
2039         );
2040     }
2041
2042     return 0;
2043 }
2044
2045 /**
2046  * Decode the user data stuff in the header.
2047  * Also initializes divx/xvid/lavc_version/build.
2048  */
2049 static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
2050 {
2051     MpegEncContext *s = &ctx->m;
2052     char buf[256];
2053     int i;
2054     int e;
2055     int ver = 0, build = 0, ver2 = 0, ver3 = 0;
2056     char last;
2057
2058     for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
2059         if (show_bits(gb, 23) == 0)
2060             break;
2061         buf[i] = get_bits(gb, 8);
2062     }
2063     buf[i] = 0;
2064
2065     /* divx detection */
2066     e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
2067     if (e < 2)
2068         e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
2069     if (e >= 2) {
2070         ctx->divx_version = ver;
2071         ctx->divx_build   = build;
2072         s->divx_packed  = e == 3 && last == 'p';
2073         if (s->divx_packed && !ctx->showed_packed_warning) {
2074             av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and "
2075                    "wasteful way to store B-frames ('packed B-frames'). "
2076                    "Consider using a tool like VirtualDub or avidemux to fix it.\n");
2077             ctx->showed_packed_warning = 1;
2078         }
2079     }
2080
2081     /* libavcodec detection */
2082     e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
2083     if (e != 4)
2084         e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
2085     if (e != 4) {
2086         e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
2087         if (e > 1)
2088             build = (ver << 16) + (ver2 << 8) + ver3;
2089     }
2090     if (e != 4) {
2091         if (strcmp(buf, "ffmpeg") == 0)
2092             ctx->lavc_build = 4600;
2093     }
2094     if (e == 4)
2095         ctx->lavc_build = build;
2096
2097     /* Xvid detection */
2098     e = sscanf(buf, "XviD%d", &build);
2099     if (e == 1)
2100         ctx->xvid_build = build;
2101
2102     return 0;
2103 }
2104
2105 int ff_mpeg4_workaround_bugs(AVCodecContext *avctx)
2106 {
2107     Mpeg4DecContext *ctx = avctx->priv_data;
2108     MpegEncContext *s = &ctx->m;
2109
2110     if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
2111         if (s->stream_codec_tag == AV_RL32("XVID") ||
2112             s->codec_tag        == AV_RL32("XVID") ||
2113             s->codec_tag        == AV_RL32("XVIX") ||
2114             s->codec_tag        == AV_RL32("RMP4") ||
2115             s->codec_tag        == AV_RL32("ZMP4") ||
2116             s->codec_tag        == AV_RL32("SIPP"))
2117             ctx->xvid_build = 0;
2118     }
2119
2120     if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
2121         if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 &&
2122             s->vol_control_parameters == 0)
2123             ctx->divx_version = 400;  // divx 4
2124
2125     if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
2126         ctx->divx_version =
2127         ctx->divx_build   = -1;
2128     }
2129
2130     if (s->workaround_bugs & FF_BUG_AUTODETECT) {
2131         if (s->codec_tag == AV_RL32("XVIX"))
2132             s->workaround_bugs |= FF_BUG_XVID_ILACE;
2133
2134         if (s->codec_tag == AV_RL32("UMP4"))
2135             s->workaround_bugs |= FF_BUG_UMP4;
2136
2137         if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
2138             s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
2139
2140         if (ctx->divx_version > 502 && ctx->divx_build < 1814)
2141             s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
2142
2143         if (ctx->xvid_build <= 3U)
2144             s->padding_bug_score = 256 * 256 * 256 * 64;
2145
2146         if (ctx->xvid_build <= 1U)
2147             s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
2148
2149         if (ctx->xvid_build <= 12U)
2150             s->workaround_bugs |= FF_BUG_EDGE;
2151
2152         if (ctx->xvid_build <= 32U)
2153             s->workaround_bugs |= FF_BUG_DC_CLIP;
2154
2155 #define SET_QPEL_FUNC(postfix1, postfix2)                           \
2156     s->dsp.put_        ## postfix1 = ff_put_        ## postfix2;    \
2157     s->dsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2;    \
2158     s->dsp.avg_        ## postfix1 = ff_avg_        ## postfix2;
2159
2160         if (ctx->lavc_build < 4653U)
2161             s->workaround_bugs |= FF_BUG_STD_QPEL;
2162
2163         if (ctx->lavc_build < 4655U)
2164             s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
2165
2166         if (ctx->lavc_build < 4670U)
2167             s->workaround_bugs |= FF_BUG_EDGE;
2168
2169         if (ctx->lavc_build <= 4712U)
2170             s->workaround_bugs |= FF_BUG_DC_CLIP;
2171
2172         if (ctx->divx_version >= 0)
2173             s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
2174         if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
2175             s->padding_bug_score = 256 * 256 * 256 * 64;
2176
2177         if (ctx->divx_version < 500U)
2178             s->workaround_bugs |= FF_BUG_EDGE;
2179
2180         if (ctx->divx_version >= 0)
2181             s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
2182     }
2183
2184     if (s->workaround_bugs & FF_BUG_STD_QPEL) {
2185         SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)
2186         SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)
2187         SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)
2188         SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
2189         SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
2190         SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
2191
2192         SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)
2193         SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)
2194         SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)
2195         SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
2196         SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
2197         SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
2198     }
2199
2200     if (avctx->debug & FF_DEBUG_BUGS)
2201         av_log(s->avctx, AV_LOG_DEBUG,
2202                "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
2203                s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
2204                ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
2205
2206 #if HAVE_MMX
2207     if (s->codec_id == AV_CODEC_ID_MPEG4 && ctx->xvid_build >= 0 &&
2208         avctx->idct_algo == FF_IDCT_AUTO &&
2209         (av_get_cpu_flags() & AV_CPU_FLAG_MMX)) {
2210         avctx->idct_algo = FF_IDCT_XVIDMMX;
2211         ff_dct_common_init(s);
2212         return 1;
2213     }
2214 #endif
2215     return 0;
2216 }
2217
2218 static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
2219 {
2220     MpegEncContext *s = &ctx->m;
2221     int time_incr, time_increment;
2222     int64_t pts;
2223
2224     s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I;        /* pict type: I = 0 , P = 1 */
2225     if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
2226         s->vol_control_parameters == 0 && !(s->flags & CODEC_FLAG_LOW_DELAY)) {
2227         av_log(s->avctx, AV_LOG_ERROR, "low_delay flag incorrectly, clearing it\n");
2228         s->low_delay = 0;
2229     }
2230
2231     s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
2232     if (s->partitioned_frame)
2233         s->decode_mb = mpeg4_decode_partitioned_mb;
2234     else
2235         s->decode_mb = mpeg4_decode_mb;
2236
2237     time_incr = 0;
2238     while (get_bits1(gb) != 0)
2239         time_incr++;
2240
2241     check_marker(gb, "before time_increment");
2242
2243     if (ctx->time_increment_bits == 0 ||
2244         !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
2245         av_log(s->avctx, AV_LOG_ERROR,
2246                "hmm, seems the headers are not complete, trying to guess time_increment_bits\n");
2247
2248         for (ctx->time_increment_bits = 1;
2249              ctx->time_increment_bits < 16;
2250              ctx->time_increment_bits++) {
2251             if (s->pict_type == AV_PICTURE_TYPE_P ||
2252                 (s->pict_type == AV_PICTURE_TYPE_S &&
2253                  ctx->vol_sprite_usage == GMC_SPRITE)) {
2254                 if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
2255                     break;
2256             } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
2257                 break;
2258         }
2259
2260         av_log(s->avctx, AV_LOG_ERROR,
2261                "my guess is %d bits ;)\n", ctx->time_increment_bits);
2262         if (s->avctx->time_base.den && 4*s->avctx->time_base.den < 1<<ctx->time_increment_bits) {
2263             s->avctx->time_base.den = 1<<ctx->time_increment_bits;
2264         }
2265     }
2266
2267     if (IS_3IV1)
2268         time_increment = get_bits1(gb);        // FIXME investigate further
2269     else
2270         time_increment = get_bits(gb, ctx->time_increment_bits);
2271
2272     if (s->pict_type != AV_PICTURE_TYPE_B) {
2273         s->last_time_base = s->time_base;
2274         s->time_base     += time_incr;
2275         s->time = s->time_base * s->avctx->time_base.den + time_increment;
2276         if (s->workaround_bugs & FF_BUG_UMP4) {
2277             if (s->time < s->last_non_b_time) {
2278                 /* header is not mpeg-4-compatible, broken encoder,
2279                  * trying to workaround */
2280                 s->time_base++;
2281                 s->time += s->avctx->time_base.den;
2282             }
2283         }
2284         s->pp_time         = s->time - s->last_non_b_time;
2285         s->last_non_b_time = s->time;
2286     } else {
2287         s->time    = (s->last_time_base + time_incr) * s->avctx->time_base.den + time_increment;
2288         s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
2289         if (s->pp_time <= s->pb_time ||
2290             s->pp_time <= s->pp_time - s->pb_time ||
2291             s->pp_time <= 0) {
2292             /* messed up order, maybe after seeking? skipping current b-frame */
2293             return FRAME_SKIPPED;
2294         }
2295         ff_mpeg4_init_direct_mv(s);
2296
2297         if (ctx->t_frame == 0)
2298             ctx->t_frame = s->pb_time;
2299         if (ctx->t_frame == 0)
2300             ctx->t_frame = 1;  // 1/0 protection
2301         s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
2302                             ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
2303         s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
2304                             ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
2305         if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) {
2306             s->pb_field_time = 2;
2307             s->pp_field_time = 4;
2308             if (!s->progressive_sequence)
2309                 return FRAME_SKIPPED;
2310         }
2311     }
2312
2313     if (s->avctx->time_base.num)
2314         pts = ROUNDED_DIV(s->time, s->avctx->time_base.num);
2315     else
2316         pts = AV_NOPTS_VALUE;
2317     if (s->avctx->debug&FF_DEBUG_PTS)
2318         av_log(s->avctx, AV_LOG_DEBUG, "MPEG4 PTS: %"PRId64"\n",
2319                pts);
2320
2321     check_marker(gb, "before vop_coded");
2322
2323     /* vop coded */
2324     if (get_bits1(gb) != 1) {
2325         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2326             av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
2327         return FRAME_SKIPPED;
2328     }
2329     if (ctx->new_pred)
2330         decode_new_pred(ctx, gb);
2331
2332     if (ctx->shape != BIN_ONLY_SHAPE &&
2333                     (s->pict_type == AV_PICTURE_TYPE_P ||
2334                      (s->pict_type == AV_PICTURE_TYPE_S &&
2335                       ctx->vol_sprite_usage == GMC_SPRITE))) {
2336         /* rounding type for motion estimation */
2337         s->no_rounding = get_bits1(gb);
2338     } else {
2339         s->no_rounding = 0;
2340     }
2341     // FIXME reduced res stuff
2342
2343     if (ctx->shape != RECT_SHAPE) {
2344         if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
2345             skip_bits(gb, 13);  /* width */
2346             skip_bits1(gb);     /* marker */
2347             skip_bits(gb, 13);  /* height */
2348             skip_bits1(gb);     /* marker */
2349             skip_bits(gb, 13);  /* hor_spat_ref */
2350             skip_bits1(gb);     /* marker */
2351             skip_bits(gb, 13);  /* ver_spat_ref */
2352         }
2353         skip_bits1(gb);         /* change_CR_disable */
2354
2355         if (get_bits1(gb) != 0)
2356             skip_bits(gb, 8);   /* constant_alpha_value */
2357     }
2358
2359     // FIXME complexity estimation stuff
2360
2361     if (ctx->shape != BIN_ONLY_SHAPE) {
2362         skip_bits_long(gb, ctx->cplx_estimation_trash_i);
2363         if (s->pict_type != AV_PICTURE_TYPE_I)
2364             skip_bits_long(gb, ctx->cplx_estimation_trash_p);
2365         if (s->pict_type == AV_PICTURE_TYPE_B)
2366             skip_bits_long(gb, ctx->cplx_estimation_trash_b);
2367
2368         if (get_bits_left(gb) < 3) {
2369             av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");
2370             return -1;
2371         }
2372         ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
2373         if (!s->progressive_sequence) {
2374             s->top_field_first = get_bits1(gb);
2375             s->alternate_scan  = get_bits1(gb);
2376         } else
2377             s->alternate_scan = 0;
2378     }
2379
2380     if (s->alternate_scan) {
2381         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable,   ff_alternate_vertical_scan);
2382         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable,   ff_alternate_vertical_scan);
2383         ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
2384         ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2385     } else {
2386         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable,   ff_zigzag_direct);
2387         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable,   ff_zigzag_direct);
2388         ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
2389         ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2390     }
2391
2392     if (s->pict_type == AV_PICTURE_TYPE_S &&
2393         (ctx->vol_sprite_usage == STATIC_SPRITE ||
2394          ctx->vol_sprite_usage == GMC_SPRITE)) {
2395         if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
2396             return AVERROR_INVALIDDATA;
2397         if (ctx->sprite_brightness_change)
2398             av_log(s->avctx, AV_LOG_ERROR,
2399                    "sprite_brightness_change not supported\n");
2400         if (ctx->vol_sprite_usage == STATIC_SPRITE)
2401             av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
2402     }
2403
2404     if (ctx->shape != BIN_ONLY_SHAPE) {
2405         s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);
2406         if (s->qscale == 0) {
2407             av_log(s->avctx, AV_LOG_ERROR,
2408                    "Error, header damaged or not MPEG4 header (qscale=0)\n");
2409             return -1;  // makes no sense to continue, as there is nothing left from the image then
2410         }
2411
2412         if (s->pict_type != AV_PICTURE_TYPE_I) {
2413             s->f_code = get_bits(gb, 3);        /* fcode_for */
2414             if (s->f_code == 0) {
2415                 av_log(s->avctx, AV_LOG_ERROR,
2416                        "Error, header damaged or not MPEG4 header (f_code=0)\n");
2417                 s->f_code = 1;
2418                 return -1;  // makes no sense to continue, as there is nothing left from the image then
2419             }
2420         } else
2421             s->f_code = 1;
2422
2423         if (s->pict_type == AV_PICTURE_TYPE_B) {
2424             s->b_code = get_bits(gb, 3);
2425             if (s->b_code == 0) {
2426                 av_log(s->avctx, AV_LOG_ERROR,
2427                        "Error, header damaged or not MPEG4 header (b_code=0)\n");
2428                 s->b_code=1;
2429                 return -1; // makes no sense to continue, as the MV decoding will break very quickly
2430             }
2431         } else
2432             s->b_code = 1;
2433
2434         if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
2435             av_log(s->avctx, AV_LOG_DEBUG,
2436                    "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",
2437                    s->qscale, s->f_code, s->b_code,
2438                    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")),
2439                    gb->size_in_bits,s->progressive_sequence, s->alternate_scan,
2440                    s->top_field_first, s->quarter_sample ? "q" : "h",
2441                    s->data_partitioning, ctx->resync_marker,
2442                    ctx->num_sprite_warping_points, s->sprite_warping_accuracy,
2443                    1 - s->no_rounding, s->vo_type,
2444                    s->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
2445                    ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
2446                    ctx->cplx_estimation_trash_b,
2447                    s->time,
2448                    time_increment
2449                   );
2450         }
2451
2452         if (!ctx->scalability) {
2453             if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
2454                 skip_bits1(gb);  // vop shape coding type
2455         } else {
2456             if (ctx->enhancement_type) {
2457                 int load_backward_shape = get_bits1(gb);
2458                 if (load_backward_shape)
2459                     av_log(s->avctx, AV_LOG_ERROR,
2460                            "load backward shape isn't supported\n");
2461             }
2462             skip_bits(gb, 2);  // ref_select_code
2463         }
2464     }
2465     /* detect buggy encoders which don't set the low_delay flag
2466      * (divx4/xvid/opendivx). Note we cannot detect divx5 without b-frames
2467      * easily (although it's buggy too) */
2468     if (s->vo_type == 0 && s->vol_control_parameters == 0 &&
2469         ctx->divx_version == -1 && s->picture_number == 0) {
2470         av_log(s->avctx, AV_LOG_WARNING,
2471                "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
2472         s->low_delay = 1;
2473     }
2474
2475     s->picture_number++;  // better than pic number==0 always ;)
2476
2477     // FIXME add short header support
2478     s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
2479     s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
2480
2481     if (s->workaround_bugs & FF_BUG_EDGE) {
2482         s->h_edge_pos = s->width;
2483         s->v_edge_pos = s->height;
2484     }
2485     return 0;
2486 }
2487
2488 /**
2489  * Decode mpeg4 headers.
2490  * @return <0 if no VOP found (or a damaged one)
2491  *         FRAME_SKIPPED if a not coded VOP is found
2492  *         0 if a VOP is found
2493  */
2494 int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
2495 {
2496     MpegEncContext *s = &ctx->m;
2497     unsigned startcode, v;
2498
2499     /* search next start code */
2500     align_get_bits(gb);
2501
2502     if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
2503         skip_bits(gb, 24);
2504         if (get_bits(gb, 8) == 0xF0)
2505             goto end;
2506     }
2507
2508     startcode = 0xff;
2509     for (;;) {
2510         if (get_bits_count(gb) >= gb->size_in_bits) {
2511             if (gb->size_in_bits == 8 &&
2512                 (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
2513                 av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
2514                 return FRAME_SKIPPED;  // divx bug
2515             } else
2516                 return -1;  // end of stream
2517         }
2518
2519         /* use the bits after the test */
2520         v = get_bits(gb, 8);
2521         startcode = ((startcode << 8) | v) & 0xffffffff;
2522
2523         if ((startcode & 0xFFFFFF00) != 0x100)
2524             continue;  // no startcode
2525
2526         if (s->avctx->debug & FF_DEBUG_STARTCODE) {
2527             av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
2528             if (startcode <= 0x11F)
2529                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
2530             else if (startcode <= 0x12F)
2531                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
2532             else if (startcode <= 0x13F)
2533                 av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2534             else if (startcode <= 0x15F)
2535                 av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
2536             else if (startcode <= 0x1AF)
2537                 av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2538             else if (startcode == 0x1B0)
2539                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
2540             else if (startcode == 0x1B1)
2541                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
2542             else if (startcode == 0x1B2)
2543                 av_log(s->avctx, AV_LOG_DEBUG, "User Data");
2544             else if (startcode == 0x1B3)
2545                 av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
2546             else if (startcode == 0x1B4)
2547                 av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
2548             else if (startcode == 0x1B5)
2549                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
2550             else if (startcode == 0x1B6)
2551                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
2552             else if (startcode == 0x1B7)
2553                 av_log(s->avctx, AV_LOG_DEBUG, "slice start");
2554             else if (startcode == 0x1B8)
2555                 av_log(s->avctx, AV_LOG_DEBUG, "extension start");
2556             else if (startcode == 0x1B9)
2557                 av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
2558             else if (startcode == 0x1BA)
2559                 av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
2560             else if (startcode == 0x1BB)
2561                 av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
2562             else if (startcode == 0x1BC)
2563                 av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
2564             else if (startcode == 0x1BD)
2565                 av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
2566             else if (startcode == 0x1BE)
2567                 av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
2568             else if (startcode == 0x1BF)
2569                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
2570             else if (startcode == 0x1C0)
2571                 av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
2572             else if (startcode == 0x1C1)
2573                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
2574             else if (startcode == 0x1C2)
2575                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
2576             else if (startcode == 0x1C3)
2577                 av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
2578             else if (startcode <= 0x1C5)
2579                 av_log(s->avctx, AV_LOG_DEBUG, "reserved");
2580             else if (startcode <= 0x1FF)
2581                 av_log(s->avctx, AV_LOG_DEBUG, "System start");
2582             av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
2583         }
2584
2585         if (startcode >= 0x120 && startcode <= 0x12F) {
2586             if (decode_vol_header(ctx, gb) < 0)
2587                 return -1;
2588         } else if (startcode == USER_DATA_STARTCODE) {
2589             decode_user_data(ctx, gb);
2590         } else if (startcode == GOP_STARTCODE) {
2591             mpeg4_decode_gop_header(s, gb);
2592         } else if (startcode == VOS_STARTCODE) {
2593             mpeg4_decode_profile_level(s, gb);
2594         } else if (startcode == VOP_STARTCODE) {
2595             break;
2596         }
2597
2598         align_get_bits(gb);
2599         startcode = 0xff;
2600     }
2601
2602 end:
2603     if (s->flags & CODEC_FLAG_LOW_DELAY)
2604         s->low_delay = 1;
2605     s->avctx->has_b_frames = !s->low_delay;
2606
2607     return decode_vop_header(ctx, gb);
2608 }
2609
2610 av_cold void ff_mpeg4videodec_static_init(void) {
2611     static int done = 0;
2612
2613     if (!done) {
2614         ff_init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
2615         ff_init_rl(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
2616         ff_init_rl(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
2617         INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
2618         INIT_VLC_RL(ff_rvlc_rl_inter, 1072);
2619         INIT_VLC_RL(ff_rvlc_rl_intra, 1072);
2620         INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2621                         &ff_mpeg4_DCtab_lum[0][1], 2, 1,
2622                         &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
2623         INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2624                         &ff_mpeg4_DCtab_chrom[0][1], 2, 1,
2625                         &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
2626         INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2627                         &ff_sprite_trajectory_tab[0][1], 4, 2,
2628                         &ff_sprite_trajectory_tab[0][0], 4, 2, 128);
2629         INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2630                         &ff_mb_type_b_tab[0][1], 2, 1,
2631                         &ff_mb_type_b_tab[0][0], 2, 1, 16);
2632         done = 1;
2633     }
2634 }
2635
2636 int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
2637 {
2638     Mpeg4DecContext *ctx = avctx->priv_data;
2639     MpegEncContext    *s = &ctx->m;
2640
2641     /* divx 5.01+ bitstream reorder stuff */
2642     /* Since this clobbers the input buffer and hwaccel codecs still need the
2643      * data during hwaccel->end_frame we should not do this any earlier */
2644     if (s->divx_packed) {
2645         int current_pos     = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);
2646         int startcode_found = 0;
2647
2648         if (buf_size - current_pos > 7) {
2649
2650             int i;
2651             for (i = current_pos; i < buf_size - 4; i++)
2652
2653                 if (buf[i]     == 0 &&
2654                     buf[i + 1] == 0 &&
2655                     buf[i + 2] == 1 &&
2656                     buf[i + 3] == 0xB6) {
2657                     startcode_found = !(buf[i + 4] & 0x40);
2658                     break;
2659                 }
2660         }
2661
2662         if (startcode_found) {
2663             av_fast_padded_malloc(&s->bitstream_buffer,
2664                            &s->allocated_bitstream_buffer_size,
2665                            buf_size - current_pos);
2666             if (!s->bitstream_buffer)
2667                 return AVERROR(ENOMEM);
2668             memcpy(s->bitstream_buffer, buf + current_pos,
2669                    buf_size - current_pos);
2670             s->bitstream_buffer_size = buf_size - current_pos;
2671         }
2672     }
2673
2674     return 0;
2675 }
2676
2677 static int mpeg4_update_thread_context(AVCodecContext *dst,
2678                                        const AVCodecContext *src)
2679 {
2680     Mpeg4DecContext *s = dst->priv_data;
2681     const Mpeg4DecContext *s1 = src->priv_data;
2682
2683     int ret = ff_mpeg_update_thread_context(dst, src);
2684
2685     if (ret < 0)
2686         return ret;
2687
2688     memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext));
2689
2690     return 0;
2691 }
2692
2693 static av_cold int decode_init(AVCodecContext *avctx)
2694 {
2695     Mpeg4DecContext *ctx = avctx->priv_data;
2696     MpegEncContext *s = &ctx->m;
2697     int ret;
2698
2699     ctx->divx_version =
2700     ctx->divx_build   =
2701     ctx->xvid_build   =
2702     ctx->lavc_build   = -1;
2703
2704     if ((ret = ff_h263_decode_init(avctx)) < 0)
2705         return ret;
2706
2707     ff_mpeg4videodec_static_init();
2708
2709     s->h263_pred = 1;
2710     s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */
2711     s->decode_mb = mpeg4_decode_mb;
2712     ctx->time_increment_bits = 4; /* default value for broken headers */
2713
2714     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
2715     avctx->internal->allocate_progress = 1;
2716
2717     return 0;
2718 }
2719
2720 static const AVProfile mpeg4_video_profiles[] = {
2721     { FF_PROFILE_MPEG4_SIMPLE,                    "Simple Profile" },
2722     { FF_PROFILE_MPEG4_SIMPLE_SCALABLE,           "Simple Scalable Profile" },
2723     { FF_PROFILE_MPEG4_CORE,                      "Core Profile" },
2724     { FF_PROFILE_MPEG4_MAIN,                      "Main Profile" },
2725     { FF_PROFILE_MPEG4_N_BIT,                     "N-bit Profile" },
2726     { FF_PROFILE_MPEG4_SCALABLE_TEXTURE,          "Scalable Texture Profile" },
2727     { FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION,     "Simple Face Animation Profile" },
2728     { FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE,    "Basic Animated Texture Profile" },
2729     { FF_PROFILE_MPEG4_HYBRID,                    "Hybrid Profile" },
2730     { FF_PROFILE_MPEG4_ADVANCED_REAL_TIME,        "Advanced Real Time Simple Profile" },
2731     { FF_PROFILE_MPEG4_CORE_SCALABLE,             "Code Scalable Profile" },
2732     { FF_PROFILE_MPEG4_ADVANCED_CODING,           "Advanced Coding Profile" },
2733     { FF_PROFILE_MPEG4_ADVANCED_CORE,             "Advanced Core Profile" },
2734     { FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE, "Advanced Scalable Texture Profile" },
2735     { FF_PROFILE_MPEG4_SIMPLE_STUDIO,             "Simple Studio Profile" },
2736     { FF_PROFILE_MPEG4_ADVANCED_SIMPLE,           "Advanced Simple Profile" },
2737     { FF_PROFILE_UNKNOWN },
2738 };
2739
2740 static const AVOption mpeg4_options[] = {
2741     {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
2742     {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
2743     {NULL}
2744 };
2745
2746 static const AVClass mpeg4_class = {
2747     "MPEG4 Video Decoder",
2748     av_default_item_name,
2749     mpeg4_options,
2750     LIBAVUTIL_VERSION_INT,
2751 };
2752
2753 static const AVClass mpeg4_vdpau_class = {
2754     "MPEG4 Video VDPAU Decoder",
2755     av_default_item_name,
2756     mpeg4_options,
2757     LIBAVUTIL_VERSION_INT,
2758 };
2759
2760 AVCodec ff_mpeg4_decoder = {
2761     .name                  = "mpeg4",
2762     .long_name             = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
2763     .type                  = AVMEDIA_TYPE_VIDEO,
2764     .id                    = AV_CODEC_ID_MPEG4,
2765     .priv_data_size        = sizeof(Mpeg4DecContext),
2766     .init                  = decode_init,
2767     .close                 = ff_h263_decode_end,
2768     .decode                = ff_h263_decode_frame,
2769     .capabilities          = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2770                              CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2771                              CODEC_CAP_FRAME_THREADS,
2772     .flush                 = ff_mpeg_flush,
2773     .max_lowres            = 3,
2774     .pix_fmts              = ff_h263_hwaccel_pixfmt_list_420,
2775     .profiles              = NULL_IF_CONFIG_SMALL(mpeg4_video_profiles),
2776     .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context),
2777     .priv_class = &mpeg4_class,
2778 };
2779
2780
2781 #if CONFIG_MPEG4_VDPAU_DECODER
2782 AVCodec ff_mpeg4_vdpau_decoder = {
2783     .name           = "mpeg4_vdpau",
2784     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 part 2 (VDPAU)"),
2785     .type           = AVMEDIA_TYPE_VIDEO,
2786     .id             = AV_CODEC_ID_MPEG4,
2787     .priv_data_size = sizeof(MpegEncContext),
2788     .init           = decode_init,
2789     .close          = ff_h263_decode_end,
2790     .decode         = ff_h263_decode_frame,
2791     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2792                       CODEC_CAP_HWACCEL_VDPAU,
2793     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_MPEG4,
2794                                                   AV_PIX_FMT_NONE },
2795     .priv_class     = &mpeg4_vdpau_class,
2796 };
2797 #endif