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