avcodec: more correct printf specifiers
[ffmpeg.git] / libavcodec / mpeg12dec.c
1 /*
2  * MPEG-1/2 decoder
3  * Copyright (c) 2000, 2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * MPEG-1/2 decoder
26  */
27
28 #include <inttypes.h>
29
30 #include "libavutil/attributes.h"
31 #include "libavutil/internal.h"
32 #include "libavutil/stereo3d.h"
33
34 #include "avcodec.h"
35 #include "bytestream.h"
36 #include "dsputil.h"
37 #include "error_resilience.h"
38 #include "internal.h"
39 #include "mpeg12.h"
40 #include "mpeg12data.h"
41 #include "mpegutils.h"
42 #include "mpegvideo.h"
43 #include "thread.h"
44 #include "version.h"
45 #include "xvmc_internal.h"
46
47 typedef struct Mpeg1Context {
48     MpegEncContext mpeg_enc_ctx;
49     int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
50     int repeat_field;           /* true if we must repeat the field */
51     AVPanScan pan_scan;         /* some temporary storage for the panscan */
52     AVStereo3D stereo3d;
53     int has_stereo3d;
54     uint8_t *a53_caption;
55     int a53_caption_size;
56     int slice_count;
57     int save_aspect_info;
58     int save_width, save_height, save_progressive_seq;
59     AVRational frame_rate_ext;  /* MPEG-2 specific framerate modificator */
60     int sync;                   /* Did we reach a sync point like a GOP/SEQ/KEYFrame? */
61     int closed_gop;             /* GOP is closed */
62     int first_slice;
63     int extradata_decoded;
64 } Mpeg1Context;
65
66 #define MB_TYPE_ZERO_MV   0x20000000
67
68 static const uint32_t ptype2mb_type[7] = {
69                     MB_TYPE_INTRA,
70                     MB_TYPE_L0 | MB_TYPE_CBP | MB_TYPE_ZERO_MV | MB_TYPE_16x16,
71                     MB_TYPE_L0,
72                     MB_TYPE_L0 | MB_TYPE_CBP,
73     MB_TYPE_QUANT | MB_TYPE_INTRA,
74     MB_TYPE_QUANT | MB_TYPE_L0 | MB_TYPE_CBP | MB_TYPE_ZERO_MV | MB_TYPE_16x16,
75     MB_TYPE_QUANT | MB_TYPE_L0 | MB_TYPE_CBP,
76 };
77
78 static const uint32_t btype2mb_type[11] = {
79                     MB_TYPE_INTRA,
80                     MB_TYPE_L1,
81                     MB_TYPE_L1   | MB_TYPE_CBP,
82                     MB_TYPE_L0,
83                     MB_TYPE_L0   | MB_TYPE_CBP,
84                     MB_TYPE_L0L1,
85                     MB_TYPE_L0L1 | MB_TYPE_CBP,
86     MB_TYPE_QUANT | MB_TYPE_INTRA,
87     MB_TYPE_QUANT | MB_TYPE_L1   | MB_TYPE_CBP,
88     MB_TYPE_QUANT | MB_TYPE_L0   | MB_TYPE_CBP,
89     MB_TYPE_QUANT | MB_TYPE_L0L1 | MB_TYPE_CBP,
90 };
91
92 static const uint8_t non_linear_qscale[32] = {
93      0,  1,  2,  3,  4,  5,   6,   7,
94      8, 10, 12, 14, 16, 18,  20,  22,
95     24, 28, 32, 36, 40, 44,  48,  52,
96     56, 64, 72, 80, 88, 96, 104, 112,
97 };
98
99 /* as H.263, but only 17 codes */
100 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
101 {
102     int code, sign, val, shift;
103
104     code = get_vlc2(&s->gb, ff_mv_vlc.table, MV_VLC_BITS, 2);
105     if (code == 0)
106         return pred;
107     if (code < 0)
108         return 0xffff;
109
110     sign  = get_bits1(&s->gb);
111     shift = fcode - 1;
112     val   = code;
113     if (shift) {
114         val  = (val - 1) << shift;
115         val |= get_bits(&s->gb, shift);
116         val++;
117     }
118     if (sign)
119         val = -val;
120     val += pred;
121
122     /* modulo decoding */
123     return sign_extend(val, 5 + shift);
124 }
125
126 #define check_scantable_index(ctx, x)                                         \
127     do {                                                                      \
128         if ((x) > 63) {                                                       \
129             av_log(ctx->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n",     \
130                    ctx->mb_x, ctx->mb_y);                                     \
131             return AVERROR_INVALIDDATA;                                       \
132         }                                                                     \
133     } while (0)
134
135 static inline int mpeg1_decode_block_intra(MpegEncContext *s,
136                                            int16_t *block, int n)
137 {
138     int level, dc, diff, i, j, run;
139     int component;
140     RLTable *rl                  = &ff_rl_mpeg1;
141     uint8_t *const scantable     = s->intra_scantable.permutated;
142     const uint16_t *quant_matrix = s->intra_matrix;
143     const int qscale             = s->qscale;
144
145     /* DC coefficient */
146     component = (n <= 3 ? 0 : n - 4 + 1);
147     diff = decode_dc(&s->gb, component);
148     if (diff >= 0xffff)
149         return -1;
150     dc  = s->last_dc[component];
151     dc += diff;
152     s->last_dc[component] = dc;
153     block[0] = dc * quant_matrix[0];
154     av_dlog(s->avctx, "dc=%d diff=%d\n", dc, diff);
155     i = 0;
156     {
157         OPEN_READER(re, &s->gb);
158         /* now quantify & encode AC coefficients */
159         for (;;) {
160             UPDATE_CACHE(re, &s->gb);
161             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
162                        TEX_VLC_BITS, 2, 0);
163
164             if (level == 127) {
165                 break;
166             } else if (level != 0) {
167                 i += run;
168                 check_scantable_index(s, i);
169                 j = scantable[i];
170                 level = (level * qscale * quant_matrix[j]) >> 4;
171                 level = (level - 1) | 1;
172                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
173                         SHOW_SBITS(re, &s->gb, 1);
174                 LAST_SKIP_BITS(re, &s->gb, 1);
175             } else {
176                 /* escape */
177                 run = SHOW_UBITS(re, &s->gb, 6) + 1;
178                 LAST_SKIP_BITS(re, &s->gb, 6);
179                 UPDATE_CACHE(re, &s->gb);
180                 level = SHOW_SBITS(re, &s->gb, 8);
181                 SKIP_BITS(re, &s->gb, 8);
182                 if (level == -128) {
183                     level = SHOW_UBITS(re, &s->gb, 8) - 256;
184                     LAST_SKIP_BITS(re, &s->gb, 8);
185                 } else if (level == 0) {
186                     level = SHOW_UBITS(re, &s->gb, 8);
187                     LAST_SKIP_BITS(re, &s->gb, 8);
188                 }
189                 i += run;
190                 check_scantable_index(s, i);
191                 j = scantable[i];
192                 if (level < 0) {
193                     level = -level;
194                     level = (level * qscale * quant_matrix[j]) >> 4;
195                     level = (level - 1) | 1;
196                     level = -level;
197                 } else {
198                     level = (level * qscale * quant_matrix[j]) >> 4;
199                     level = (level - 1) | 1;
200                 }
201             }
202
203             block[j] = level;
204         }
205         CLOSE_READER(re, &s->gb);
206     }
207     s->block_last_index[n] = i;
208     return 0;
209 }
210
211 int ff_mpeg1_decode_block_intra(MpegEncContext *s, int16_t *block, int n)
212 {
213     return mpeg1_decode_block_intra(s, block, n);
214 }
215
216 static inline int mpeg1_decode_block_inter(MpegEncContext *s,
217                                            int16_t *block, int n)
218 {
219     int level, i, j, run;
220     RLTable *rl                  = &ff_rl_mpeg1;
221     uint8_t *const scantable     = s->intra_scantable.permutated;
222     const uint16_t *quant_matrix = s->inter_matrix;
223     const int qscale             = s->qscale;
224
225     {
226         OPEN_READER(re, &s->gb);
227         i = -1;
228         // special case for first coefficient, no need to add second VLC table
229         UPDATE_CACHE(re, &s->gb);
230         if (((int32_t) GET_CACHE(re, &s->gb)) < 0) {
231             level = (3 * qscale * quant_matrix[0]) >> 5;
232             level = (level - 1) | 1;
233             if (GET_CACHE(re, &s->gb) & 0x40000000)
234                 level = -level;
235             block[0] = level;
236             i++;
237             SKIP_BITS(re, &s->gb, 2);
238             if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
239                 goto end;
240         }
241         /* now quantify & encode AC coefficients */
242         for (;;) {
243             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
244                        TEX_VLC_BITS, 2, 0);
245
246             if (level != 0) {
247                 i += run;
248                 check_scantable_index(s, i);
249                 j = scantable[i];
250                 level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
251                 level = (level - 1) | 1;
252                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
253                         SHOW_SBITS(re, &s->gb, 1);
254                 SKIP_BITS(re, &s->gb, 1);
255             } else {
256                 /* escape */
257                 run = SHOW_UBITS(re, &s->gb, 6) + 1;
258                 LAST_SKIP_BITS(re, &s->gb, 6);
259                 UPDATE_CACHE(re, &s->gb);
260                 level = SHOW_SBITS(re, &s->gb, 8);
261                 SKIP_BITS(re, &s->gb, 8);
262                 if (level == -128) {
263                     level = SHOW_UBITS(re, &s->gb, 8) - 256;
264                     SKIP_BITS(re, &s->gb, 8);
265                 } else if (level == 0) {
266                     level = SHOW_UBITS(re, &s->gb, 8);
267                     SKIP_BITS(re, &s->gb, 8);
268                 }
269                 i += run;
270                 check_scantable_index(s, i);
271                 j = scantable[i];
272                 if (level < 0) {
273                     level = -level;
274                     level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
275                     level = (level - 1) | 1;
276                     level = -level;
277                 } else {
278                     level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
279                     level = (level - 1) | 1;
280                 }
281             }
282
283             block[j] = level;
284             if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
285                 break;
286             UPDATE_CACHE(re, &s->gb);
287         }
288 end:
289         LAST_SKIP_BITS(re, &s->gb, 2);
290         CLOSE_READER(re, &s->gb);
291     }
292     s->block_last_index[n] = i;
293     return 0;
294 }
295
296 static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s,
297                                                 int16_t *block, int n)
298 {
299     int level, i, j, run;
300     RLTable *rl              = &ff_rl_mpeg1;
301     uint8_t *const scantable = s->intra_scantable.permutated;
302     const int qscale         = s->qscale;
303
304     {
305         OPEN_READER(re, &s->gb);
306         i = -1;
307         // Special case for first coefficient, no need to add second VLC table.
308         UPDATE_CACHE(re, &s->gb);
309         if (((int32_t) GET_CACHE(re, &s->gb)) < 0) {
310             level = (3 * qscale) >> 1;
311             level = (level - 1) | 1;
312             if (GET_CACHE(re, &s->gb) & 0x40000000)
313                 level = -level;
314             block[0] = level;
315             i++;
316             SKIP_BITS(re, &s->gb, 2);
317             if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
318                 goto end;
319         }
320
321         /* now quantify & encode AC coefficients */
322         for (;;) {
323             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
324                        TEX_VLC_BITS, 2, 0);
325
326             if (level != 0) {
327                 i += run;
328                 check_scantable_index(s, i);
329                 j = scantable[i];
330                 level = ((level * 2 + 1) * qscale) >> 1;
331                 level = (level - 1) | 1;
332                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
333                         SHOW_SBITS(re, &s->gb, 1);
334                 SKIP_BITS(re, &s->gb, 1);
335             } else {
336                 /* escape */
337                 run = SHOW_UBITS(re, &s->gb, 6) + 1;
338                 LAST_SKIP_BITS(re, &s->gb, 6);
339                 UPDATE_CACHE(re, &s->gb);
340                 level = SHOW_SBITS(re, &s->gb, 8);
341                 SKIP_BITS(re, &s->gb, 8);
342                 if (level == -128) {
343                     level = SHOW_UBITS(re, &s->gb, 8) - 256;
344                     SKIP_BITS(re, &s->gb, 8);
345                 } else if (level == 0) {
346                     level = SHOW_UBITS(re, &s->gb, 8);
347                     SKIP_BITS(re, &s->gb, 8);
348                 }
349                 i += run;
350                 check_scantable_index(s, i);
351                 j = scantable[i];
352                 if (level < 0) {
353                     level = -level;
354                     level = ((level * 2 + 1) * qscale) >> 1;
355                     level = (level - 1) | 1;
356                     level = -level;
357                 } else {
358                     level = ((level * 2 + 1) * qscale) >> 1;
359                     level = (level - 1) | 1;
360                 }
361             }
362
363             block[j] = level;
364             if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
365                 break;
366             UPDATE_CACHE(re, &s->gb);
367         }
368 end:
369         LAST_SKIP_BITS(re, &s->gb, 2);
370         CLOSE_READER(re, &s->gb);
371     }
372     s->block_last_index[n] = i;
373     return 0;
374 }
375
376 static inline int mpeg2_decode_block_non_intra(MpegEncContext *s,
377                                                int16_t *block, int n)
378 {
379     int level, i, j, run;
380     RLTable *rl = &ff_rl_mpeg1;
381     uint8_t *const scantable = s->intra_scantable.permutated;
382     const uint16_t *quant_matrix;
383     const int qscale = s->qscale;
384     int mismatch;
385
386     mismatch = 1;
387
388     {
389         OPEN_READER(re, &s->gb);
390         i = -1;
391         if (n < 4)
392             quant_matrix = s->inter_matrix;
393         else
394             quant_matrix = s->chroma_inter_matrix;
395
396         // Special case for first coefficient, no need to add second VLC table.
397         UPDATE_CACHE(re, &s->gb);
398         if (((int32_t) GET_CACHE(re, &s->gb)) < 0) {
399             level = (3 * qscale * quant_matrix[0]) >> 5;
400             if (GET_CACHE(re, &s->gb) & 0x40000000)
401                 level = -level;
402             block[0]  = level;
403             mismatch ^= level;
404             i++;
405             SKIP_BITS(re, &s->gb, 2);
406             if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
407                 goto end;
408         }
409
410         /* now quantify & encode AC coefficients */
411         for (;;) {
412             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
413                        TEX_VLC_BITS, 2, 0);
414
415             if (level != 0) {
416                 i += run;
417                 check_scantable_index(s, i);
418                 j = scantable[i];
419                 level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
420                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
421                         SHOW_SBITS(re, &s->gb, 1);
422                 SKIP_BITS(re, &s->gb, 1);
423             } else {
424                 /* escape */
425                 run = SHOW_UBITS(re, &s->gb, 6) + 1;
426                 LAST_SKIP_BITS(re, &s->gb, 6);
427                 UPDATE_CACHE(re, &s->gb);
428                 level = SHOW_SBITS(re, &s->gb, 12);
429                 SKIP_BITS(re, &s->gb, 12);
430
431                 i += run;
432                 check_scantable_index(s, i);
433                 j = scantable[i];
434                 if (level < 0) {
435                     level = ((-level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
436                     level = -level;
437                 } else {
438                     level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
439                 }
440             }
441
442             mismatch ^= level;
443             block[j]  = level;
444             if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
445                 break;
446             UPDATE_CACHE(re, &s->gb);
447         }
448 end:
449         LAST_SKIP_BITS(re, &s->gb, 2);
450         CLOSE_READER(re, &s->gb);
451     }
452     block[63] ^= (mismatch & 1);
453
454     s->block_last_index[n] = i;
455     return 0;
456 }
457
458 static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s,
459                                                     int16_t *block, int n)
460 {
461     int level, i, j, run;
462     RLTable *rl              = &ff_rl_mpeg1;
463     uint8_t *const scantable = s->intra_scantable.permutated;
464     const int qscale         = s->qscale;
465     OPEN_READER(re, &s->gb);
466     i = -1;
467
468     // special case for first coefficient, no need to add second VLC table
469     UPDATE_CACHE(re, &s->gb);
470     if (((int32_t) GET_CACHE(re, &s->gb)) < 0) {
471         level = (3 * qscale) >> 1;
472         if (GET_CACHE(re, &s->gb) & 0x40000000)
473             level = -level;
474         block[0] = level;
475         i++;
476         SKIP_BITS(re, &s->gb, 2);
477         if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
478             goto end;
479     }
480
481     /* now quantify & encode AC coefficients */
482     for (;;) {
483         GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
484
485         if (level != 0) {
486             i += run;
487             check_scantable_index(s, i);
488             j = scantable[i];
489             level = ((level * 2 + 1) * qscale) >> 1;
490             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
491                     SHOW_SBITS(re, &s->gb, 1);
492             SKIP_BITS(re, &s->gb, 1);
493         } else {
494             /* escape */
495             run = SHOW_UBITS(re, &s->gb, 6) + 1;
496             LAST_SKIP_BITS(re, &s->gb, 6);
497             UPDATE_CACHE(re, &s->gb);
498             level = SHOW_SBITS(re, &s->gb, 12);
499             SKIP_BITS(re, &s->gb, 12);
500
501             i += run;
502             check_scantable_index(s, i);
503             j = scantable[i];
504             if (level < 0) {
505                 level = ((-level * 2 + 1) * qscale) >> 1;
506                 level = -level;
507             } else {
508                 level = ((level * 2 + 1) * qscale) >> 1;
509             }
510         }
511
512         block[j] = level;
513         if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
514             break;
515         UPDATE_CACHE(re, &s->gb);
516     }
517 end:
518     LAST_SKIP_BITS(re, &s->gb, 2);
519     CLOSE_READER(re, &s->gb);
520     s->block_last_index[n] = i;
521     return 0;
522 }
523
524 static inline int mpeg2_decode_block_intra(MpegEncContext *s,
525                                            int16_t *block, int n)
526 {
527     int level, dc, diff, i, j, run;
528     int component;
529     RLTable *rl;
530     uint8_t *const scantable = s->intra_scantable.permutated;
531     const uint16_t *quant_matrix;
532     const int qscale = s->qscale;
533     int mismatch;
534
535     /* DC coefficient */
536     if (n < 4) {
537         quant_matrix = s->intra_matrix;
538         component    = 0;
539     } else {
540         quant_matrix = s->chroma_intra_matrix;
541         component    = (n & 1) + 1;
542     }
543     diff = decode_dc(&s->gb, component);
544     if (diff >= 0xffff)
545         return -1;
546     dc  = s->last_dc[component];
547     dc += diff;
548     s->last_dc[component] = dc;
549     block[0] = dc << (3 - s->intra_dc_precision);
550     av_dlog(s->avctx, "dc=%d\n", block[0]);
551     mismatch = block[0] ^ 1;
552     i = 0;
553     if (s->intra_vlc_format)
554         rl = &ff_rl_mpeg2;
555     else
556         rl = &ff_rl_mpeg1;
557
558     {
559         OPEN_READER(re, &s->gb);
560         /* now quantify & encode AC coefficients */
561         for (;;) {
562             UPDATE_CACHE(re, &s->gb);
563             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
564                        TEX_VLC_BITS, 2, 0);
565
566             if (level == 127) {
567                 break;
568             } else if (level != 0) {
569                 i += run;
570                 check_scantable_index(s, i);
571                 j = scantable[i];
572                 level = (level * qscale * quant_matrix[j]) >> 4;
573                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
574                         SHOW_SBITS(re, &s->gb, 1);
575                 LAST_SKIP_BITS(re, &s->gb, 1);
576             } else {
577                 /* escape */
578                 run = SHOW_UBITS(re, &s->gb, 6) + 1;
579                 LAST_SKIP_BITS(re, &s->gb, 6);
580                 UPDATE_CACHE(re, &s->gb);
581                 level = SHOW_SBITS(re, &s->gb, 12);
582                 SKIP_BITS(re, &s->gb, 12);
583                 i += run;
584                 check_scantable_index(s, i);
585                 j = scantable[i];
586                 if (level < 0) {
587                     level = (-level * qscale * quant_matrix[j]) >> 4;
588                     level = -level;
589                 } else {
590                     level = (level * qscale * quant_matrix[j]) >> 4;
591                 }
592             }
593
594             mismatch ^= level;
595             block[j]  = level;
596         }
597         CLOSE_READER(re, &s->gb);
598     }
599     block[63] ^= mismatch & 1;
600
601     s->block_last_index[n] = i;
602     return 0;
603 }
604
605 static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s,
606                                                 int16_t *block, int n)
607 {
608     int level, dc, diff, i, j, run;
609     int component;
610     RLTable *rl;
611     uint8_t *const scantable = s->intra_scantable.permutated;
612     const uint16_t *quant_matrix;
613     const int qscale = s->qscale;
614
615     /* DC coefficient */
616     if (n < 4) {
617         quant_matrix = s->intra_matrix;
618         component    = 0;
619     } else {
620         quant_matrix = s->chroma_intra_matrix;
621         component    = (n & 1) + 1;
622     }
623     diff = decode_dc(&s->gb, component);
624     if (diff >= 0xffff)
625         return -1;
626     dc = s->last_dc[component];
627     dc += diff;
628     s->last_dc[component] = dc;
629     block[0] = dc << (3 - s->intra_dc_precision);
630     i = 0;
631     if (s->intra_vlc_format)
632         rl = &ff_rl_mpeg2;
633     else
634         rl = &ff_rl_mpeg1;
635
636     {
637         OPEN_READER(re, &s->gb);
638         /* now quantify & encode AC coefficients */
639         for (;;) {
640             UPDATE_CACHE(re, &s->gb);
641             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
642                        TEX_VLC_BITS, 2, 0);
643
644             if (level == 127) {
645                 break;
646             } else if (level != 0) {
647                 i += run;
648                 check_scantable_index(s, i);
649                 j = scantable[i];
650                 level = (level * qscale * quant_matrix[j]) >> 4;
651                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
652                         SHOW_SBITS(re, &s->gb, 1);
653                 LAST_SKIP_BITS(re, &s->gb, 1);
654             } else {
655                 /* escape */
656                 run = SHOW_UBITS(re, &s->gb, 6) + 1;
657                 LAST_SKIP_BITS(re, &s->gb, 6);
658                 UPDATE_CACHE(re, &s->gb);
659                 level = SHOW_SBITS(re, &s->gb, 12);
660                 SKIP_BITS(re, &s->gb, 12);
661                 i += run;
662                 check_scantable_index(s, i);
663                 j = scantable[i];
664                 if (level < 0) {
665                     level = (-level * qscale * quant_matrix[j]) >> 4;
666                     level = -level;
667                 } else {
668                     level = (level * qscale * quant_matrix[j]) >> 4;
669                 }
670             }
671
672             block[j] = level;
673         }
674         CLOSE_READER(re, &s->gb);
675     }
676
677     s->block_last_index[n] = i;
678     return 0;
679 }
680
681 /******************************************/
682 /* decoding */
683
684 static inline int get_dmv(MpegEncContext *s)
685 {
686     if (get_bits1(&s->gb))
687         return 1 - (get_bits1(&s->gb) << 1);
688     else
689         return 0;
690 }
691
692 static inline int get_qscale(MpegEncContext *s)
693 {
694     int qscale = get_bits(&s->gb, 5);
695     if (s->q_scale_type)
696         return non_linear_qscale[qscale];
697     else
698         return qscale << 1;
699 }
700
701 /* motion type (for MPEG-2) */
702 #define MT_FIELD 1
703 #define MT_FRAME 2
704 #define MT_16X8  2
705 #define MT_DMV   3
706
707 static int mpeg_decode_mb(MpegEncContext *s, int16_t block[12][64])
708 {
709     int i, j, k, cbp, val, mb_type, motion_type;
710     const int mb_block_count = 4 + (1 << s->chroma_format);
711
712     av_dlog(s->avctx, "decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
713
714     assert(s->mb_skipped == 0);
715
716     if (s->mb_skip_run-- != 0) {
717         if (s->pict_type == AV_PICTURE_TYPE_P) {
718             s->mb_skipped = 1;
719             s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride] =
720                 MB_TYPE_SKIP | MB_TYPE_L0 | MB_TYPE_16x16;
721         } else {
722             int mb_type;
723
724             if (s->mb_x)
725                 mb_type = s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride - 1];
726             else
727                 // FIXME not sure if this is allowed in MPEG at all
728                 mb_type = s->current_picture.mb_type[s->mb_width + (s->mb_y - 1) * s->mb_stride - 1];
729             if (IS_INTRA(mb_type))
730                 return -1;
731             s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride] =
732                 mb_type | MB_TYPE_SKIP;
733 //            assert(s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride - 1] & (MB_TYPE_16x16 | MB_TYPE_16x8));
734
735             if ((s->mv[0][0][0] | s->mv[0][0][1] | s->mv[1][0][0] | s->mv[1][0][1]) == 0)
736                 s->mb_skipped = 1;
737         }
738
739         return 0;
740     }
741
742     switch (s->pict_type) {
743     default:
744     case AV_PICTURE_TYPE_I:
745         if (get_bits1(&s->gb) == 0) {
746             if (get_bits1(&s->gb) == 0) {
747                 av_log(s->avctx, AV_LOG_ERROR,
748                        "invalid mb type in I Frame at %d %d\n",
749                        s->mb_x, s->mb_y);
750                 return -1;
751             }
752             mb_type = MB_TYPE_QUANT | MB_TYPE_INTRA;
753         } else {
754             mb_type = MB_TYPE_INTRA;
755         }
756         break;
757     case AV_PICTURE_TYPE_P:
758         mb_type = get_vlc2(&s->gb, ff_mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
759         if (mb_type < 0) {
760             av_log(s->avctx, AV_LOG_ERROR,
761                    "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
762             return -1;
763         }
764         mb_type = ptype2mb_type[mb_type];
765         break;
766     case AV_PICTURE_TYPE_B:
767         mb_type = get_vlc2(&s->gb, ff_mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
768         if (mb_type < 0) {
769             av_log(s->avctx, AV_LOG_ERROR,
770                    "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
771             return -1;
772         }
773         mb_type = btype2mb_type[mb_type];
774         break;
775     }
776     av_dlog(s->avctx, "mb_type=%x\n", mb_type);
777 //    motion_type = 0; /* avoid warning */
778     if (IS_INTRA(mb_type)) {
779         s->dsp.clear_blocks(s->block[0]);
780
781         if (!s->chroma_y_shift)
782             s->dsp.clear_blocks(s->block[6]);
783
784         /* compute DCT type */
785         // FIXME: add an interlaced_dct coded var?
786         if (s->picture_structure == PICT_FRAME &&
787             !s->frame_pred_frame_dct)
788             s->interlaced_dct = get_bits1(&s->gb);
789
790         if (IS_QUANT(mb_type))
791             s->qscale = get_qscale(s);
792
793         if (s->concealment_motion_vectors) {
794             /* just parse them */
795             if (s->picture_structure != PICT_FRAME)
796                 skip_bits1(&s->gb);  /* field select */
797
798             s->mv[0][0][0]      =
799             s->last_mv[0][0][0] =
800             s->last_mv[0][1][0] = mpeg_decode_motion(s, s->mpeg_f_code[0][0],
801                                                      s->last_mv[0][0][0]);
802             s->mv[0][0][1]      =
803             s->last_mv[0][0][1] =
804             s->last_mv[0][1][1] = mpeg_decode_motion(s, s->mpeg_f_code[0][1],
805                                                      s->last_mv[0][0][1]);
806
807             skip_bits1(&s->gb); /* marker */
808         } else {
809             /* reset mv prediction */
810             memset(s->last_mv, 0, sizeof(s->last_mv));
811         }
812         s->mb_intra = 1;
813 #if FF_API_XVMC
814 FF_DISABLE_DEPRECATION_WARNINGS
815         // if 1, we memcpy blocks in xvmcvideo
816         if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration > 1)
817             ff_xvmc_pack_pblocks(s, -1); // inter are always full blocks
818 FF_ENABLE_DEPRECATION_WARNINGS
819 #endif /* FF_API_XVMC */
820
821         if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
822             if (s->flags2 & CODEC_FLAG2_FAST) {
823                 for (i = 0; i < 6; i++)
824                     mpeg2_fast_decode_block_intra(s, *s->pblocks[i], i);
825             } else {
826                 for (i = 0; i < mb_block_count; i++)
827                     if (mpeg2_decode_block_intra(s, *s->pblocks[i], i) < 0)
828                         return -1;
829             }
830         } else {
831             for (i = 0; i < 6; i++)
832                 if (mpeg1_decode_block_intra(s, *s->pblocks[i], i) < 0)
833                     return -1;
834         }
835     } else {
836         if (mb_type & MB_TYPE_ZERO_MV) {
837             assert(mb_type & MB_TYPE_CBP);
838
839             s->mv_dir = MV_DIR_FORWARD;
840             if (s->picture_structure == PICT_FRAME) {
841                 if (!s->frame_pred_frame_dct)
842                     s->interlaced_dct = get_bits1(&s->gb);
843                 s->mv_type = MV_TYPE_16X16;
844             } else {
845                 s->mv_type            = MV_TYPE_FIELD;
846                 mb_type              |= MB_TYPE_INTERLACED;
847                 s->field_select[0][0] = s->picture_structure - 1;
848             }
849
850             if (IS_QUANT(mb_type))
851                 s->qscale = get_qscale(s);
852
853             s->last_mv[0][0][0] = 0;
854             s->last_mv[0][0][1] = 0;
855             s->last_mv[0][1][0] = 0;
856             s->last_mv[0][1][1] = 0;
857             s->mv[0][0][0]      = 0;
858             s->mv[0][0][1]      = 0;
859         } else {
860             assert(mb_type & MB_TYPE_L0L1);
861             // FIXME decide if MBs in field pictures are MB_TYPE_INTERLACED
862             /* get additional motion vector type */
863             if (s->frame_pred_frame_dct) {
864                 motion_type = MT_FRAME;
865             } else {
866                 motion_type = get_bits(&s->gb, 2);
867                 if (s->picture_structure == PICT_FRAME && HAS_CBP(mb_type))
868                     s->interlaced_dct = get_bits1(&s->gb);
869             }
870
871             if (IS_QUANT(mb_type))
872                 s->qscale = get_qscale(s);
873
874             /* motion vectors */
875             s->mv_dir = (mb_type >> 13) & 3;
876             av_dlog(s->avctx, "motion_type=%d\n", motion_type);
877             switch (motion_type) {
878             case MT_FRAME: /* or MT_16X8 */
879                 if (s->picture_structure == PICT_FRAME) {
880                     mb_type   |= MB_TYPE_16x16;
881                     s->mv_type = MV_TYPE_16X16;
882                     for (i = 0; i < 2; i++) {
883                         if (USES_LIST(mb_type, i)) {
884                             /* MT_FRAME */
885                             s->mv[i][0][0]      =
886                             s->last_mv[i][0][0] =
887                             s->last_mv[i][1][0] =
888                                 mpeg_decode_motion(s, s->mpeg_f_code[i][0],
889                                                    s->last_mv[i][0][0]);
890                             s->mv[i][0][1]      =
891                             s->last_mv[i][0][1] =
892                             s->last_mv[i][1][1] =
893                                 mpeg_decode_motion(s, s->mpeg_f_code[i][1],
894                                                    s->last_mv[i][0][1]);
895                             /* full_pel: only for MPEG-1 */
896                             if (s->full_pel[i]) {
897                                 s->mv[i][0][0] <<= 1;
898                                 s->mv[i][0][1] <<= 1;
899                             }
900                         }
901                     }
902                 } else {
903                     mb_type   |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
904                     s->mv_type = MV_TYPE_16X8;
905                     for (i = 0; i < 2; i++) {
906                         if (USES_LIST(mb_type, i)) {
907                             /* MT_16X8 */
908                             for (j = 0; j < 2; j++) {
909                                 s->field_select[i][j] = get_bits1(&s->gb);
910                                 for (k = 0; k < 2; k++) {
911                                     val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
912                                                              s->last_mv[i][j][k]);
913                                     s->last_mv[i][j][k] = val;
914                                     s->mv[i][j][k]      = val;
915                                 }
916                             }
917                         }
918                     }
919                 }
920                 break;
921             case MT_FIELD:
922                 s->mv_type = MV_TYPE_FIELD;
923                 if (s->picture_structure == PICT_FRAME) {
924                     mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
925                     for (i = 0; i < 2; i++) {
926                         if (USES_LIST(mb_type, i)) {
927                             for (j = 0; j < 2; j++) {
928                                 s->field_select[i][j] = get_bits1(&s->gb);
929                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
930                                                          s->last_mv[i][j][0]);
931                                 s->last_mv[i][j][0] = val;
932                                 s->mv[i][j][0]      = val;
933                                 av_dlog(s->avctx, "fmx=%d\n", val);
934                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
935                                                          s->last_mv[i][j][1] >> 1);
936                                 s->last_mv[i][j][1] = val << 1;
937                                 s->mv[i][j][1]      = val;
938                                 av_dlog(s->avctx, "fmy=%d\n", val);
939                             }
940                         }
941                     }
942                 } else {
943                     mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
944                     for (i = 0; i < 2; i++) {
945                         if (USES_LIST(mb_type, i)) {
946                             s->field_select[i][0] = get_bits1(&s->gb);
947                             for (k = 0; k < 2; k++) {
948                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
949                                                          s->last_mv[i][0][k]);
950                                 s->last_mv[i][0][k] = val;
951                                 s->last_mv[i][1][k] = val;
952                                 s->mv[i][0][k]      = val;
953                             }
954                         }
955                     }
956                 }
957                 break;
958             case MT_DMV:
959                 s->mv_type = MV_TYPE_DMV;
960                 for (i = 0; i < 2; i++) {
961                     if (USES_LIST(mb_type, i)) {
962                         int dmx, dmy, mx, my, m;
963                         const int my_shift = s->picture_structure == PICT_FRAME;
964
965                         mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
966                                                 s->last_mv[i][0][0]);
967                         s->last_mv[i][0][0] = mx;
968                         s->last_mv[i][1][0] = mx;
969                         dmx = get_dmv(s);
970                         my  = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
971                                                  s->last_mv[i][0][1] >> my_shift);
972                         dmy = get_dmv(s);
973
974
975                         s->last_mv[i][0][1] = my << my_shift;
976                         s->last_mv[i][1][1] = my << my_shift;
977
978                         s->mv[i][0][0] = mx;
979                         s->mv[i][0][1] = my;
980                         s->mv[i][1][0] = mx; // not used
981                         s->mv[i][1][1] = my; // not used
982
983                         if (s->picture_structure == PICT_FRAME) {
984                             mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
985
986                             // m = 1 + 2 * s->top_field_first;
987                             m = s->top_field_first ? 1 : 3;
988
989                             /* top -> top pred */
990                             s->mv[i][2][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
991                             s->mv[i][2][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
992                             m = 4 - m;
993                             s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
994                             s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
995                         } else {
996                             mb_type |= MB_TYPE_16x16;
997
998                             s->mv[i][2][0] = ((mx + (mx > 0)) >> 1) + dmx;
999                             s->mv[i][2][1] = ((my + (my > 0)) >> 1) + dmy;
1000                             if (s->picture_structure == PICT_TOP_FIELD)
1001                                 s->mv[i][2][1]--;
1002                             else
1003                                 s->mv[i][2][1]++;
1004                         }
1005                     }
1006                 }
1007                 break;
1008             default:
1009                 av_log(s->avctx, AV_LOG_ERROR,
1010                        "00 motion_type at %d %d\n", s->mb_x, s->mb_y);
1011                 return -1;
1012             }
1013         }
1014
1015         s->mb_intra = 0;
1016         if (HAS_CBP(mb_type)) {
1017             s->dsp.clear_blocks(s->block[0]);
1018
1019             cbp = get_vlc2(&s->gb, ff_mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
1020             if (mb_block_count > 6) {
1021                 cbp <<= mb_block_count - 6;
1022                 cbp  |= get_bits(&s->gb, mb_block_count - 6);
1023                 s->dsp.clear_blocks(s->block[6]);
1024             }
1025             if (cbp <= 0) {
1026                 av_log(s->avctx, AV_LOG_ERROR,
1027                        "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
1028                 return -1;
1029             }
1030
1031 #if FF_API_XVMC
1032 FF_DISABLE_DEPRECATION_WARNINGS
1033             // if 1, we memcpy blocks in xvmcvideo
1034             if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration > 1)
1035                 ff_xvmc_pack_pblocks(s, cbp);
1036 FF_ENABLE_DEPRECATION_WARNINGS
1037 #endif /* FF_API_XVMC */
1038
1039             if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
1040                 if (s->flags2 & CODEC_FLAG2_FAST) {
1041                     for (i = 0; i < 6; i++) {
1042                         if (cbp & 32)
1043                             mpeg2_fast_decode_block_non_intra(s, *s->pblocks[i], i);
1044                         else
1045                             s->block_last_index[i] = -1;
1046                         cbp += cbp;
1047                     }
1048                 } else {
1049                     cbp <<= 12 - mb_block_count;
1050
1051                     for (i = 0; i < mb_block_count; i++) {
1052                         if (cbp & (1 << 11)) {
1053                             if (mpeg2_decode_block_non_intra(s, *s->pblocks[i], i) < 0)
1054                                 return -1;
1055                         } else {
1056                             s->block_last_index[i] = -1;
1057                         }
1058                         cbp += cbp;
1059                     }
1060                 }
1061             } else {
1062                 if (s->flags2 & CODEC_FLAG2_FAST) {
1063                     for (i = 0; i < 6; i++) {
1064                         if (cbp & 32)
1065                             mpeg1_fast_decode_block_inter(s, *s->pblocks[i], i);
1066                         else
1067                             s->block_last_index[i] = -1;
1068                         cbp += cbp;
1069                     }
1070                 } else {
1071                     for (i = 0; i < 6; i++) {
1072                         if (cbp & 32) {
1073                             if (mpeg1_decode_block_inter(s, *s->pblocks[i], i) < 0)
1074                                 return -1;
1075                         } else {
1076                             s->block_last_index[i] = -1;
1077                         }
1078                         cbp += cbp;
1079                     }
1080                 }
1081             }
1082         } else {
1083             for (i = 0; i < 12; i++)
1084                 s->block_last_index[i] = -1;
1085         }
1086     }
1087
1088     s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride] = mb_type;
1089
1090     return 0;
1091 }
1092
1093 static av_cold int mpeg_decode_init(AVCodecContext *avctx)
1094 {
1095     Mpeg1Context *s    = avctx->priv_data;
1096     MpegEncContext *s2 = &s->mpeg_enc_ctx;
1097     int i;
1098
1099     /* we need some permutation to store matrices,
1100      * until MPV_common_init() sets the real permutation. */
1101     for (i = 0; i < 64; i++)
1102         s2->dsp.idct_permutation[i] = i;
1103
1104     ff_MPV_decode_defaults(s2);
1105
1106     s->mpeg_enc_ctx.avctx  = avctx;
1107     s->mpeg_enc_ctx.flags  = avctx->flags;
1108     s->mpeg_enc_ctx.flags2 = avctx->flags2;
1109     ff_mpeg12_common_init(&s->mpeg_enc_ctx);
1110     ff_mpeg12_init_vlcs();
1111
1112     s->mpeg_enc_ctx_allocated      = 0;
1113     s->mpeg_enc_ctx.picture_number = 0;
1114     s->repeat_field                = 0;
1115     s->mpeg_enc_ctx.codec_id       = avctx->codec->id;
1116     avctx->color_range             = AVCOL_RANGE_MPEG;
1117     if (avctx->codec->id == AV_CODEC_ID_MPEG1VIDEO)
1118         avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1119     else
1120         avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1121     return 0;
1122 }
1123
1124 static int mpeg_decode_update_thread_context(AVCodecContext *avctx,
1125                                              const AVCodecContext *avctx_from)
1126 {
1127     Mpeg1Context *ctx = avctx->priv_data, *ctx_from = avctx_from->priv_data;
1128     MpegEncContext *s = &ctx->mpeg_enc_ctx, *s1 = &ctx_from->mpeg_enc_ctx;
1129     int err;
1130
1131     if (avctx == avctx_from               ||
1132         !ctx_from->mpeg_enc_ctx_allocated ||
1133         !s1->context_initialized)
1134         return 0;
1135
1136     err = ff_mpeg_update_thread_context(avctx, avctx_from);
1137     if (err)
1138         return err;
1139
1140     if (!ctx->mpeg_enc_ctx_allocated)
1141         memcpy(s + 1, s1 + 1, sizeof(Mpeg1Context) - sizeof(MpegEncContext));
1142
1143     if (!(s->pict_type == AV_PICTURE_TYPE_B || s->low_delay))
1144         s->picture_number++;
1145
1146     return 0;
1147 }
1148
1149 static void quant_matrix_rebuild(uint16_t *matrix, const uint8_t *old_perm,
1150                                  const uint8_t *new_perm)
1151 {
1152     uint16_t temp_matrix[64];
1153     int i;
1154
1155     memcpy(temp_matrix, matrix, 64 * sizeof(uint16_t));
1156
1157     for (i = 0; i < 64; i++)
1158         matrix[new_perm[i]] = temp_matrix[old_perm[i]];
1159 }
1160
1161 #if FF_API_XVMC
1162 static const enum AVPixelFormat pixfmt_xvmc_mpg2_420[] = {
1163     AV_PIX_FMT_XVMC_MPEG2_IDCT,
1164     AV_PIX_FMT_XVMC_MPEG2_MC,
1165     AV_PIX_FMT_NONE
1166 };
1167 #endif /* FF_API_XVMC */
1168
1169 static const enum AVPixelFormat mpeg12_hwaccel_pixfmt_list_420[] = {
1170 #if CONFIG_MPEG2_DXVA2_HWACCEL
1171     AV_PIX_FMT_DXVA2_VLD,
1172 #endif
1173 #if CONFIG_MPEG2_VAAPI_HWACCEL
1174     AV_PIX_FMT_VAAPI_VLD,
1175 #endif
1176 #if CONFIG_MPEG1_VDPAU_HWACCEL | CONFIG_MPEG2_VDPAU_HWACCEL
1177     AV_PIX_FMT_VDPAU,
1178 #endif
1179     AV_PIX_FMT_YUV420P,
1180     AV_PIX_FMT_NONE
1181 };
1182
1183 static enum AVPixelFormat mpeg_get_pixelformat(AVCodecContext *avctx)
1184 {
1185     Mpeg1Context *s1  = avctx->priv_data;
1186     MpegEncContext *s = &s1->mpeg_enc_ctx;
1187
1188 #if FF_API_XVMC
1189 FF_DISABLE_DEPRECATION_WARNINGS
1190     if (avctx->xvmc_acceleration)
1191         return avctx->get_format(avctx, pixfmt_xvmc_mpg2_420);
1192 FF_ENABLE_DEPRECATION_WARNINGS
1193 #endif /* FF_API_XVMC */
1194
1195     if (s->chroma_format < 2)
1196         return avctx->get_format(avctx, mpeg12_hwaccel_pixfmt_list_420);
1197     else if (s->chroma_format == 2)
1198         return AV_PIX_FMT_YUV422P;
1199     else
1200         return AV_PIX_FMT_YUV444P;
1201 }
1202
1203 /* Call this function when we know all parameters.
1204  * It may be called in different places for MPEG-1 and MPEG-2. */
1205 static int mpeg_decode_postinit(AVCodecContext *avctx)
1206 {
1207     Mpeg1Context *s1  = avctx->priv_data;
1208     MpegEncContext *s = &s1->mpeg_enc_ctx;
1209     uint8_t old_permutation[64];
1210     int ret;
1211
1212     if ((s1->mpeg_enc_ctx_allocated == 0)                   ||
1213         avctx->coded_width       != s->width                ||
1214         avctx->coded_height      != s->height               ||
1215         s1->save_width           != s->width                ||
1216         s1->save_height          != s->height               ||
1217         s1->save_aspect_info     != s->aspect_ratio_info    ||
1218         s1->save_progressive_seq != s->progressive_sequence ||
1219         0) {
1220         if (s1->mpeg_enc_ctx_allocated) {
1221             ParseContext pc = s->parse_context;
1222             s->parse_context.buffer = 0;
1223             ff_MPV_common_end(s);
1224             s->parse_context = pc;
1225         }
1226
1227         if ((s->width == 0) || (s->height == 0))
1228             return -2;
1229
1230         ret = ff_set_dimensions(avctx, s->width, s->height);
1231         if (ret < 0)
1232             return ret;
1233
1234         avctx->bit_rate          = s->bit_rate;
1235         s1->save_aspect_info     = s->aspect_ratio_info;
1236         s1->save_width           = s->width;
1237         s1->save_height          = s->height;
1238         s1->save_progressive_seq = s->progressive_sequence;
1239
1240         /* low_delay may be forced, in this case we will have B-frames
1241          * that behave like P-frames. */
1242         avctx->has_b_frames = !s->low_delay;
1243
1244         if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
1245             // MPEG-1 fps
1246             avctx->time_base.den = ff_mpeg12_frame_rate_tab[s->frame_rate_index].num;
1247             avctx->time_base.num = ff_mpeg12_frame_rate_tab[s->frame_rate_index].den;
1248             // MPEG-1 aspect
1249             avctx->sample_aspect_ratio = av_d2q(1.0 / ff_mpeg1_aspect[s->aspect_ratio_info], 255);
1250             avctx->ticks_per_frame     = 1;
1251         } else { // MPEG-2
1252             // MPEG-2 fps
1253             av_reduce(&s->avctx->time_base.den,
1254                       &s->avctx->time_base.num,
1255                       ff_mpeg12_frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num * 2,
1256                       ff_mpeg12_frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den,
1257                       1 << 30);
1258             avctx->ticks_per_frame = 2;
1259             // MPEG-2 aspect
1260             if (s->aspect_ratio_info > 1) {
1261                 AVRational dar =
1262                     av_mul_q(av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],
1263                                       (AVRational) { s1->pan_scan.width,
1264                                                      s1->pan_scan.height }),
1265                              (AVRational) { s->width, s->height });
1266
1267                 /* We ignore the spec here and guess a bit as reality does not
1268                  * match the spec, see for example res_change_ffmpeg_aspect.ts
1269                  * and sequence-display-aspect.mpg.
1270                  * issue1613, 621, 562 */
1271                 if ((s1->pan_scan.width == 0) || (s1->pan_scan.height == 0) ||
1272                     (av_cmp_q(dar, (AVRational) { 4, 3 }) &&
1273                      av_cmp_q(dar, (AVRational) { 16, 9 }))) {
1274                     s->avctx->sample_aspect_ratio =
1275                         av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],
1276                                  (AVRational) { s->width, s->height });
1277                 } else {
1278                     s->avctx->sample_aspect_ratio =
1279                         av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],
1280                                  (AVRational) { s1->pan_scan.width, s1->pan_scan.height });
1281 // issue1613 4/3 16/9 -> 16/9
1282 // res_change_ffmpeg_aspect.ts 4/3 225/44 ->4/3
1283 // widescreen-issue562.mpg 4/3 16/9 -> 16/9
1284 //                    s->avctx->sample_aspect_ratio = av_mul_q(s->avctx->sample_aspect_ratio, (AVRational) {s->width, s->height});
1285                     av_dlog(avctx, "A %d/%d\n",
1286                             ff_mpeg2_aspect[s->aspect_ratio_info].num,
1287                             ff_mpeg2_aspect[s->aspect_ratio_info].den);
1288                     av_dlog(avctx, "B %d/%d\n", s->avctx->sample_aspect_ratio.num,
1289                             s->avctx->sample_aspect_ratio.den);
1290                 }
1291             } else {
1292                 s->avctx->sample_aspect_ratio =
1293                     ff_mpeg2_aspect[s->aspect_ratio_info];
1294             }
1295         } // MPEG-2
1296
1297         avctx->pix_fmt = mpeg_get_pixelformat(avctx);
1298         avctx->hwaccel = ff_find_hwaccel(avctx);
1299         // until then pix_fmt may be changed right after codec init
1300 #if FF_API_XVMC
1301         if ((avctx->pix_fmt == AV_PIX_FMT_XVMC_MPEG2_IDCT ||
1302              avctx->hwaccel) && avctx->idct_algo == FF_IDCT_AUTO)
1303 #else
1304         if (avctx->hwaccel && avctx->idct_algo == FF_IDCT_AUTO)
1305 #endif /* FF_API_XVMC */
1306             avctx->idct_algo = FF_IDCT_SIMPLE;
1307
1308         /* Quantization matrices may need reordering
1309          * if DCT permutation is changed. */
1310         memcpy(old_permutation, s->dsp.idct_permutation, 64 * sizeof(uint8_t));
1311
1312         if (ff_MPV_common_init(s) < 0)
1313             return -2;
1314
1315         quant_matrix_rebuild(s->intra_matrix,        old_permutation, s->dsp.idct_permutation);
1316         quant_matrix_rebuild(s->inter_matrix,        old_permutation, s->dsp.idct_permutation);
1317         quant_matrix_rebuild(s->chroma_intra_matrix, old_permutation, s->dsp.idct_permutation);
1318         quant_matrix_rebuild(s->chroma_inter_matrix, old_permutation, s->dsp.idct_permutation);
1319
1320         s1->mpeg_enc_ctx_allocated = 1;
1321     }
1322     return 0;
1323 }
1324
1325 static int mpeg1_decode_picture(AVCodecContext *avctx, const uint8_t *buf,
1326                                 int buf_size)
1327 {
1328     Mpeg1Context *s1  = avctx->priv_data;
1329     MpegEncContext *s = &s1->mpeg_enc_ctx;
1330     int ref, f_code, vbv_delay;
1331
1332     init_get_bits(&s->gb, buf, buf_size * 8);
1333
1334     ref = get_bits(&s->gb, 10); /* temporal ref */
1335     s->pict_type = get_bits(&s->gb, 3);
1336     if (s->pict_type == 0 || s->pict_type > 3)
1337         return -1;
1338
1339     vbv_delay = get_bits(&s->gb, 16);
1340     if (s->pict_type == AV_PICTURE_TYPE_P ||
1341         s->pict_type == AV_PICTURE_TYPE_B) {
1342         s->full_pel[0] = get_bits1(&s->gb);
1343         f_code = get_bits(&s->gb, 3);
1344         if (f_code == 0 && (avctx->err_recognition & AV_EF_BITSTREAM))
1345             return -1;
1346         s->mpeg_f_code[0][0] = f_code;
1347         s->mpeg_f_code[0][1] = f_code;
1348     }
1349     if (s->pict_type == AV_PICTURE_TYPE_B) {
1350         s->full_pel[1] = get_bits1(&s->gb);
1351         f_code = get_bits(&s->gb, 3);
1352         if (f_code == 0 && (avctx->err_recognition & AV_EF_BITSTREAM))
1353             return -1;
1354         s->mpeg_f_code[1][0] = f_code;
1355         s->mpeg_f_code[1][1] = f_code;
1356     }
1357     s->current_picture.f.pict_type = s->pict_type;
1358     s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
1359
1360     if (avctx->debug & FF_DEBUG_PICT_INFO)
1361         av_log(avctx, AV_LOG_DEBUG,
1362                "vbv_delay %d, ref %d type:%d\n", vbv_delay, ref, s->pict_type);
1363
1364     s->y_dc_scale = 8;
1365     s->c_dc_scale = 8;
1366     return 0;
1367 }
1368
1369 static void mpeg_decode_sequence_extension(Mpeg1Context *s1)
1370 {
1371     MpegEncContext *s = &s1->mpeg_enc_ctx;
1372     int horiz_size_ext, vert_size_ext;
1373     int bit_rate_ext;
1374
1375     skip_bits(&s->gb, 1); /* profile and level esc*/
1376     s->avctx->profile       = get_bits(&s->gb, 3);
1377     s->avctx->level         = get_bits(&s->gb, 4);
1378     s->progressive_sequence = get_bits1(&s->gb);   /* progressive_sequence */
1379     s->chroma_format        = get_bits(&s->gb, 2); /* chroma_format 1=420, 2=422, 3=444 */
1380     horiz_size_ext          = get_bits(&s->gb, 2);
1381     vert_size_ext           = get_bits(&s->gb, 2);
1382     s->width  |= (horiz_size_ext << 12);
1383     s->height |= (vert_size_ext  << 12);
1384     bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1385     s->bit_rate += (bit_rate_ext << 18) * 400;
1386     skip_bits1(&s->gb); /* marker */
1387     s->avctx->rc_buffer_size += get_bits(&s->gb, 8) * 1024 * 16 << 10;
1388
1389     s->low_delay = get_bits1(&s->gb);
1390     if (s->flags & CODEC_FLAG_LOW_DELAY)
1391         s->low_delay = 1;
1392
1393     s1->frame_rate_ext.num = get_bits(&s->gb, 2) + 1;
1394     s1->frame_rate_ext.den = get_bits(&s->gb, 5) + 1;
1395
1396     av_dlog(s->avctx, "sequence extension\n");
1397     s->codec_id = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO;
1398
1399     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1400         av_log(s->avctx, AV_LOG_DEBUG,
1401                "profile: %d, level: %d vbv buffer: %d, bitrate:%d\n",
1402                s->avctx->profile, s->avctx->level,
1403                s->avctx->rc_buffer_size, s->bit_rate);
1404 }
1405
1406 static void mpeg_decode_sequence_display_extension(Mpeg1Context *s1)
1407 {
1408     MpegEncContext *s = &s1->mpeg_enc_ctx;
1409     int color_description, w, h;
1410
1411     skip_bits(&s->gb, 3); /* video format */
1412     color_description = get_bits1(&s->gb);
1413     if (color_description) {
1414         s->avctx->color_primaries = get_bits(&s->gb, 8);
1415         s->avctx->color_trc       = get_bits(&s->gb, 8);
1416         s->avctx->colorspace      = get_bits(&s->gb, 8);
1417     }
1418     w = get_bits(&s->gb, 14);
1419     skip_bits(&s->gb, 1); // marker
1420     h = get_bits(&s->gb, 14);
1421     // remaining 3 bits are zero padding
1422
1423     s1->pan_scan.width  = 16 * w;
1424     s1->pan_scan.height = 16 * h;
1425
1426     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1427         av_log(s->avctx, AV_LOG_DEBUG, "sde w:%d, h:%d\n", w, h);
1428 }
1429
1430 static void mpeg_decode_picture_display_extension(Mpeg1Context *s1)
1431 {
1432     MpegEncContext *s = &s1->mpeg_enc_ctx;
1433     int i, nofco;
1434
1435     nofco = 1;
1436     if (s->progressive_sequence) {
1437         if (s->repeat_first_field) {
1438             nofco++;
1439             if (s->top_field_first)
1440                 nofco++;
1441         }
1442     } else {
1443         if (s->picture_structure == PICT_FRAME) {
1444             nofco++;
1445             if (s->repeat_first_field)
1446                 nofco++;
1447         }
1448     }
1449     for (i = 0; i < nofco; i++) {
1450         s1->pan_scan.position[i][0] = get_sbits(&s->gb, 16);
1451         skip_bits(&s->gb, 1); // marker
1452         s1->pan_scan.position[i][1] = get_sbits(&s->gb, 16);
1453         skip_bits(&s->gb, 1); // marker
1454     }
1455
1456     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1457         av_log(s->avctx, AV_LOG_DEBUG,
1458                "pde (%"PRId16",%"PRId16") (%"PRId16",%"PRId16") (%"PRId16",%"PRId16")\n",
1459                s1->pan_scan.position[0][0], s1->pan_scan.position[0][1],
1460                s1->pan_scan.position[1][0], s1->pan_scan.position[1][1],
1461                s1->pan_scan.position[2][0], s1->pan_scan.position[2][1]);
1462 }
1463
1464 static int load_matrix(MpegEncContext *s, uint16_t matrix0[64],
1465                        uint16_t matrix1[64], int intra)
1466 {
1467     int i;
1468
1469     for (i = 0; i < 64; i++) {
1470         int j = s->dsp.idct_permutation[ff_zigzag_direct[i]];
1471         int v = get_bits(&s->gb, 8);
1472         if (v == 0) {
1473             av_log(s->avctx, AV_LOG_ERROR, "matrix damaged\n");
1474             return -1;
1475         }
1476         if (intra && i == 0 && v != 8) {
1477             av_log(s->avctx, AV_LOG_ERROR, "intra matrix invalid, ignoring\n");
1478             v = 8; // needed by pink.mpg / issue1046
1479         }
1480         matrix0[j] = v;
1481         if (matrix1)
1482             matrix1[j] = v;
1483     }
1484     return 0;
1485 }
1486
1487 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1488 {
1489     av_dlog(s->avctx, "matrix extension\n");
1490
1491     if (get_bits1(&s->gb))
1492         load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
1493     if (get_bits1(&s->gb))
1494         load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
1495     if (get_bits1(&s->gb))
1496         load_matrix(s, s->chroma_intra_matrix, NULL, 1);
1497     if (get_bits1(&s->gb))
1498         load_matrix(s, s->chroma_inter_matrix, NULL, 0);
1499 }
1500
1501 static void mpeg_decode_picture_coding_extension(Mpeg1Context *s1)
1502 {
1503     MpegEncContext *s = &s1->mpeg_enc_ctx;
1504
1505     s->full_pel[0]       = s->full_pel[1] = 0;
1506     s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1507     s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1508     s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1509     s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1510     if (!s->pict_type && s1->mpeg_enc_ctx_allocated) {
1511         av_log(s->avctx, AV_LOG_ERROR,
1512                "Missing picture start code, guessing missing values\n");
1513         if (s->mpeg_f_code[1][0] == 15 && s->mpeg_f_code[1][1] == 15) {
1514             if (s->mpeg_f_code[0][0] == 15 && s->mpeg_f_code[0][1] == 15)
1515                 s->pict_type = AV_PICTURE_TYPE_I;
1516             else
1517                 s->pict_type = AV_PICTURE_TYPE_P;
1518         } else
1519             s->pict_type = AV_PICTURE_TYPE_B;
1520         s->current_picture.f.pict_type = s->pict_type;
1521         s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
1522     }
1523     s->intra_dc_precision         = get_bits(&s->gb, 2);
1524     s->picture_structure          = get_bits(&s->gb, 2);
1525     s->top_field_first            = get_bits1(&s->gb);
1526     s->frame_pred_frame_dct       = get_bits1(&s->gb);
1527     s->concealment_motion_vectors = get_bits1(&s->gb);
1528     s->q_scale_type               = get_bits1(&s->gb);
1529     s->intra_vlc_format           = get_bits1(&s->gb);
1530     s->alternate_scan             = get_bits1(&s->gb);
1531     s->repeat_first_field         = get_bits1(&s->gb);
1532     s->chroma_420_type            = get_bits1(&s->gb);
1533     s->progressive_frame          = get_bits1(&s->gb);
1534
1535     if (s->progressive_sequence && !s->progressive_frame) {
1536         s->progressive_frame = 1;
1537         av_log(s->avctx, AV_LOG_ERROR,
1538                "interlaced frame in progressive sequence, ignoring\n");
1539     }
1540
1541     if (s->picture_structure == 0 ||
1542         (s->progressive_frame && s->picture_structure != PICT_FRAME)) {
1543         av_log(s->avctx, AV_LOG_ERROR,
1544                "picture_structure %d invalid, ignoring\n",
1545                s->picture_structure);
1546         s->picture_structure = PICT_FRAME;
1547     }
1548
1549     if (s->progressive_sequence && !s->frame_pred_frame_dct)
1550         av_log(s->avctx, AV_LOG_WARNING, "invalid frame_pred_frame_dct\n");
1551
1552     if (s->picture_structure == PICT_FRAME) {
1553         s->first_field = 0;
1554         s->v_edge_pos  = 16 * s->mb_height;
1555     } else {
1556         s->first_field ^= 1;
1557         s->v_edge_pos   = 8 * s->mb_height;
1558         memset(s->mbskip_table, 0, s->mb_stride * s->mb_height);
1559     }
1560
1561     if (s->alternate_scan) {
1562         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
1563         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
1564     } else {
1565         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
1566         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
1567     }
1568
1569     /* composite display not parsed */
1570     av_dlog(s->avctx, "intra_dc_precision=%d\n", s->intra_dc_precision);
1571     av_dlog(s->avctx, "picture_structure=%d\n", s->picture_structure);
1572     av_dlog(s->avctx, "top field first=%d\n", s->top_field_first);
1573     av_dlog(s->avctx, "repeat first field=%d\n", s->repeat_first_field);
1574     av_dlog(s->avctx, "conceal=%d\n", s->concealment_motion_vectors);
1575     av_dlog(s->avctx, "intra_vlc_format=%d\n", s->intra_vlc_format);
1576     av_dlog(s->avctx, "alternate_scan=%d\n", s->alternate_scan);
1577     av_dlog(s->avctx, "frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1578     av_dlog(s->avctx, "progressive_frame=%d\n", s->progressive_frame);
1579 }
1580
1581 static int mpeg_field_start(MpegEncContext *s, const uint8_t *buf, int buf_size)
1582 {
1583     AVCodecContext *avctx = s->avctx;
1584     Mpeg1Context *s1      = (Mpeg1Context *) s;
1585
1586     /* start frame decoding */
1587     if (s->first_field || s->picture_structure == PICT_FRAME) {
1588         AVFrameSideData *pan_scan;
1589
1590         if (ff_MPV_frame_start(s, avctx) < 0)
1591             return -1;
1592
1593         ff_mpeg_er_frame_start(s);
1594
1595         /* first check if we must repeat the frame */
1596         s->current_picture_ptr->f.repeat_pict = 0;
1597         if (s->repeat_first_field) {
1598             if (s->progressive_sequence) {
1599                 if (s->top_field_first)
1600                     s->current_picture_ptr->f.repeat_pict = 4;
1601                 else
1602                     s->current_picture_ptr->f.repeat_pict = 2;
1603             } else if (s->progressive_frame) {
1604                 s->current_picture_ptr->f.repeat_pict = 1;
1605             }
1606         }
1607
1608         pan_scan = av_frame_new_side_data(&s->current_picture_ptr->f,
1609                                           AV_FRAME_DATA_PANSCAN,
1610                                           sizeof(s1->pan_scan));
1611         if (!pan_scan)
1612             return AVERROR(ENOMEM);
1613         memcpy(pan_scan->data, &s1->pan_scan, sizeof(s1->pan_scan));
1614
1615         if (s1->a53_caption) {
1616             AVFrameSideData *sd = av_frame_new_side_data(
1617                 &s->current_picture_ptr->f, AV_FRAME_DATA_A53_CC,
1618                 s1->a53_caption_size);
1619             if (sd)
1620                 memcpy(sd->data, s1->a53_caption, s1->a53_caption_size);
1621             av_freep(&s1->a53_caption);
1622         }
1623
1624         if (s1->has_stereo3d) {
1625             AVStereo3D *stereo = av_stereo3d_create_side_data(&s->current_picture_ptr->f);
1626             if (!stereo)
1627                 return AVERROR(ENOMEM);
1628
1629             *stereo = s1->stereo3d;
1630             s1->has_stereo3d = 0;
1631         }
1632         if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_FRAME))
1633             ff_thread_finish_setup(avctx);
1634     } else { // second field
1635         int i;
1636
1637         if (!s->current_picture_ptr) {
1638             av_log(s->avctx, AV_LOG_ERROR, "first field missing\n");
1639             return -1;
1640         }
1641
1642         if (s->avctx->hwaccel &&
1643             (s->avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD)) {
1644             if (s->avctx->hwaccel->end_frame(s->avctx) < 0)
1645                 av_log(avctx, AV_LOG_ERROR,
1646                        "hardware accelerator failed to decode first field\n");
1647         }
1648
1649         for (i = 0; i < 4; i++) {
1650             s->current_picture.f.data[i] = s->current_picture_ptr->f.data[i];
1651             if (s->picture_structure == PICT_BOTTOM_FIELD)
1652                 s->current_picture.f.data[i] +=
1653                     s->current_picture_ptr->f.linesize[i];
1654         }
1655     }
1656
1657     if (avctx->hwaccel) {
1658         if (avctx->hwaccel->start_frame(avctx, buf, buf_size) < 0)
1659             return -1;
1660     }
1661
1662 #if FF_API_XVMC
1663 FF_DISABLE_DEPRECATION_WARNINGS
1664 // MPV_frame_start will call this function too,
1665 // but we need to call it on every field
1666     if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)
1667         if (ff_xvmc_field_start(s, avctx) < 0)
1668             return -1;
1669 FF_ENABLE_DEPRECATION_WARNINGS
1670 #endif /* FF_API_XVMC */
1671
1672     return 0;
1673 }
1674
1675 #define DECODE_SLICE_ERROR -1
1676 #define DECODE_SLICE_OK     0
1677
1678 /**
1679  * Decode a slice.
1680  * MpegEncContext.mb_y must be set to the MB row from the startcode.
1681  * @return DECODE_SLICE_ERROR if the slice is damaged,
1682  *         DECODE_SLICE_OK if this slice is OK
1683  */
1684 static int mpeg_decode_slice(MpegEncContext *s, int mb_y,
1685                              const uint8_t **buf, int buf_size)
1686 {
1687     AVCodecContext *avctx = s->avctx;
1688     const int field_pic   = s->picture_structure != PICT_FRAME;
1689
1690     s->resync_mb_x =
1691     s->resync_mb_y = -1;
1692
1693     assert(mb_y < s->mb_height);
1694
1695     init_get_bits(&s->gb, *buf, buf_size * 8);
1696
1697     ff_mpeg1_clean_buffers(s);
1698     s->interlaced_dct = 0;
1699
1700     s->qscale = get_qscale(s);
1701
1702     if (s->qscale == 0) {
1703         av_log(s->avctx, AV_LOG_ERROR, "qscale == 0\n");
1704         return -1;
1705     }
1706
1707     /* extra slice info */
1708     while (get_bits1(&s->gb) != 0)
1709         skip_bits(&s->gb, 8);
1710
1711     s->mb_x = 0;
1712
1713     if (mb_y == 0 && s->codec_tag == AV_RL32("SLIF")) {
1714         skip_bits1(&s->gb);
1715     } else {
1716         while (get_bits_left(&s->gb) > 0) {
1717             int code = get_vlc2(&s->gb, ff_mbincr_vlc.table,
1718                                 MBINCR_VLC_BITS, 2);
1719             if (code < 0) {
1720                 av_log(s->avctx, AV_LOG_ERROR, "first mb_incr damaged\n");
1721                 return -1;
1722             }
1723             if (code >= 33) {
1724                 if (code == 33)
1725                     s->mb_x += 33;
1726                 /* otherwise, stuffing, nothing to do */
1727             } else {
1728                 s->mb_x += code;
1729                 break;
1730             }
1731         }
1732     }
1733
1734     if (s->mb_x >= (unsigned) s->mb_width) {
1735         av_log(s->avctx, AV_LOG_ERROR, "initial skip overflow\n");
1736         return -1;
1737     }
1738
1739     if (avctx->hwaccel) {
1740         const uint8_t *buf_end, *buf_start = *buf - 4; /* include start_code */
1741         int start_code = -1;
1742         buf_end = avpriv_find_start_code(buf_start + 2, *buf + buf_size, &start_code);
1743         if (buf_end < *buf + buf_size)
1744             buf_end -= 4;
1745         s->mb_y = mb_y;
1746         if (avctx->hwaccel->decode_slice(avctx, buf_start, buf_end - buf_start) < 0)
1747             return DECODE_SLICE_ERROR;
1748         *buf = buf_end;
1749         return DECODE_SLICE_OK;
1750     }
1751
1752     s->resync_mb_x = s->mb_x;
1753     s->resync_mb_y = s->mb_y = mb_y;
1754     s->mb_skip_run = 0;
1755     ff_init_block_index(s);
1756
1757     if (s->mb_y == 0 && s->mb_x == 0 && (s->first_field || s->picture_structure == PICT_FRAME)) {
1758         if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
1759             av_log(s->avctx, AV_LOG_DEBUG,
1760                    "qp:%d fc:%2d%2d%2d%2d %s %s %s %s %s dc:%d pstruct:%d fdct:%d cmv:%d qtype:%d ivlc:%d rff:%d %s\n",
1761                    s->qscale,
1762                    s->mpeg_f_code[0][0], s->mpeg_f_code[0][1],
1763                    s->mpeg_f_code[1][0], s->mpeg_f_code[1][1],
1764                    s->pict_type  == AV_PICTURE_TYPE_I ? "I" :
1765                    (s->pict_type == AV_PICTURE_TYPE_P ? "P" :
1766                    (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
1767                    s->progressive_sequence ? "ps"  : "",
1768                    s->progressive_frame    ? "pf"  : "",
1769                    s->alternate_scan       ? "alt" : "",
1770                    s->top_field_first      ? "top" : "",
1771                    s->intra_dc_precision, s->picture_structure,
1772                    s->frame_pred_frame_dct, s->concealment_motion_vectors,
1773                    s->q_scale_type, s->intra_vlc_format,
1774                    s->repeat_first_field, s->chroma_420_type ? "420" : "");
1775         }
1776     }
1777
1778     for (;;) {
1779 #if FF_API_XVMC
1780 FF_DISABLE_DEPRECATION_WARNINGS
1781         // If 1, we memcpy blocks in xvmcvideo.
1782         if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration > 1)
1783             ff_xvmc_init_block(s); // set s->block
1784 FF_ENABLE_DEPRECATION_WARNINGS
1785 #endif /* FF_API_XVMC */
1786
1787         if (mpeg_decode_mb(s, s->block) < 0)
1788             return -1;
1789
1790         // Note motion_val is normally NULL unless we want to extract the MVs.
1791         if (s->current_picture.motion_val[0] && !s->encoding) {
1792             const int wrap = s->b8_stride;
1793             int xy         = s->mb_x * 2 + s->mb_y * 2 * wrap;
1794             int b8_xy      = 4 * (s->mb_x + s->mb_y * s->mb_stride);
1795             int motion_x, motion_y, dir, i;
1796
1797             for (i = 0; i < 2; i++) {
1798                 for (dir = 0; dir < 2; dir++) {
1799                     if (s->mb_intra ||
1800                         (dir == 1 && s->pict_type != AV_PICTURE_TYPE_B)) {
1801                         motion_x = motion_y = 0;
1802                     } else if (s->mv_type == MV_TYPE_16X16 ||
1803                                (s->mv_type == MV_TYPE_FIELD && field_pic)) {
1804                         motion_x = s->mv[dir][0][0];
1805                         motion_y = s->mv[dir][0][1];
1806                     } else { /* if ((s->mv_type == MV_TYPE_FIELD) || (s->mv_type == MV_TYPE_16X8)) */
1807                         motion_x = s->mv[dir][i][0];
1808                         motion_y = s->mv[dir][i][1];
1809                     }
1810
1811                     s->current_picture.motion_val[dir][xy][0]     = motion_x;
1812                     s->current_picture.motion_val[dir][xy][1]     = motion_y;
1813                     s->current_picture.motion_val[dir][xy + 1][0] = motion_x;
1814                     s->current_picture.motion_val[dir][xy + 1][1] = motion_y;
1815                     s->current_picture.ref_index [dir][b8_xy]     =
1816                     s->current_picture.ref_index [dir][b8_xy + 1] = s->field_select[dir][i];
1817                     assert(s->field_select[dir][i] == 0 ||
1818                            s->field_select[dir][i] == 1);
1819                 }
1820                 xy    += wrap;
1821                 b8_xy += 2;
1822             }
1823         }
1824
1825         s->dest[0] += 16;
1826         s->dest[1] += 16 >> s->chroma_x_shift;
1827         s->dest[2] += 16 >> s->chroma_x_shift;
1828
1829         ff_MPV_decode_mb(s, s->block);
1830
1831         if (++s->mb_x >= s->mb_width) {
1832             const int mb_size = 16;
1833
1834             ff_mpeg_draw_horiz_band(s, mb_size * (s->mb_y >> field_pic), mb_size);
1835             ff_MPV_report_decode_progress(s);
1836
1837             s->mb_x  = 0;
1838             s->mb_y += 1 << field_pic;
1839
1840             if (s->mb_y >= s->mb_height) {
1841                 int left   = get_bits_left(&s->gb);
1842                 int is_d10 = s->chroma_format == 2 &&
1843                              s->pict_type == AV_PICTURE_TYPE_I &&
1844                              avctx->profile == 0 && avctx->level == 5 &&
1845                              s->intra_dc_precision == 2 &&
1846                              s->q_scale_type == 1 && s->alternate_scan == 0 &&
1847                              s->progressive_frame == 0
1848                              /* vbv_delay == 0xBBB || 0xE10 */;
1849
1850                 if (left < 0 ||
1851                     (left && show_bits(&s->gb, FFMIN(left, 23)) && !is_d10) ||
1852                     ((avctx->err_recognition & AV_EF_BUFFER) && left > 8)) {
1853                     av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d %0X\n",
1854                            left, show_bits(&s->gb, FFMIN(left, 23)));
1855                     return -1;
1856                 } else
1857                     goto eos;
1858             }
1859
1860             ff_init_block_index(s);
1861         }
1862
1863         /* skip mb handling */
1864         if (s->mb_skip_run == -1) {
1865             /* read increment again */
1866             s->mb_skip_run = 0;
1867             for (;;) {
1868                 int code = get_vlc2(&s->gb, ff_mbincr_vlc.table,
1869                                     MBINCR_VLC_BITS, 2);
1870                 if (code < 0) {
1871                     av_log(s->avctx, AV_LOG_ERROR, "mb incr damaged\n");
1872                     return -1;
1873                 }
1874                 if (code >= 33) {
1875                     if (code == 33) {
1876                         s->mb_skip_run += 33;
1877                     } else if (code == 35) {
1878                         if (s->mb_skip_run != 0 || show_bits(&s->gb, 15) != 0) {
1879                             av_log(s->avctx, AV_LOG_ERROR, "slice mismatch\n");
1880                             return -1;
1881                         }
1882                         goto eos; /* end of slice */
1883                     }
1884                     /* otherwise, stuffing, nothing to do */
1885                 } else {
1886                     s->mb_skip_run += code;
1887                     break;
1888                 }
1889             }
1890             if (s->mb_skip_run) {
1891                 int i;
1892                 if (s->pict_type == AV_PICTURE_TYPE_I) {
1893                     av_log(s->avctx, AV_LOG_ERROR,
1894                            "skipped MB in I frame at %d %d\n", s->mb_x, s->mb_y);
1895                     return -1;
1896                 }
1897
1898                 /* skip mb */
1899                 s->mb_intra = 0;
1900                 for (i = 0; i < 12; i++)
1901                     s->block_last_index[i] = -1;
1902                 if (s->picture_structure == PICT_FRAME)
1903                     s->mv_type = MV_TYPE_16X16;
1904                 else
1905                     s->mv_type = MV_TYPE_FIELD;
1906                 if (s->pict_type == AV_PICTURE_TYPE_P) {
1907                     /* if P type, zero motion vector is implied */
1908                     s->mv_dir             = MV_DIR_FORWARD;
1909                     s->mv[0][0][0]        = s->mv[0][0][1]      = 0;
1910                     s->last_mv[0][0][0]   = s->last_mv[0][0][1] = 0;
1911                     s->last_mv[0][1][0]   = s->last_mv[0][1][1] = 0;
1912                     s->field_select[0][0] = (s->picture_structure - 1) & 1;
1913                 } else {
1914                     /* if B type, reuse previous vectors and directions */
1915                     s->mv[0][0][0] = s->last_mv[0][0][0];
1916                     s->mv[0][0][1] = s->last_mv[0][0][1];
1917                     s->mv[1][0][0] = s->last_mv[1][0][0];
1918                     s->mv[1][0][1] = s->last_mv[1][0][1];
1919                 }
1920             }
1921         }
1922     }
1923 eos: // end of slice
1924     *buf += (get_bits_count(&s->gb) - 1) / 8;
1925     av_dlog(s, "y %d %d %d %d\n", s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y);
1926     return 0;
1927 }
1928
1929 static int slice_decode_thread(AVCodecContext *c, void *arg)
1930 {
1931     MpegEncContext *s   = *(void **) arg;
1932     const uint8_t *buf  = s->gb.buffer;
1933     int mb_y            = s->start_mb_y;
1934     const int field_pic = s->picture_structure != PICT_FRAME;
1935
1936     s->er.error_count = (3 * (s->end_mb_y - s->start_mb_y) * s->mb_width) >> field_pic;
1937
1938     for (;;) {
1939         uint32_t start_code;
1940         int ret;
1941
1942         ret = mpeg_decode_slice(s, mb_y, &buf, s->gb.buffer_end - buf);
1943         emms_c();
1944         av_dlog(c, "ret:%d resync:%d/%d mb:%d/%d ts:%d/%d ec:%d\n",
1945                 ret, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y,
1946                 s->start_mb_y, s->end_mb_y, s->er.error_count);
1947         if (ret < 0) {
1948             if (c->err_recognition & AV_EF_EXPLODE)
1949                 return ret;
1950             if (s->resync_mb_x >= 0 && s->resync_mb_y >= 0)
1951                 ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1952                                 s->mb_x, s->mb_y,
1953                                 ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);
1954         } else {
1955             ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1956                             s->mb_x - 1, s->mb_y,
1957                             ER_AC_END | ER_DC_END | ER_MV_END);
1958         }
1959
1960         if (s->mb_y == s->end_mb_y)
1961             return 0;
1962
1963         start_code = -1;
1964         buf        = avpriv_find_start_code(buf, s->gb.buffer_end, &start_code);
1965         mb_y       = (start_code - SLICE_MIN_START_CODE) << field_pic;
1966         if (s->picture_structure == PICT_BOTTOM_FIELD)
1967             mb_y++;
1968         if (mb_y < 0 || mb_y >= s->end_mb_y)
1969             return -1;
1970     }
1971 }
1972
1973 /**
1974  * Handle slice ends.
1975  * @return 1 if it seems to be the last slice
1976  */
1977 static int slice_end(AVCodecContext *avctx, AVFrame *pict)
1978 {
1979     Mpeg1Context *s1  = avctx->priv_data;
1980     MpegEncContext *s = &s1->mpeg_enc_ctx;
1981
1982     if (!s1->mpeg_enc_ctx_allocated || !s->current_picture_ptr)
1983         return 0;
1984
1985     if (s->avctx->hwaccel) {
1986         if (s->avctx->hwaccel->end_frame(s->avctx) < 0)
1987             av_log(avctx, AV_LOG_ERROR,
1988                    "hardware accelerator failed to decode picture\n");
1989     }
1990
1991 #if FF_API_XVMC
1992 FF_DISABLE_DEPRECATION_WARNINGS
1993     if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)
1994         ff_xvmc_field_end(s);
1995 FF_ENABLE_DEPRECATION_WARNINGS
1996 #endif /* FF_API_XVMC */
1997
1998     /* end of slice reached */
1999     if (/* s->mb_y << field_pic == s->mb_height && */ !s->first_field) {
2000         /* end of image */
2001
2002         ff_er_frame_end(&s->er);
2003
2004         ff_MPV_frame_end(s);
2005
2006         if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
2007             int ret = av_frame_ref(pict, &s->current_picture_ptr->f);
2008             if (ret < 0)
2009                 return ret;
2010             ff_print_debug_info(s, s->current_picture_ptr);
2011         } else {
2012             if (avctx->active_thread_type & FF_THREAD_FRAME)
2013                 s->picture_number++;
2014             /* latency of 1 frame for I- and P-frames */
2015             /* XXX: use another variable than picture_number */
2016             if (s->last_picture_ptr != NULL) {
2017                 int ret = av_frame_ref(pict, &s->last_picture_ptr->f);
2018                 if (ret < 0)
2019                     return ret;
2020                 ff_print_debug_info(s, s->last_picture_ptr);
2021             }
2022         }
2023
2024         return 1;
2025     } else {
2026         return 0;
2027     }
2028 }
2029
2030 static int mpeg1_decode_sequence(AVCodecContext *avctx,
2031                                  const uint8_t *buf, int buf_size)
2032 {
2033     Mpeg1Context *s1  = avctx->priv_data;
2034     MpegEncContext *s = &s1->mpeg_enc_ctx;
2035     int width, height;
2036     int i, v, j;
2037
2038     init_get_bits(&s->gb, buf, buf_size * 8);
2039
2040     width  = get_bits(&s->gb, 12);
2041     height = get_bits(&s->gb, 12);
2042     if (width == 0 || height == 0) {
2043         av_log(avctx, AV_LOG_WARNING,
2044                "Invalid horizontal or vertical size value.\n");
2045         if (avctx->err_recognition & AV_EF_BITSTREAM)
2046             return AVERROR_INVALIDDATA;
2047     }
2048     s->aspect_ratio_info = get_bits(&s->gb, 4);
2049     if (s->aspect_ratio_info == 0) {
2050         av_log(avctx, AV_LOG_ERROR, "aspect ratio has forbidden 0 value\n");
2051         if (avctx->err_recognition & AV_EF_BITSTREAM)
2052             return -1;
2053     }
2054     s->frame_rate_index = get_bits(&s->gb, 4);
2055     if (s->frame_rate_index == 0 || s->frame_rate_index > 13)
2056         return -1;
2057     s->bit_rate = get_bits(&s->gb, 18) * 400;
2058     if (get_bits1(&s->gb) == 0) /* marker */
2059         return -1;
2060     s->width  = width;
2061     s->height = height;
2062
2063     s->avctx->rc_buffer_size = get_bits(&s->gb, 10) * 1024 * 16;
2064     skip_bits(&s->gb, 1);
2065
2066     /* get matrix */
2067     if (get_bits1(&s->gb)) {
2068         load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
2069     } else {
2070         for (i = 0; i < 64; i++) {
2071             j = s->dsp.idct_permutation[i];
2072             v = ff_mpeg1_default_intra_matrix[i];
2073             s->intra_matrix[j]        = v;
2074             s->chroma_intra_matrix[j] = v;
2075         }
2076     }
2077     if (get_bits1(&s->gb)) {
2078         load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
2079     } else {
2080         for (i = 0; i < 64; i++) {
2081             int j = s->dsp.idct_permutation[i];
2082             v = ff_mpeg1_default_non_intra_matrix[i];
2083             s->inter_matrix[j]        = v;
2084             s->chroma_inter_matrix[j] = v;
2085         }
2086     }
2087
2088     if (show_bits(&s->gb, 23) != 0) {
2089         av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");
2090         return -1;
2091     }
2092
2093     /* We set MPEG-2 parameters so that it emulates MPEG-1. */
2094     s->progressive_sequence = 1;
2095     s->progressive_frame    = 1;
2096     s->picture_structure    = PICT_FRAME;
2097     s->frame_pred_frame_dct = 1;
2098     s->chroma_format        = 1;
2099     s->codec_id             =
2100     s->avctx->codec_id      = AV_CODEC_ID_MPEG1VIDEO;
2101     s->out_format           = FMT_MPEG1;
2102     if (s->flags & CODEC_FLAG_LOW_DELAY)
2103         s->low_delay = 1;
2104
2105     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2106         av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%d\n",
2107                s->avctx->rc_buffer_size, s->bit_rate);
2108
2109     return 0;
2110 }
2111
2112 static int vcr2_init_sequence(AVCodecContext *avctx)
2113 {
2114     Mpeg1Context *s1  = avctx->priv_data;
2115     MpegEncContext *s = &s1->mpeg_enc_ctx;
2116     int i, v;
2117
2118     /* start new MPEG-1 context decoding */
2119     s->out_format = FMT_MPEG1;
2120     if (s1->mpeg_enc_ctx_allocated) {
2121         ff_MPV_common_end(s);
2122     }
2123     s->width            = avctx->coded_width;
2124     s->height           = avctx->coded_height;
2125     avctx->has_b_frames = 0; // true?
2126     s->low_delay        = 1;
2127
2128     avctx->pix_fmt = mpeg_get_pixelformat(avctx);
2129     avctx->hwaccel = ff_find_hwaccel(avctx);
2130
2131 #if FF_API_XVMC
2132     if ((avctx->pix_fmt == AV_PIX_FMT_XVMC_MPEG2_IDCT || avctx->hwaccel) &&
2133         avctx->idct_algo == FF_IDCT_AUTO)
2134 #else
2135     if (avctx->hwaccel && avctx->idct_algo == FF_IDCT_AUTO)
2136 #endif /* FF_API_XVMC */
2137         avctx->idct_algo = FF_IDCT_SIMPLE;
2138
2139     if (ff_MPV_common_init(s) < 0)
2140         return -1;
2141     s1->mpeg_enc_ctx_allocated = 1;
2142
2143     for (i = 0; i < 64; i++) {
2144         int j = s->dsp.idct_permutation[i];
2145         v = ff_mpeg1_default_intra_matrix[i];
2146         s->intra_matrix[j]        = v;
2147         s->chroma_intra_matrix[j] = v;
2148
2149         v = ff_mpeg1_default_non_intra_matrix[i];
2150         s->inter_matrix[j]        = v;
2151         s->chroma_inter_matrix[j] = v;
2152     }
2153
2154     s->progressive_sequence  = 1;
2155     s->progressive_frame     = 1;
2156     s->picture_structure     = PICT_FRAME;
2157     s->frame_pred_frame_dct  = 1;
2158     s->chroma_format         = 1;
2159     s->codec_id              = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO;
2160     s1->save_width           = s->width;
2161     s1->save_height          = s->height;
2162     s1->save_progressive_seq = s->progressive_sequence;
2163     return 0;
2164 }
2165
2166 static int mpeg_decode_a53_cc(AVCodecContext *avctx,
2167                               const uint8_t *p, int buf_size)
2168 {
2169     Mpeg1Context *s1 = avctx->priv_data;
2170
2171     if (buf_size >= 6 &&
2172         p[0] == 'G' && p[1] == 'A' && p[2] == '9' && p[3] == '4' &&
2173         p[4] == 3 && (p[5] & 0x40)) {
2174         /* extract A53 Part 4 CC data */
2175         int cc_count = p[5] & 0x1f;
2176         if (cc_count > 0 && buf_size >= 7 + cc_count * 3) {
2177             av_freep(&s1->a53_caption);
2178             s1->a53_caption_size = cc_count * 3;
2179             s1->a53_caption      = av_malloc(s1->a53_caption_size);
2180             if (s1->a53_caption)
2181                 memcpy(s1->a53_caption, p + 7, s1->a53_caption_size);
2182         }
2183         return 1;
2184     } else if (buf_size >= 11 &&
2185                p[0] == 'C' && p[1] == 'C' && p[2] == 0x01 && p[3] == 0xf8) {
2186         /* extract DVD CC data */
2187         int cc_count = 0;
2188         int i;
2189         // There is a caption count field in the data, but it is often
2190         // incorect.  So count the number of captions present.
2191         for (i = 5; i + 6 <= buf_size && ((p[i] & 0xfe) == 0xfe); i += 6)
2192             cc_count++;
2193         // Transform the DVD format into A53 Part 4 format
2194         if (cc_count > 0) {
2195             av_freep(&s1->a53_caption);
2196             s1->a53_caption_size = cc_count * 6;
2197             s1->a53_caption      = av_malloc(s1->a53_caption_size);
2198             if (s1->a53_caption) {
2199                 uint8_t field1 = !!(p[4] & 0x80);
2200                 uint8_t *cap = s1->a53_caption;
2201                 p += 5;
2202                 for (i = 0; i < cc_count; i++) {
2203                     cap[0] = (p[0] == 0xff && field1) ? 0xfc : 0xfd;
2204                     cap[1] = p[1];
2205                     cap[2] = p[2];
2206                     cap[3] = (p[3] == 0xff && !field1) ? 0xfc : 0xfd;
2207                     cap[4] = p[4];
2208                     cap[5] = p[5];
2209                     cap += 6;
2210                     p += 6;
2211                 }
2212             }
2213         }
2214         return 1;
2215     }
2216     return 0;
2217 }
2218
2219 static void mpeg_decode_user_data(AVCodecContext *avctx,
2220                                   const uint8_t *p, int buf_size)
2221 {
2222     const uint8_t *buf_end = p + buf_size;
2223
2224     /* we parse the DTG active format information */
2225     if (buf_end - p >= 5 &&
2226         p[0] == 'D' && p[1] == 'T' && p[2] == 'G' && p[3] == '1') {
2227         int flags = p[4];
2228         p += 5;
2229         if (flags & 0x80) {
2230             /* skip event id */
2231             p += 2;
2232         }
2233         if (flags & 0x40) {
2234             if (buf_end - p < 1)
2235                 return;
2236             avctx->dtg_active_format = p[0] & 0x0f;
2237         }
2238     } else if (buf_end - p >= 6 &&
2239                p[0] == 'J' && p[1] == 'P' && p[2] == '3' && p[3] == 'D' &&
2240                p[4] == 0x03) { // S3D_video_format_length
2241         // the 0x7F mask ignores the reserved_bit value
2242         const uint8_t S3D_video_format_type = p[5] & 0x7F;
2243
2244         if (S3D_video_format_type == 0x03 ||
2245             S3D_video_format_type == 0x04 ||
2246             S3D_video_format_type == 0x08 ||
2247             S3D_video_format_type == 0x23) {
2248             Mpeg1Context *s1   = avctx->priv_data;
2249
2250             s1->has_stereo3d = 1;
2251
2252             switch (S3D_video_format_type) {
2253             case 0x03:
2254                 s1->stereo3d.type = AV_STEREO3D_SIDEBYSIDE;
2255                 break;
2256             case 0x04:
2257                 s1->stereo3d.type = AV_STEREO3D_TOPBOTTOM;
2258                 break;
2259             case 0x08:
2260                 s1->stereo3d.type = AV_STEREO3D_2D;
2261                 break;
2262             case 0x23:
2263                 s1->stereo3d.type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2264                 break;
2265             }
2266         }
2267     } else if (mpeg_decode_a53_cc(avctx, p, buf_size)) {
2268         return;
2269     }
2270 }
2271
2272 static void mpeg_decode_gop(AVCodecContext *avctx,
2273                             const uint8_t *buf, int buf_size)
2274 {
2275     Mpeg1Context *s1  = avctx->priv_data;
2276     MpegEncContext *s = &s1->mpeg_enc_ctx;
2277
2278     int time_code_hours, time_code_minutes;
2279     int time_code_seconds, time_code_pictures;
2280     int broken_link;
2281
2282     init_get_bits(&s->gb, buf, buf_size * 8);
2283
2284     skip_bits1(&s->gb); /* drop_frame_flag */
2285
2286     time_code_hours   = get_bits(&s->gb, 5);
2287     time_code_minutes = get_bits(&s->gb, 6);
2288     skip_bits1(&s->gb); // marker bit
2289     time_code_seconds  = get_bits(&s->gb, 6);
2290     time_code_pictures = get_bits(&s->gb, 6);
2291
2292     s1->closed_gop = get_bits1(&s->gb);
2293     /* broken_link indicate that after editing the
2294      * reference frames of the first B-Frames after GOP I-Frame
2295      * are missing (open gop) */
2296     broken_link = get_bits1(&s->gb);
2297
2298     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2299         av_log(s->avctx, AV_LOG_DEBUG,
2300                "GOP (%2d:%02d:%02d.[%02d]) closed_gop=%d broken_link=%d\n",
2301                time_code_hours, time_code_minutes, time_code_seconds,
2302                time_code_pictures, s1->closed_gop, broken_link);
2303 }
2304
2305 static int decode_chunks(AVCodecContext *avctx, AVFrame *picture,
2306                          int *got_output, const uint8_t *buf, int buf_size)
2307 {
2308     Mpeg1Context *s = avctx->priv_data;
2309     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2310     const uint8_t *buf_ptr = buf;
2311     const uint8_t *buf_end = buf + buf_size;
2312     int ret, input_size;
2313     int last_code = 0, skip_frame = 0;
2314
2315     for (;;) {
2316         /* find next start code */
2317         uint32_t start_code = -1;
2318         buf_ptr = avpriv_find_start_code(buf_ptr, buf_end, &start_code);
2319         if (start_code > 0x1ff) {
2320             if (!skip_frame) {
2321                 if (HAVE_THREADS &&
2322                     (avctx->active_thread_type & FF_THREAD_SLICE) &&
2323                     !avctx->hwaccel) {
2324                     int i;
2325
2326                     avctx->execute(avctx, slice_decode_thread,
2327                                    &s2->thread_context[0], NULL,
2328                                    s->slice_count, sizeof(void *));
2329                     for (i = 0; i < s->slice_count; i++)
2330                         s2->er.error_count += s2->thread_context[i]->er.error_count;
2331                 }
2332
2333                 ret = slice_end(avctx, picture);
2334                 if (ret < 0)
2335                     return ret;
2336                 else if (ret) {
2337                     // FIXME: merge with the stuff in mpeg_decode_slice
2338                     if (s2->last_picture_ptr || s2->low_delay)
2339                         *got_output = 1;
2340                 }
2341             }
2342             s2->pict_type = 0;
2343             return FFMAX(0, buf_ptr - buf - s2->parse_context.last_index);
2344         }
2345
2346         input_size = buf_end - buf_ptr;
2347
2348         if (avctx->debug & FF_DEBUG_STARTCODE)
2349             av_log(avctx, AV_LOG_DEBUG, "%3"PRIX32" at %td left %d\n",
2350                    start_code, buf_ptr - buf, input_size);
2351
2352         /* prepare data for next start code */
2353         switch (start_code) {
2354         case SEQ_START_CODE:
2355             if (last_code == 0) {
2356                 mpeg1_decode_sequence(avctx, buf_ptr, input_size);
2357                 s->sync = 1;
2358             } else {
2359                 av_log(avctx, AV_LOG_ERROR,
2360                        "ignoring SEQ_START_CODE after %X\n", last_code);
2361                 if (avctx->err_recognition & AV_EF_EXPLODE)
2362                     return AVERROR_INVALIDDATA;
2363             }
2364             break;
2365
2366         case PICTURE_START_CODE:
2367             if (s2->width <= 0 || s2->height <= 0) {
2368                 av_log(avctx, AV_LOG_ERROR, "Invalid frame dimensions %dx%d.\n",
2369                        s2->width, s2->height);
2370                 return AVERROR_INVALIDDATA;
2371             }
2372
2373             if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE) &&
2374                 !avctx->hwaccel && s->slice_count) {
2375                 int i;
2376
2377                 avctx->execute(avctx, slice_decode_thread,
2378                                s2->thread_context, NULL,
2379                                s->slice_count, sizeof(void *));
2380                 for (i = 0; i < s->slice_count; i++)
2381                     s2->er.error_count += s2->thread_context[i]->er.error_count;
2382                 s->slice_count = 0;
2383             }
2384             if (last_code == 0 || last_code == SLICE_MIN_START_CODE) {
2385                 ret = mpeg_decode_postinit(avctx);
2386                 if (ret < 0) {
2387                     av_log(avctx, AV_LOG_ERROR,
2388                            "mpeg_decode_postinit() failure\n");
2389                     return ret;
2390                 }
2391
2392                 /* We have a complete image: we try to decompress it. */
2393                 if (mpeg1_decode_picture(avctx, buf_ptr, input_size) < 0)
2394                     s2->pict_type = 0;
2395                 s->first_slice = 1;
2396                 last_code      = PICTURE_START_CODE;
2397             } else {
2398                 av_log(avctx, AV_LOG_ERROR,
2399                        "ignoring pic after %X\n", last_code);
2400                 if (avctx->err_recognition & AV_EF_EXPLODE)
2401                     return AVERROR_INVALIDDATA;
2402             }
2403             break;
2404         case EXT_START_CODE:
2405             init_get_bits(&s2->gb, buf_ptr, input_size * 8);
2406
2407             switch (get_bits(&s2->gb, 4)) {
2408             case 0x1:
2409                 if (last_code == 0) {
2410                     mpeg_decode_sequence_extension(s);
2411                 } else {
2412                     av_log(avctx, AV_LOG_ERROR,
2413                            "ignoring seq ext after %X\n", last_code);
2414                     if (avctx->err_recognition & AV_EF_EXPLODE)
2415                         return AVERROR_INVALIDDATA;
2416                 }
2417                 break;
2418             case 0x2:
2419                 mpeg_decode_sequence_display_extension(s);
2420                 break;
2421             case 0x3:
2422                 mpeg_decode_quant_matrix_extension(s2);
2423                 break;
2424             case 0x7:
2425                 mpeg_decode_picture_display_extension(s);
2426                 break;
2427             case 0x8:
2428                 if (last_code == PICTURE_START_CODE) {
2429                     mpeg_decode_picture_coding_extension(s);
2430                 } else {
2431                     av_log(avctx, AV_LOG_ERROR,
2432                            "ignoring pic cod ext after %X\n", last_code);
2433                     if (avctx->err_recognition & AV_EF_EXPLODE)
2434                         return AVERROR_INVALIDDATA;
2435                 }
2436                 break;
2437             }
2438             break;
2439         case USER_START_CODE:
2440             mpeg_decode_user_data(avctx, buf_ptr, input_size);
2441             break;
2442         case GOP_START_CODE:
2443             if (last_code == 0) {
2444                 s2->first_field = 0;
2445                 mpeg_decode_gop(avctx, buf_ptr, input_size);
2446                 s->sync = 1;
2447             } else {
2448                 av_log(avctx, AV_LOG_ERROR,
2449                        "ignoring GOP_START_CODE after %X\n", last_code);
2450                 if (avctx->err_recognition & AV_EF_EXPLODE)
2451                     return AVERROR_INVALIDDATA;
2452             }
2453             break;
2454         default:
2455             if (start_code >= SLICE_MIN_START_CODE &&
2456                 start_code <= SLICE_MAX_START_CODE && last_code != 0) {
2457                 const int field_pic = s2->picture_structure != PICT_FRAME;
2458                 int mb_y = (start_code - SLICE_MIN_START_CODE) << field_pic;
2459                 last_code = SLICE_MIN_START_CODE;
2460
2461                 if (s2->picture_structure == PICT_BOTTOM_FIELD)
2462                     mb_y++;
2463
2464                 if (mb_y >= s2->mb_height) {
2465                     av_log(s2->avctx, AV_LOG_ERROR,
2466                            "slice below image (%d >= %d)\n", mb_y, s2->mb_height);
2467                     return -1;
2468                 }
2469
2470                 if (s2->last_picture_ptr == NULL) {
2471                     /* Skip B-frames if we do not have reference frames and
2472                      * GOP is not closed. */
2473                     if (s2->pict_type == AV_PICTURE_TYPE_B) {
2474                         if (!s->closed_gop) {
2475                             skip_frame = 1;
2476                             break;
2477                         }
2478                     }
2479                 }
2480                 if (s2->pict_type == AV_PICTURE_TYPE_I)
2481                     s->sync = 1;
2482                 if (s2->next_picture_ptr == NULL) {
2483                     /* Skip P-frames if we do not have a reference frame or
2484                      * we have an invalid header. */
2485                     if (s2->pict_type == AV_PICTURE_TYPE_P && !s->sync) {
2486                         skip_frame = 1;
2487                         break;
2488                     }
2489                 }
2490                 if ((avctx->skip_frame >= AVDISCARD_NONREF &&
2491                      s2->pict_type == AV_PICTURE_TYPE_B) ||
2492                     (avctx->skip_frame >= AVDISCARD_NONKEY &&
2493                      s2->pict_type != AV_PICTURE_TYPE_I) ||
2494                     avctx->skip_frame >= AVDISCARD_ALL) {
2495                     skip_frame = 1;
2496                     break;
2497                 }
2498
2499                 if (!s->mpeg_enc_ctx_allocated)
2500                     break;
2501
2502                 if (s2->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2503                     if (mb_y < avctx->skip_top ||
2504                         mb_y >= s2->mb_height - avctx->skip_bottom)
2505                         break;
2506                 }
2507
2508                 if (!s2->pict_type) {
2509                     av_log(avctx, AV_LOG_ERROR, "Missing picture start code\n");
2510                     if (avctx->err_recognition & AV_EF_EXPLODE)
2511                         return AVERROR_INVALIDDATA;
2512                     break;
2513                 }
2514
2515                 if (s->first_slice) {
2516                     skip_frame     = 0;
2517                     s->first_slice = 0;
2518                     if (mpeg_field_start(s2, buf, buf_size) < 0)
2519                         return -1;
2520                 }
2521                 if (!s2->current_picture_ptr) {
2522                     av_log(avctx, AV_LOG_ERROR,
2523                            "current_picture not initialized\n");
2524                     return AVERROR_INVALIDDATA;
2525                 }
2526
2527                 if (HAVE_THREADS &&
2528                     (avctx->active_thread_type & FF_THREAD_SLICE) &&
2529                     !avctx->hwaccel) {
2530                     int threshold = (s2->mb_height * s->slice_count +
2531                                      s2->slice_context_count / 2) /
2532                                     s2->slice_context_count;
2533                     if (threshold <= mb_y) {
2534                         MpegEncContext *thread_context = s2->thread_context[s->slice_count];
2535
2536                         thread_context->start_mb_y = mb_y;
2537                         thread_context->end_mb_y   = s2->mb_height;
2538                         if (s->slice_count) {
2539                             s2->thread_context[s->slice_count - 1]->end_mb_y = mb_y;
2540                             ret = ff_update_duplicate_context(thread_context, s2);
2541                             if (ret < 0)
2542                                 return ret;
2543                         }
2544                         init_get_bits(&thread_context->gb, buf_ptr, input_size * 8);
2545                         s->slice_count++;
2546                     }
2547                     buf_ptr += 2; // FIXME add minimum number of bytes per slice
2548                 } else {
2549                     ret = mpeg_decode_slice(s2, mb_y, &buf_ptr, input_size);
2550                     emms_c();
2551
2552                     if (ret < 0) {
2553                         if (avctx->err_recognition & AV_EF_EXPLODE)
2554                             return ret;
2555                         if (s2->resync_mb_x >= 0 && s2->resync_mb_y >= 0)
2556                             ff_er_add_slice(&s2->er, s2->resync_mb_x,
2557                                             s2->resync_mb_y, s2->mb_x, s2->mb_y,
2558                                             ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);
2559                     } else {
2560                         ff_er_add_slice(&s2->er, s2->resync_mb_x,
2561                                         s2->resync_mb_y, s2->mb_x - 1, s2->mb_y,
2562                                         ER_AC_END | ER_DC_END | ER_MV_END);
2563                     }
2564                 }
2565             }
2566             break;
2567         }
2568     }
2569 }
2570
2571 static int mpeg_decode_frame(AVCodecContext *avctx, void *data,
2572                              int *got_output, AVPacket *avpkt)
2573 {
2574     const uint8_t *buf = avpkt->data;
2575     int buf_size = avpkt->size;
2576     Mpeg1Context *s = avctx->priv_data;
2577     AVFrame *picture = data;
2578     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2579     av_dlog(avctx, "fill_buffer\n");
2580
2581     if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {
2582         /* special case for last picture */
2583         if (s2->low_delay == 0 && s2->next_picture_ptr) {
2584             int ret = av_frame_ref(picture, &s2->next_picture_ptr->f);
2585             if (ret < 0)
2586                 return ret;
2587
2588             s2->next_picture_ptr = NULL;
2589
2590             *got_output = 1;
2591         }
2592         return buf_size;
2593     }
2594
2595     if (s2->flags & CODEC_FLAG_TRUNCATED) {
2596         int next = ff_mpeg1_find_frame_end(&s2->parse_context, buf,
2597                                            buf_size, NULL);
2598
2599         if (ff_combine_frame(&s2->parse_context, next,
2600                              (const uint8_t **) &buf, &buf_size) < 0)
2601             return buf_size;
2602     }
2603
2604     if (s->mpeg_enc_ctx_allocated == 0 && avctx->codec_tag == AV_RL32("VCR2"))
2605         vcr2_init_sequence(avctx);
2606
2607     s->slice_count = 0;
2608
2609     if (avctx->extradata && !s->extradata_decoded) {
2610         int ret = decode_chunks(avctx, picture, got_output,
2611                                 avctx->extradata, avctx->extradata_size);
2612         s->extradata_decoded = 1;
2613         if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
2614             return ret;
2615     }
2616
2617     return decode_chunks(avctx, picture, got_output, buf, buf_size);
2618 }
2619
2620 static void flush(AVCodecContext *avctx)
2621 {
2622     Mpeg1Context *s = avctx->priv_data;
2623
2624     s->sync       = 0;
2625     s->closed_gop = 0;
2626
2627     ff_mpeg_flush(avctx);
2628 }
2629
2630 static av_cold int mpeg_decode_end(AVCodecContext *avctx)
2631 {
2632     Mpeg1Context *s = avctx->priv_data;
2633
2634     if (s->mpeg_enc_ctx_allocated)
2635         ff_MPV_common_end(&s->mpeg_enc_ctx);
2636     av_freep(&s->a53_caption);
2637     return 0;
2638 }
2639
2640 static const AVProfile mpeg2_video_profiles[] = {
2641     { FF_PROFILE_MPEG2_422,          "4:2:2"              },
2642     { FF_PROFILE_MPEG2_HIGH,         "High"               },
2643     { FF_PROFILE_MPEG2_SS,           "Spatially Scalable" },
2644     { FF_PROFILE_MPEG2_SNR_SCALABLE, "SNR Scalable"       },
2645     { FF_PROFILE_MPEG2_MAIN,         "Main"               },
2646     { FF_PROFILE_MPEG2_SIMPLE,       "Simple"             },
2647     { FF_PROFILE_RESERVED,           "Reserved"           },
2648     { FF_PROFILE_RESERVED,           "Reserved"           },
2649     { FF_PROFILE_UNKNOWN                                  },
2650 };
2651
2652 AVCodec ff_mpeg1video_decoder = {
2653     .name                  = "mpeg1video",
2654     .long_name             = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
2655     .type                  = AVMEDIA_TYPE_VIDEO,
2656     .id                    = AV_CODEC_ID_MPEG1VIDEO,
2657     .priv_data_size        = sizeof(Mpeg1Context),
2658     .init                  = mpeg_decode_init,
2659     .close                 = mpeg_decode_end,
2660     .decode                = mpeg_decode_frame,
2661     .capabilities          = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2662                              CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2663                              CODEC_CAP_SLICE_THREADS,
2664     .flush                 = flush,
2665     .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg_decode_update_thread_context)
2666 };
2667
2668 AVCodec ff_mpeg2video_decoder = {
2669     .name           = "mpeg2video",
2670     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
2671     .type           = AVMEDIA_TYPE_VIDEO,
2672     .id             = AV_CODEC_ID_MPEG2VIDEO,
2673     .priv_data_size = sizeof(Mpeg1Context),
2674     .init           = mpeg_decode_init,
2675     .close          = mpeg_decode_end,
2676     .decode         = mpeg_decode_frame,
2677     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2678                       CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2679                       CODEC_CAP_SLICE_THREADS,
2680     .flush          = flush,
2681     .profiles       = NULL_IF_CONFIG_SMALL(mpeg2_video_profiles),
2682 };
2683
2684 #if FF_API_XVMC
2685 #if CONFIG_MPEG_XVMC_DECODER
2686 static av_cold int mpeg_mc_decode_init(AVCodecContext *avctx)
2687 {
2688     if (avctx->active_thread_type & FF_THREAD_SLICE)
2689         return -1;
2690     if (!(avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
2691         return -1;
2692     if (!(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD)) {
2693         av_dlog(avctx, "mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");
2694     }
2695     mpeg_decode_init(avctx);
2696
2697     avctx->pix_fmt           = AV_PIX_FMT_XVMC_MPEG2_IDCT;
2698     avctx->xvmc_acceleration = 2; // 2 - the blocks are packed!
2699
2700     return 0;
2701 }
2702
2703 AVCodec ff_mpeg_xvmc_decoder = {
2704     .name           = "mpegvideo_xvmc",
2705     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1/2 video XvMC (X-Video Motion Compensation)"),
2706     .type           = AVMEDIA_TYPE_VIDEO,
2707     .id             = AV_CODEC_ID_MPEG2VIDEO_XVMC,
2708     .priv_data_size = sizeof(Mpeg1Context),
2709     .init           = mpeg_mc_decode_init,
2710     .close          = mpeg_decode_end,
2711     .decode         = mpeg_decode_frame,
2712     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2713                       CODEC_CAP_TRUNCATED | CODEC_CAP_HWACCEL | CODEC_CAP_DELAY,
2714     .flush          = flush,
2715 };
2716
2717 #endif
2718 #endif /* FF_API_XVMC */