]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpeg12dec.c
195f9f3250ca351693f36b95fe26161060402c87
[ffmpeg] / 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->bdsp.clear_blocks(s->block[0]);
780
781         if (!s->chroma_y_shift)
782             s->bdsp.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->bdsp.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->bdsp.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 ff_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 ff_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         // until then pix_fmt may be changed right after codec init
1299 #if FF_API_XVMC
1300         if ((avctx->pix_fmt == AV_PIX_FMT_XVMC_MPEG2_IDCT ||
1301              avctx->hwaccel) && avctx->idct_algo == FF_IDCT_AUTO)
1302 #else
1303         if (avctx->hwaccel && avctx->idct_algo == FF_IDCT_AUTO)
1304 #endif /* FF_API_XVMC */
1305             avctx->idct_algo = FF_IDCT_SIMPLE;
1306
1307         /* Quantization matrices may need reordering
1308          * if DCT permutation is changed. */
1309         memcpy(old_permutation, s->dsp.idct_permutation, 64 * sizeof(uint8_t));
1310
1311         if (ff_MPV_common_init(s) < 0)
1312             return -2;
1313
1314         quant_matrix_rebuild(s->intra_matrix,        old_permutation, s->dsp.idct_permutation);
1315         quant_matrix_rebuild(s->inter_matrix,        old_permutation, s->dsp.idct_permutation);
1316         quant_matrix_rebuild(s->chroma_intra_matrix, old_permutation, s->dsp.idct_permutation);
1317         quant_matrix_rebuild(s->chroma_inter_matrix, old_permutation, s->dsp.idct_permutation);
1318
1319         s1->mpeg_enc_ctx_allocated = 1;
1320     }
1321     return 0;
1322 }
1323
1324 static int mpeg1_decode_picture(AVCodecContext *avctx, const uint8_t *buf,
1325                                 int buf_size)
1326 {
1327     Mpeg1Context *s1  = avctx->priv_data;
1328     MpegEncContext *s = &s1->mpeg_enc_ctx;
1329     int ref, f_code, vbv_delay;
1330
1331     init_get_bits(&s->gb, buf, buf_size * 8);
1332
1333     ref = get_bits(&s->gb, 10); /* temporal ref */
1334     s->pict_type = get_bits(&s->gb, 3);
1335     if (s->pict_type == 0 || s->pict_type > 3)
1336         return -1;
1337
1338     vbv_delay = get_bits(&s->gb, 16);
1339     if (s->pict_type == AV_PICTURE_TYPE_P ||
1340         s->pict_type == AV_PICTURE_TYPE_B) {
1341         s->full_pel[0] = get_bits1(&s->gb);
1342         f_code = get_bits(&s->gb, 3);
1343         if (f_code == 0 && (avctx->err_recognition & AV_EF_BITSTREAM))
1344             return -1;
1345         s->mpeg_f_code[0][0] = f_code;
1346         s->mpeg_f_code[0][1] = f_code;
1347     }
1348     if (s->pict_type == AV_PICTURE_TYPE_B) {
1349         s->full_pel[1] = get_bits1(&s->gb);
1350         f_code = get_bits(&s->gb, 3);
1351         if (f_code == 0 && (avctx->err_recognition & AV_EF_BITSTREAM))
1352             return -1;
1353         s->mpeg_f_code[1][0] = f_code;
1354         s->mpeg_f_code[1][1] = f_code;
1355     }
1356     s->current_picture.f->pict_type = s->pict_type;
1357     s->current_picture.f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;
1358
1359     if (avctx->debug & FF_DEBUG_PICT_INFO)
1360         av_log(avctx, AV_LOG_DEBUG,
1361                "vbv_delay %d, ref %d type:%d\n", vbv_delay, ref, s->pict_type);
1362
1363     s->y_dc_scale = 8;
1364     s->c_dc_scale = 8;
1365     return 0;
1366 }
1367
1368 static void mpeg_decode_sequence_extension(Mpeg1Context *s1)
1369 {
1370     MpegEncContext *s = &s1->mpeg_enc_ctx;
1371     int horiz_size_ext, vert_size_ext;
1372     int bit_rate_ext;
1373
1374     skip_bits(&s->gb, 1); /* profile and level esc*/
1375     s->avctx->profile       = get_bits(&s->gb, 3);
1376     s->avctx->level         = get_bits(&s->gb, 4);
1377     s->progressive_sequence = get_bits1(&s->gb);   /* progressive_sequence */
1378     s->chroma_format        = get_bits(&s->gb, 2); /* chroma_format 1=420, 2=422, 3=444 */
1379     horiz_size_ext          = get_bits(&s->gb, 2);
1380     vert_size_ext           = get_bits(&s->gb, 2);
1381     s->width  |= (horiz_size_ext << 12);
1382     s->height |= (vert_size_ext  << 12);
1383     bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1384     s->bit_rate += (bit_rate_ext << 18) * 400;
1385     skip_bits1(&s->gb); /* marker */
1386     s->avctx->rc_buffer_size += get_bits(&s->gb, 8) * 1024 * 16 << 10;
1387
1388     s->low_delay = get_bits1(&s->gb);
1389     if (s->flags & CODEC_FLAG_LOW_DELAY)
1390         s->low_delay = 1;
1391
1392     s1->frame_rate_ext.num = get_bits(&s->gb, 2) + 1;
1393     s1->frame_rate_ext.den = get_bits(&s->gb, 5) + 1;
1394
1395     av_dlog(s->avctx, "sequence extension\n");
1396     s->codec_id = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO;
1397
1398     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1399         av_log(s->avctx, AV_LOG_DEBUG,
1400                "profile: %d, level: %d vbv buffer: %d, bitrate:%d\n",
1401                s->avctx->profile, s->avctx->level,
1402                s->avctx->rc_buffer_size, s->bit_rate);
1403 }
1404
1405 static void mpeg_decode_sequence_display_extension(Mpeg1Context *s1)
1406 {
1407     MpegEncContext *s = &s1->mpeg_enc_ctx;
1408     int color_description, w, h;
1409
1410     skip_bits(&s->gb, 3); /* video format */
1411     color_description = get_bits1(&s->gb);
1412     if (color_description) {
1413         s->avctx->color_primaries = get_bits(&s->gb, 8);
1414         s->avctx->color_trc       = get_bits(&s->gb, 8);
1415         s->avctx->colorspace      = get_bits(&s->gb, 8);
1416     }
1417     w = get_bits(&s->gb, 14);
1418     skip_bits(&s->gb, 1); // marker
1419     h = get_bits(&s->gb, 14);
1420     // remaining 3 bits are zero padding
1421
1422     s1->pan_scan.width  = 16 * w;
1423     s1->pan_scan.height = 16 * h;
1424
1425     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1426         av_log(s->avctx, AV_LOG_DEBUG, "sde w:%d, h:%d\n", w, h);
1427 }
1428
1429 static void mpeg_decode_picture_display_extension(Mpeg1Context *s1)
1430 {
1431     MpegEncContext *s = &s1->mpeg_enc_ctx;
1432     int i, nofco;
1433
1434     nofco = 1;
1435     if (s->progressive_sequence) {
1436         if (s->repeat_first_field) {
1437             nofco++;
1438             if (s->top_field_first)
1439                 nofco++;
1440         }
1441     } else {
1442         if (s->picture_structure == PICT_FRAME) {
1443             nofco++;
1444             if (s->repeat_first_field)
1445                 nofco++;
1446         }
1447     }
1448     for (i = 0; i < nofco; i++) {
1449         s1->pan_scan.position[i][0] = get_sbits(&s->gb, 16);
1450         skip_bits(&s->gb, 1); // marker
1451         s1->pan_scan.position[i][1] = get_sbits(&s->gb, 16);
1452         skip_bits(&s->gb, 1); // marker
1453     }
1454
1455     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1456         av_log(s->avctx, AV_LOG_DEBUG,
1457                "pde (%"PRId16",%"PRId16") (%"PRId16",%"PRId16") (%"PRId16",%"PRId16")\n",
1458                s1->pan_scan.position[0][0], s1->pan_scan.position[0][1],
1459                s1->pan_scan.position[1][0], s1->pan_scan.position[1][1],
1460                s1->pan_scan.position[2][0], s1->pan_scan.position[2][1]);
1461 }
1462
1463 static int load_matrix(MpegEncContext *s, uint16_t matrix0[64],
1464                        uint16_t matrix1[64], int intra)
1465 {
1466     int i;
1467
1468     for (i = 0; i < 64; i++) {
1469         int j = s->dsp.idct_permutation[ff_zigzag_direct[i]];
1470         int v = get_bits(&s->gb, 8);
1471         if (v == 0) {
1472             av_log(s->avctx, AV_LOG_ERROR, "matrix damaged\n");
1473             return -1;
1474         }
1475         if (intra && i == 0 && v != 8) {
1476             av_log(s->avctx, AV_LOG_ERROR, "intra matrix invalid, ignoring\n");
1477             v = 8; // needed by pink.mpg / issue1046
1478         }
1479         matrix0[j] = v;
1480         if (matrix1)
1481             matrix1[j] = v;
1482     }
1483     return 0;
1484 }
1485
1486 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1487 {
1488     av_dlog(s->avctx, "matrix extension\n");
1489
1490     if (get_bits1(&s->gb))
1491         load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
1492     if (get_bits1(&s->gb))
1493         load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
1494     if (get_bits1(&s->gb))
1495         load_matrix(s, s->chroma_intra_matrix, NULL, 1);
1496     if (get_bits1(&s->gb))
1497         load_matrix(s, s->chroma_inter_matrix, NULL, 0);
1498 }
1499
1500 static void mpeg_decode_picture_coding_extension(Mpeg1Context *s1)
1501 {
1502     MpegEncContext *s = &s1->mpeg_enc_ctx;
1503
1504     s->full_pel[0]       = s->full_pel[1] = 0;
1505     s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1506     s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1507     s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1508     s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1509     if (!s->pict_type && s1->mpeg_enc_ctx_allocated) {
1510         av_log(s->avctx, AV_LOG_ERROR,
1511                "Missing picture start code, guessing missing values\n");
1512         if (s->mpeg_f_code[1][0] == 15 && s->mpeg_f_code[1][1] == 15) {
1513             if (s->mpeg_f_code[0][0] == 15 && s->mpeg_f_code[0][1] == 15)
1514                 s->pict_type = AV_PICTURE_TYPE_I;
1515             else
1516                 s->pict_type = AV_PICTURE_TYPE_P;
1517         } else
1518             s->pict_type = AV_PICTURE_TYPE_B;
1519         s->current_picture.f->pict_type = s->pict_type;
1520         s->current_picture.f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;
1521     }
1522     s->intra_dc_precision         = get_bits(&s->gb, 2);
1523     s->picture_structure          = get_bits(&s->gb, 2);
1524     s->top_field_first            = get_bits1(&s->gb);
1525     s->frame_pred_frame_dct       = get_bits1(&s->gb);
1526     s->concealment_motion_vectors = get_bits1(&s->gb);
1527     s->q_scale_type               = get_bits1(&s->gb);
1528     s->intra_vlc_format           = get_bits1(&s->gb);
1529     s->alternate_scan             = get_bits1(&s->gb);
1530     s->repeat_first_field         = get_bits1(&s->gb);
1531     s->chroma_420_type            = get_bits1(&s->gb);
1532     s->progressive_frame          = get_bits1(&s->gb);
1533
1534     if (s->progressive_sequence && !s->progressive_frame) {
1535         s->progressive_frame = 1;
1536         av_log(s->avctx, AV_LOG_ERROR,
1537                "interlaced frame in progressive sequence, ignoring\n");
1538     }
1539
1540     if (s->picture_structure == 0 ||
1541         (s->progressive_frame && s->picture_structure != PICT_FRAME)) {
1542         av_log(s->avctx, AV_LOG_ERROR,
1543                "picture_structure %d invalid, ignoring\n",
1544                s->picture_structure);
1545         s->picture_structure = PICT_FRAME;
1546     }
1547
1548     if (s->progressive_sequence && !s->frame_pred_frame_dct)
1549         av_log(s->avctx, AV_LOG_WARNING, "invalid frame_pred_frame_dct\n");
1550
1551     if (s->picture_structure == PICT_FRAME) {
1552         s->first_field = 0;
1553         s->v_edge_pos  = 16 * s->mb_height;
1554     } else {
1555         s->first_field ^= 1;
1556         s->v_edge_pos   = 8 * s->mb_height;
1557         memset(s->mbskip_table, 0, s->mb_stride * s->mb_height);
1558     }
1559
1560     if (s->alternate_scan) {
1561         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
1562         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
1563     } else {
1564         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
1565         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
1566     }
1567
1568     /* composite display not parsed */
1569     av_dlog(s->avctx, "intra_dc_precision=%d\n", s->intra_dc_precision);
1570     av_dlog(s->avctx, "picture_structure=%d\n", s->picture_structure);
1571     av_dlog(s->avctx, "top field first=%d\n", s->top_field_first);
1572     av_dlog(s->avctx, "repeat first field=%d\n", s->repeat_first_field);
1573     av_dlog(s->avctx, "conceal=%d\n", s->concealment_motion_vectors);
1574     av_dlog(s->avctx, "intra_vlc_format=%d\n", s->intra_vlc_format);
1575     av_dlog(s->avctx, "alternate_scan=%d\n", s->alternate_scan);
1576     av_dlog(s->avctx, "frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1577     av_dlog(s->avctx, "progressive_frame=%d\n", s->progressive_frame);
1578 }
1579
1580 static int mpeg_field_start(MpegEncContext *s, const uint8_t *buf, int buf_size)
1581 {
1582     AVCodecContext *avctx = s->avctx;
1583     Mpeg1Context *s1      = (Mpeg1Context *) s;
1584
1585     /* start frame decoding */
1586     if (s->first_field || s->picture_structure == PICT_FRAME) {
1587         AVFrameSideData *pan_scan;
1588
1589         if (ff_MPV_frame_start(s, avctx) < 0)
1590             return -1;
1591
1592         ff_mpeg_er_frame_start(s);
1593
1594         /* first check if we must repeat the frame */
1595         s->current_picture_ptr->f->repeat_pict = 0;
1596         if (s->repeat_first_field) {
1597             if (s->progressive_sequence) {
1598                 if (s->top_field_first)
1599                     s->current_picture_ptr->f->repeat_pict = 4;
1600                 else
1601                     s->current_picture_ptr->f->repeat_pict = 2;
1602             } else if (s->progressive_frame) {
1603                 s->current_picture_ptr->f->repeat_pict = 1;
1604             }
1605         }
1606
1607         pan_scan = av_frame_new_side_data(s->current_picture_ptr->f,
1608                                           AV_FRAME_DATA_PANSCAN,
1609                                           sizeof(s1->pan_scan));
1610         if (!pan_scan)
1611             return AVERROR(ENOMEM);
1612         memcpy(pan_scan->data, &s1->pan_scan, sizeof(s1->pan_scan));
1613
1614         if (s1->a53_caption) {
1615             AVFrameSideData *sd = av_frame_new_side_data(
1616                 s->current_picture_ptr->f, AV_FRAME_DATA_A53_CC,
1617                 s1->a53_caption_size);
1618             if (sd)
1619                 memcpy(sd->data, s1->a53_caption, s1->a53_caption_size);
1620             av_freep(&s1->a53_caption);
1621         }
1622
1623         if (s1->has_stereo3d) {
1624             AVStereo3D *stereo = av_stereo3d_create_side_data(s->current_picture_ptr->f);
1625             if (!stereo)
1626                 return AVERROR(ENOMEM);
1627
1628             *stereo = s1->stereo3d;
1629             s1->has_stereo3d = 0;
1630         }
1631         if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_FRAME))
1632             ff_thread_finish_setup(avctx);
1633     } else { // second field
1634         int i;
1635
1636         if (!s->current_picture_ptr) {
1637             av_log(s->avctx, AV_LOG_ERROR, "first field missing\n");
1638             return -1;
1639         }
1640
1641         if (s->avctx->hwaccel &&
1642             (s->avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD)) {
1643             if (s->avctx->hwaccel->end_frame(s->avctx) < 0)
1644                 av_log(avctx, AV_LOG_ERROR,
1645                        "hardware accelerator failed to decode first field\n");
1646         }
1647
1648         for (i = 0; i < 4; i++) {
1649             s->current_picture.f->data[i] = s->current_picture_ptr->f->data[i];
1650             if (s->picture_structure == PICT_BOTTOM_FIELD)
1651                 s->current_picture.f->data[i] +=
1652                     s->current_picture_ptr->f->linesize[i];
1653         }
1654     }
1655
1656     if (avctx->hwaccel) {
1657         if (avctx->hwaccel->start_frame(avctx, buf, buf_size) < 0)
1658             return -1;
1659     }
1660
1661 #if FF_API_XVMC
1662 FF_DISABLE_DEPRECATION_WARNINGS
1663 // MPV_frame_start will call this function too,
1664 // but we need to call it on every field
1665     if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)
1666         if (ff_xvmc_field_start(s, avctx) < 0)
1667             return -1;
1668 FF_ENABLE_DEPRECATION_WARNINGS
1669 #endif /* FF_API_XVMC */
1670
1671     return 0;
1672 }
1673
1674 #define DECODE_SLICE_ERROR -1
1675 #define DECODE_SLICE_OK     0
1676
1677 /**
1678  * Decode a slice.
1679  * MpegEncContext.mb_y must be set to the MB row from the startcode.
1680  * @return DECODE_SLICE_ERROR if the slice is damaged,
1681  *         DECODE_SLICE_OK if this slice is OK
1682  */
1683 static int mpeg_decode_slice(MpegEncContext *s, int mb_y,
1684                              const uint8_t **buf, int buf_size)
1685 {
1686     AVCodecContext *avctx = s->avctx;
1687     const int field_pic   = s->picture_structure != PICT_FRAME;
1688
1689     s->resync_mb_x =
1690     s->resync_mb_y = -1;
1691
1692     assert(mb_y < s->mb_height);
1693
1694     init_get_bits(&s->gb, *buf, buf_size * 8);
1695
1696     ff_mpeg1_clean_buffers(s);
1697     s->interlaced_dct = 0;
1698
1699     s->qscale = get_qscale(s);
1700
1701     if (s->qscale == 0) {
1702         av_log(s->avctx, AV_LOG_ERROR, "qscale == 0\n");
1703         return -1;
1704     }
1705
1706     /* extra slice info */
1707     while (get_bits1(&s->gb) != 0)
1708         skip_bits(&s->gb, 8);
1709
1710     s->mb_x = 0;
1711
1712     if (mb_y == 0 && s->codec_tag == AV_RL32("SLIF")) {
1713         skip_bits1(&s->gb);
1714     } else {
1715         while (get_bits_left(&s->gb) > 0) {
1716             int code = get_vlc2(&s->gb, ff_mbincr_vlc.table,
1717                                 MBINCR_VLC_BITS, 2);
1718             if (code < 0) {
1719                 av_log(s->avctx, AV_LOG_ERROR, "first mb_incr damaged\n");
1720                 return -1;
1721             }
1722             if (code >= 33) {
1723                 if (code == 33)
1724                     s->mb_x += 33;
1725                 /* otherwise, stuffing, nothing to do */
1726             } else {
1727                 s->mb_x += code;
1728                 break;
1729             }
1730         }
1731     }
1732
1733     if (s->mb_x >= (unsigned) s->mb_width) {
1734         av_log(s->avctx, AV_LOG_ERROR, "initial skip overflow\n");
1735         return -1;
1736     }
1737
1738     if (avctx->hwaccel) {
1739         const uint8_t *buf_end, *buf_start = *buf - 4; /* include start_code */
1740         int start_code = -1;
1741         buf_end = avpriv_find_start_code(buf_start + 2, *buf + buf_size, &start_code);
1742         if (buf_end < *buf + buf_size)
1743             buf_end -= 4;
1744         s->mb_y = mb_y;
1745         if (avctx->hwaccel->decode_slice(avctx, buf_start, buf_end - buf_start) < 0)
1746             return DECODE_SLICE_ERROR;
1747         *buf = buf_end;
1748         return DECODE_SLICE_OK;
1749     }
1750
1751     s->resync_mb_x = s->mb_x;
1752     s->resync_mb_y = s->mb_y = mb_y;
1753     s->mb_skip_run = 0;
1754     ff_init_block_index(s);
1755
1756     if (s->mb_y == 0 && s->mb_x == 0 && (s->first_field || s->picture_structure == PICT_FRAME)) {
1757         if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
1758             av_log(s->avctx, AV_LOG_DEBUG,
1759                    "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",
1760                    s->qscale,
1761                    s->mpeg_f_code[0][0], s->mpeg_f_code[0][1],
1762                    s->mpeg_f_code[1][0], s->mpeg_f_code[1][1],
1763                    s->pict_type  == AV_PICTURE_TYPE_I ? "I" :
1764                    (s->pict_type == AV_PICTURE_TYPE_P ? "P" :
1765                    (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
1766                    s->progressive_sequence ? "ps"  : "",
1767                    s->progressive_frame    ? "pf"  : "",
1768                    s->alternate_scan       ? "alt" : "",
1769                    s->top_field_first      ? "top" : "",
1770                    s->intra_dc_precision, s->picture_structure,
1771                    s->frame_pred_frame_dct, s->concealment_motion_vectors,
1772                    s->q_scale_type, s->intra_vlc_format,
1773                    s->repeat_first_field, s->chroma_420_type ? "420" : "");
1774         }
1775     }
1776
1777     for (;;) {
1778 #if FF_API_XVMC
1779 FF_DISABLE_DEPRECATION_WARNINGS
1780         // If 1, we memcpy blocks in xvmcvideo.
1781         if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration > 1)
1782             ff_xvmc_init_block(s); // set s->block
1783 FF_ENABLE_DEPRECATION_WARNINGS
1784 #endif /* FF_API_XVMC */
1785
1786         if (mpeg_decode_mb(s, s->block) < 0)
1787             return -1;
1788
1789         // Note motion_val is normally NULL unless we want to extract the MVs.
1790         if (s->current_picture.motion_val[0] && !s->encoding) {
1791             const int wrap = s->b8_stride;
1792             int xy         = s->mb_x * 2 + s->mb_y * 2 * wrap;
1793             int b8_xy      = 4 * (s->mb_x + s->mb_y * s->mb_stride);
1794             int motion_x, motion_y, dir, i;
1795
1796             for (i = 0; i < 2; i++) {
1797                 for (dir = 0; dir < 2; dir++) {
1798                     if (s->mb_intra ||
1799                         (dir == 1 && s->pict_type != AV_PICTURE_TYPE_B)) {
1800                         motion_x = motion_y = 0;
1801                     } else if (s->mv_type == MV_TYPE_16X16 ||
1802                                (s->mv_type == MV_TYPE_FIELD && field_pic)) {
1803                         motion_x = s->mv[dir][0][0];
1804                         motion_y = s->mv[dir][0][1];
1805                     } else { /* if ((s->mv_type == MV_TYPE_FIELD) || (s->mv_type == MV_TYPE_16X8)) */
1806                         motion_x = s->mv[dir][i][0];
1807                         motion_y = s->mv[dir][i][1];
1808                     }
1809
1810                     s->current_picture.motion_val[dir][xy][0]     = motion_x;
1811                     s->current_picture.motion_val[dir][xy][1]     = motion_y;
1812                     s->current_picture.motion_val[dir][xy + 1][0] = motion_x;
1813                     s->current_picture.motion_val[dir][xy + 1][1] = motion_y;
1814                     s->current_picture.ref_index [dir][b8_xy]     =
1815                     s->current_picture.ref_index [dir][b8_xy + 1] = s->field_select[dir][i];
1816                     assert(s->field_select[dir][i] == 0 ||
1817                            s->field_select[dir][i] == 1);
1818                 }
1819                 xy    += wrap;
1820                 b8_xy += 2;
1821             }
1822         }
1823
1824         s->dest[0] += 16;
1825         s->dest[1] += 16 >> s->chroma_x_shift;
1826         s->dest[2] += 16 >> s->chroma_x_shift;
1827
1828         ff_MPV_decode_mb(s, s->block);
1829
1830         if (++s->mb_x >= s->mb_width) {
1831             const int mb_size = 16;
1832
1833             ff_mpeg_draw_horiz_band(s, mb_size * (s->mb_y >> field_pic), mb_size);
1834             ff_MPV_report_decode_progress(s);
1835
1836             s->mb_x  = 0;
1837             s->mb_y += 1 << field_pic;
1838
1839             if (s->mb_y >= s->mb_height) {
1840                 int left   = get_bits_left(&s->gb);
1841                 int is_d10 = s->chroma_format == 2 &&
1842                              s->pict_type == AV_PICTURE_TYPE_I &&
1843                              avctx->profile == 0 && avctx->level == 5 &&
1844                              s->intra_dc_precision == 2 &&
1845                              s->q_scale_type == 1 && s->alternate_scan == 0 &&
1846                              s->progressive_frame == 0
1847                              /* vbv_delay == 0xBBB || 0xE10 */;
1848
1849                 if (left < 0 ||
1850                     (left && show_bits(&s->gb, FFMIN(left, 23)) && !is_d10) ||
1851                     ((avctx->err_recognition & AV_EF_BUFFER) && left > 8)) {
1852                     av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d %0X\n",
1853                            left, show_bits(&s->gb, FFMIN(left, 23)));
1854                     return -1;
1855                 } else
1856                     goto eos;
1857             }
1858
1859             ff_init_block_index(s);
1860         }
1861
1862         /* skip mb handling */
1863         if (s->mb_skip_run == -1) {
1864             /* read increment again */
1865             s->mb_skip_run = 0;
1866             for (;;) {
1867                 int code = get_vlc2(&s->gb, ff_mbincr_vlc.table,
1868                                     MBINCR_VLC_BITS, 2);
1869                 if (code < 0) {
1870                     av_log(s->avctx, AV_LOG_ERROR, "mb incr damaged\n");
1871                     return -1;
1872                 }
1873                 if (code >= 33) {
1874                     if (code == 33) {
1875                         s->mb_skip_run += 33;
1876                     } else if (code == 35) {
1877                         if (s->mb_skip_run != 0 || show_bits(&s->gb, 15) != 0) {
1878                             av_log(s->avctx, AV_LOG_ERROR, "slice mismatch\n");
1879                             return -1;
1880                         }
1881                         goto eos; /* end of slice */
1882                     }
1883                     /* otherwise, stuffing, nothing to do */
1884                 } else {
1885                     s->mb_skip_run += code;
1886                     break;
1887                 }
1888             }
1889             if (s->mb_skip_run) {
1890                 int i;
1891                 if (s->pict_type == AV_PICTURE_TYPE_I) {
1892                     av_log(s->avctx, AV_LOG_ERROR,
1893                            "skipped MB in I frame at %d %d\n", s->mb_x, s->mb_y);
1894                     return -1;
1895                 }
1896
1897                 /* skip mb */
1898                 s->mb_intra = 0;
1899                 for (i = 0; i < 12; i++)
1900                     s->block_last_index[i] = -1;
1901                 if (s->picture_structure == PICT_FRAME)
1902                     s->mv_type = MV_TYPE_16X16;
1903                 else
1904                     s->mv_type = MV_TYPE_FIELD;
1905                 if (s->pict_type == AV_PICTURE_TYPE_P) {
1906                     /* if P type, zero motion vector is implied */
1907                     s->mv_dir             = MV_DIR_FORWARD;
1908                     s->mv[0][0][0]        = s->mv[0][0][1]      = 0;
1909                     s->last_mv[0][0][0]   = s->last_mv[0][0][1] = 0;
1910                     s->last_mv[0][1][0]   = s->last_mv[0][1][1] = 0;
1911                     s->field_select[0][0] = (s->picture_structure - 1) & 1;
1912                 } else {
1913                     /* if B type, reuse previous vectors and directions */
1914                     s->mv[0][0][0] = s->last_mv[0][0][0];
1915                     s->mv[0][0][1] = s->last_mv[0][0][1];
1916                     s->mv[1][0][0] = s->last_mv[1][0][0];
1917                     s->mv[1][0][1] = s->last_mv[1][0][1];
1918                 }
1919             }
1920         }
1921     }
1922 eos: // end of slice
1923     *buf += (get_bits_count(&s->gb) - 1) / 8;
1924     av_dlog(s, "y %d %d %d %d\n", s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y);
1925     return 0;
1926 }
1927
1928 static int slice_decode_thread(AVCodecContext *c, void *arg)
1929 {
1930     MpegEncContext *s   = *(void **) arg;
1931     const uint8_t *buf  = s->gb.buffer;
1932     int mb_y            = s->start_mb_y;
1933     const int field_pic = s->picture_structure != PICT_FRAME;
1934
1935     s->er.error_count = (3 * (s->end_mb_y - s->start_mb_y) * s->mb_width) >> field_pic;
1936
1937     for (;;) {
1938         uint32_t start_code;
1939         int ret;
1940
1941         ret = mpeg_decode_slice(s, mb_y, &buf, s->gb.buffer_end - buf);
1942         emms_c();
1943         av_dlog(c, "ret:%d resync:%d/%d mb:%d/%d ts:%d/%d ec:%d\n",
1944                 ret, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y,
1945                 s->start_mb_y, s->end_mb_y, s->er.error_count);
1946         if (ret < 0) {
1947             if (c->err_recognition & AV_EF_EXPLODE)
1948                 return ret;
1949             if (s->resync_mb_x >= 0 && s->resync_mb_y >= 0)
1950                 ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1951                                 s->mb_x, s->mb_y,
1952                                 ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);
1953         } else {
1954             ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1955                             s->mb_x - 1, s->mb_y,
1956                             ER_AC_END | ER_DC_END | ER_MV_END);
1957         }
1958
1959         if (s->mb_y == s->end_mb_y)
1960             return 0;
1961
1962         start_code = -1;
1963         buf        = avpriv_find_start_code(buf, s->gb.buffer_end, &start_code);
1964         mb_y       = (start_code - SLICE_MIN_START_CODE) << field_pic;
1965         if (s->picture_structure == PICT_BOTTOM_FIELD)
1966             mb_y++;
1967         if (mb_y < 0 || mb_y >= s->end_mb_y)
1968             return -1;
1969     }
1970 }
1971
1972 /**
1973  * Handle slice ends.
1974  * @return 1 if it seems to be the last slice
1975  */
1976 static int slice_end(AVCodecContext *avctx, AVFrame *pict)
1977 {
1978     Mpeg1Context *s1  = avctx->priv_data;
1979     MpegEncContext *s = &s1->mpeg_enc_ctx;
1980
1981     if (!s1->mpeg_enc_ctx_allocated || !s->current_picture_ptr)
1982         return 0;
1983
1984     if (s->avctx->hwaccel) {
1985         if (s->avctx->hwaccel->end_frame(s->avctx) < 0)
1986             av_log(avctx, AV_LOG_ERROR,
1987                    "hardware accelerator failed to decode picture\n");
1988     }
1989
1990 #if FF_API_XVMC
1991 FF_DISABLE_DEPRECATION_WARNINGS
1992     if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)
1993         ff_xvmc_field_end(s);
1994 FF_ENABLE_DEPRECATION_WARNINGS
1995 #endif /* FF_API_XVMC */
1996
1997     /* end of slice reached */
1998     if (/* s->mb_y << field_pic == s->mb_height && */ !s->first_field) {
1999         /* end of image */
2000
2001         ff_er_frame_end(&s->er);
2002
2003         ff_MPV_frame_end(s);
2004
2005         if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
2006             int ret = av_frame_ref(pict, s->current_picture_ptr->f);
2007             if (ret < 0)
2008                 return ret;
2009             ff_print_debug_info(s, s->current_picture_ptr);
2010         } else {
2011             if (avctx->active_thread_type & FF_THREAD_FRAME)
2012                 s->picture_number++;
2013             /* latency of 1 frame for I- and P-frames */
2014             /* XXX: use another variable than picture_number */
2015             if (s->last_picture_ptr != NULL) {
2016                 int ret = av_frame_ref(pict, s->last_picture_ptr->f);
2017                 if (ret < 0)
2018                     return ret;
2019                 ff_print_debug_info(s, s->last_picture_ptr);
2020             }
2021         }
2022
2023         return 1;
2024     } else {
2025         return 0;
2026     }
2027 }
2028
2029 static int mpeg1_decode_sequence(AVCodecContext *avctx,
2030                                  const uint8_t *buf, int buf_size)
2031 {
2032     Mpeg1Context *s1  = avctx->priv_data;
2033     MpegEncContext *s = &s1->mpeg_enc_ctx;
2034     int width, height;
2035     int i, v, j;
2036
2037     init_get_bits(&s->gb, buf, buf_size * 8);
2038
2039     width  = get_bits(&s->gb, 12);
2040     height = get_bits(&s->gb, 12);
2041     if (width == 0 || height == 0) {
2042         av_log(avctx, AV_LOG_WARNING,
2043                "Invalid horizontal or vertical size value.\n");
2044         if (avctx->err_recognition & AV_EF_BITSTREAM)
2045             return AVERROR_INVALIDDATA;
2046     }
2047     s->aspect_ratio_info = get_bits(&s->gb, 4);
2048     if (s->aspect_ratio_info == 0) {
2049         av_log(avctx, AV_LOG_ERROR, "aspect ratio has forbidden 0 value\n");
2050         if (avctx->err_recognition & AV_EF_BITSTREAM)
2051             return -1;
2052     }
2053     s->frame_rate_index = get_bits(&s->gb, 4);
2054     if (s->frame_rate_index == 0 || s->frame_rate_index > 13)
2055         return -1;
2056     s->bit_rate = get_bits(&s->gb, 18) * 400;
2057     if (get_bits1(&s->gb) == 0) /* marker */
2058         return -1;
2059     s->width  = width;
2060     s->height = height;
2061
2062     s->avctx->rc_buffer_size = get_bits(&s->gb, 10) * 1024 * 16;
2063     skip_bits(&s->gb, 1);
2064
2065     /* get matrix */
2066     if (get_bits1(&s->gb)) {
2067         load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
2068     } else {
2069         for (i = 0; i < 64; i++) {
2070             j = s->dsp.idct_permutation[i];
2071             v = ff_mpeg1_default_intra_matrix[i];
2072             s->intra_matrix[j]        = v;
2073             s->chroma_intra_matrix[j] = v;
2074         }
2075     }
2076     if (get_bits1(&s->gb)) {
2077         load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
2078     } else {
2079         for (i = 0; i < 64; i++) {
2080             int j = s->dsp.idct_permutation[i];
2081             v = ff_mpeg1_default_non_intra_matrix[i];
2082             s->inter_matrix[j]        = v;
2083             s->chroma_inter_matrix[j] = v;
2084         }
2085     }
2086
2087     if (show_bits(&s->gb, 23) != 0) {
2088         av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");
2089         return -1;
2090     }
2091
2092     /* We set MPEG-2 parameters so that it emulates MPEG-1. */
2093     s->progressive_sequence = 1;
2094     s->progressive_frame    = 1;
2095     s->picture_structure    = PICT_FRAME;
2096     s->frame_pred_frame_dct = 1;
2097     s->chroma_format        = 1;
2098     s->codec_id             =
2099     s->avctx->codec_id      = AV_CODEC_ID_MPEG1VIDEO;
2100     s->out_format           = FMT_MPEG1;
2101     if (s->flags & CODEC_FLAG_LOW_DELAY)
2102         s->low_delay = 1;
2103
2104     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2105         av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%d\n",
2106                s->avctx->rc_buffer_size, s->bit_rate);
2107
2108     return 0;
2109 }
2110
2111 static int vcr2_init_sequence(AVCodecContext *avctx)
2112 {
2113     Mpeg1Context *s1  = avctx->priv_data;
2114     MpegEncContext *s = &s1->mpeg_enc_ctx;
2115     int i, v;
2116
2117     /* start new MPEG-1 context decoding */
2118     s->out_format = FMT_MPEG1;
2119     if (s1->mpeg_enc_ctx_allocated) {
2120         ff_MPV_common_end(s);
2121     }
2122     s->width            = avctx->coded_width;
2123     s->height           = avctx->coded_height;
2124     avctx->has_b_frames = 0; // true?
2125     s->low_delay        = 1;
2126
2127     avctx->pix_fmt = mpeg_get_pixelformat(avctx);
2128
2129 #if FF_API_XVMC
2130     if ((avctx->pix_fmt == AV_PIX_FMT_XVMC_MPEG2_IDCT || avctx->hwaccel) &&
2131         avctx->idct_algo == FF_IDCT_AUTO)
2132 #else
2133     if (avctx->hwaccel && avctx->idct_algo == FF_IDCT_AUTO)
2134 #endif /* FF_API_XVMC */
2135         avctx->idct_algo = FF_IDCT_SIMPLE;
2136
2137     if (ff_MPV_common_init(s) < 0)
2138         return -1;
2139     s1->mpeg_enc_ctx_allocated = 1;
2140
2141     for (i = 0; i < 64; i++) {
2142         int j = s->dsp.idct_permutation[i];
2143         v = ff_mpeg1_default_intra_matrix[i];
2144         s->intra_matrix[j]        = v;
2145         s->chroma_intra_matrix[j] = v;
2146
2147         v = ff_mpeg1_default_non_intra_matrix[i];
2148         s->inter_matrix[j]        = v;
2149         s->chroma_inter_matrix[j] = v;
2150     }
2151
2152     s->progressive_sequence  = 1;
2153     s->progressive_frame     = 1;
2154     s->picture_structure     = PICT_FRAME;
2155     s->frame_pred_frame_dct  = 1;
2156     s->chroma_format         = 1;
2157     s->codec_id              = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO;
2158     s1->save_width           = s->width;
2159     s1->save_height          = s->height;
2160     s1->save_progressive_seq = s->progressive_sequence;
2161     return 0;
2162 }
2163
2164 static int mpeg_decode_a53_cc(AVCodecContext *avctx,
2165                               const uint8_t *p, int buf_size)
2166 {
2167     Mpeg1Context *s1 = avctx->priv_data;
2168
2169     if (buf_size >= 6 &&
2170         p[0] == 'G' && p[1] == 'A' && p[2] == '9' && p[3] == '4' &&
2171         p[4] == 3 && (p[5] & 0x40)) {
2172         /* extract A53 Part 4 CC data */
2173         int cc_count = p[5] & 0x1f;
2174         if (cc_count > 0 && buf_size >= 7 + cc_count * 3) {
2175             av_freep(&s1->a53_caption);
2176             s1->a53_caption_size = cc_count * 3;
2177             s1->a53_caption      = av_malloc(s1->a53_caption_size);
2178             if (s1->a53_caption)
2179                 memcpy(s1->a53_caption, p + 7, s1->a53_caption_size);
2180         }
2181         return 1;
2182     } else if (buf_size >= 11 &&
2183                p[0] == 'C' && p[1] == 'C' && p[2] == 0x01 && p[3] == 0xf8) {
2184         /* extract DVD CC data */
2185         int cc_count = 0;
2186         int i;
2187         // There is a caption count field in the data, but it is often
2188         // incorect.  So count the number of captions present.
2189         for (i = 5; i + 6 <= buf_size && ((p[i] & 0xfe) == 0xfe); i += 6)
2190             cc_count++;
2191         // Transform the DVD format into A53 Part 4 format
2192         if (cc_count > 0) {
2193             av_freep(&s1->a53_caption);
2194             s1->a53_caption_size = cc_count * 6;
2195             s1->a53_caption      = av_malloc(s1->a53_caption_size);
2196             if (s1->a53_caption) {
2197                 uint8_t field1 = !!(p[4] & 0x80);
2198                 uint8_t *cap = s1->a53_caption;
2199                 p += 5;
2200                 for (i = 0; i < cc_count; i++) {
2201                     cap[0] = (p[0] == 0xff && field1) ? 0xfc : 0xfd;
2202                     cap[1] = p[1];
2203                     cap[2] = p[2];
2204                     cap[3] = (p[3] == 0xff && !field1) ? 0xfc : 0xfd;
2205                     cap[4] = p[4];
2206                     cap[5] = p[5];
2207                     cap += 6;
2208                     p += 6;
2209                 }
2210             }
2211         }
2212         return 1;
2213     }
2214     return 0;
2215 }
2216
2217 static void mpeg_decode_user_data(AVCodecContext *avctx,
2218                                   const uint8_t *p, int buf_size)
2219 {
2220     const uint8_t *buf_end = p + buf_size;
2221
2222     /* we parse the DTG active format information */
2223     if (buf_end - p >= 5 &&
2224         p[0] == 'D' && p[1] == 'T' && p[2] == 'G' && p[3] == '1') {
2225         int flags = p[4];
2226         p += 5;
2227         if (flags & 0x80) {
2228             /* skip event id */
2229             p += 2;
2230         }
2231         if (flags & 0x40) {
2232             if (buf_end - p < 1)
2233                 return;
2234             avctx->dtg_active_format = p[0] & 0x0f;
2235         }
2236     } else if (buf_end - p >= 6 &&
2237                p[0] == 'J' && p[1] == 'P' && p[2] == '3' && p[3] == 'D' &&
2238                p[4] == 0x03) { // S3D_video_format_length
2239         // the 0x7F mask ignores the reserved_bit value
2240         const uint8_t S3D_video_format_type = p[5] & 0x7F;
2241
2242         if (S3D_video_format_type == 0x03 ||
2243             S3D_video_format_type == 0x04 ||
2244             S3D_video_format_type == 0x08 ||
2245             S3D_video_format_type == 0x23) {
2246             Mpeg1Context *s1   = avctx->priv_data;
2247
2248             s1->has_stereo3d = 1;
2249
2250             switch (S3D_video_format_type) {
2251             case 0x03:
2252                 s1->stereo3d.type = AV_STEREO3D_SIDEBYSIDE;
2253                 break;
2254             case 0x04:
2255                 s1->stereo3d.type = AV_STEREO3D_TOPBOTTOM;
2256                 break;
2257             case 0x08:
2258                 s1->stereo3d.type = AV_STEREO3D_2D;
2259                 break;
2260             case 0x23:
2261                 s1->stereo3d.type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2262                 break;
2263             }
2264         }
2265     } else if (mpeg_decode_a53_cc(avctx, p, buf_size)) {
2266         return;
2267     }
2268 }
2269
2270 static void mpeg_decode_gop(AVCodecContext *avctx,
2271                             const uint8_t *buf, int buf_size)
2272 {
2273     Mpeg1Context *s1  = avctx->priv_data;
2274     MpegEncContext *s = &s1->mpeg_enc_ctx;
2275
2276     int time_code_hours, time_code_minutes;
2277     int time_code_seconds, time_code_pictures;
2278     int broken_link;
2279
2280     init_get_bits(&s->gb, buf, buf_size * 8);
2281
2282     skip_bits1(&s->gb); /* drop_frame_flag */
2283
2284     time_code_hours   = get_bits(&s->gb, 5);
2285     time_code_minutes = get_bits(&s->gb, 6);
2286     skip_bits1(&s->gb); // marker bit
2287     time_code_seconds  = get_bits(&s->gb, 6);
2288     time_code_pictures = get_bits(&s->gb, 6);
2289
2290     s1->closed_gop = get_bits1(&s->gb);
2291     /* broken_link indicate that after editing the
2292      * reference frames of the first B-Frames after GOP I-Frame
2293      * are missing (open gop) */
2294     broken_link = get_bits1(&s->gb);
2295
2296     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2297         av_log(s->avctx, AV_LOG_DEBUG,
2298                "GOP (%2d:%02d:%02d.[%02d]) closed_gop=%d broken_link=%d\n",
2299                time_code_hours, time_code_minutes, time_code_seconds,
2300                time_code_pictures, s1->closed_gop, broken_link);
2301 }
2302
2303 static int decode_chunks(AVCodecContext *avctx, AVFrame *picture,
2304                          int *got_output, const uint8_t *buf, int buf_size)
2305 {
2306     Mpeg1Context *s = avctx->priv_data;
2307     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2308     const uint8_t *buf_ptr = buf;
2309     const uint8_t *buf_end = buf + buf_size;
2310     int ret, input_size;
2311     int last_code = 0, skip_frame = 0;
2312
2313     for (;;) {
2314         /* find next start code */
2315         uint32_t start_code = -1;
2316         buf_ptr = avpriv_find_start_code(buf_ptr, buf_end, &start_code);
2317         if (start_code > 0x1ff) {
2318             if (!skip_frame) {
2319                 if (HAVE_THREADS &&
2320                     (avctx->active_thread_type & FF_THREAD_SLICE) &&
2321                     !avctx->hwaccel) {
2322                     int i;
2323
2324                     avctx->execute(avctx, slice_decode_thread,
2325                                    &s2->thread_context[0], NULL,
2326                                    s->slice_count, sizeof(void *));
2327                     for (i = 0; i < s->slice_count; i++)
2328                         s2->er.error_count += s2->thread_context[i]->er.error_count;
2329                 }
2330
2331                 ret = slice_end(avctx, picture);
2332                 if (ret < 0)
2333                     return ret;
2334                 else if (ret) {
2335                     // FIXME: merge with the stuff in mpeg_decode_slice
2336                     if (s2->last_picture_ptr || s2->low_delay)
2337                         *got_output = 1;
2338                 }
2339             }
2340             s2->pict_type = 0;
2341             return FFMAX(0, buf_ptr - buf - s2->parse_context.last_index);
2342         }
2343
2344         input_size = buf_end - buf_ptr;
2345
2346         if (avctx->debug & FF_DEBUG_STARTCODE)
2347             av_log(avctx, AV_LOG_DEBUG, "%3"PRIX32" at %td left %d\n",
2348                    start_code, buf_ptr - buf, input_size);
2349
2350         /* prepare data for next start code */
2351         switch (start_code) {
2352         case SEQ_START_CODE:
2353             if (last_code == 0) {
2354                 mpeg1_decode_sequence(avctx, buf_ptr, input_size);
2355                 s->sync = 1;
2356             } else {
2357                 av_log(avctx, AV_LOG_ERROR,
2358                        "ignoring SEQ_START_CODE after %X\n", last_code);
2359                 if (avctx->err_recognition & AV_EF_EXPLODE)
2360                     return AVERROR_INVALIDDATA;
2361             }
2362             break;
2363
2364         case PICTURE_START_CODE:
2365             if (s2->width <= 0 || s2->height <= 0) {
2366                 av_log(avctx, AV_LOG_ERROR, "Invalid frame dimensions %dx%d.\n",
2367                        s2->width, s2->height);
2368                 return AVERROR_INVALIDDATA;
2369             }
2370
2371             if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE) &&
2372                 !avctx->hwaccel && s->slice_count) {
2373                 int i;
2374
2375                 avctx->execute(avctx, slice_decode_thread,
2376                                s2->thread_context, NULL,
2377                                s->slice_count, sizeof(void *));
2378                 for (i = 0; i < s->slice_count; i++)
2379                     s2->er.error_count += s2->thread_context[i]->er.error_count;
2380                 s->slice_count = 0;
2381             }
2382             if (last_code == 0 || last_code == SLICE_MIN_START_CODE) {
2383                 ret = mpeg_decode_postinit(avctx);
2384                 if (ret < 0) {
2385                     av_log(avctx, AV_LOG_ERROR,
2386                            "mpeg_decode_postinit() failure\n");
2387                     return ret;
2388                 }
2389
2390                 /* We have a complete image: we try to decompress it. */
2391                 if (mpeg1_decode_picture(avctx, buf_ptr, input_size) < 0)
2392                     s2->pict_type = 0;
2393                 s->first_slice = 1;
2394                 last_code      = PICTURE_START_CODE;
2395             } else {
2396                 av_log(avctx, AV_LOG_ERROR,
2397                        "ignoring pic after %X\n", last_code);
2398                 if (avctx->err_recognition & AV_EF_EXPLODE)
2399                     return AVERROR_INVALIDDATA;
2400             }
2401             break;
2402         case EXT_START_CODE:
2403             init_get_bits(&s2->gb, buf_ptr, input_size * 8);
2404
2405             switch (get_bits(&s2->gb, 4)) {
2406             case 0x1:
2407                 if (last_code == 0) {
2408                     mpeg_decode_sequence_extension(s);
2409                 } else {
2410                     av_log(avctx, AV_LOG_ERROR,
2411                            "ignoring seq ext after %X\n", last_code);
2412                     if (avctx->err_recognition & AV_EF_EXPLODE)
2413                         return AVERROR_INVALIDDATA;
2414                 }
2415                 break;
2416             case 0x2:
2417                 mpeg_decode_sequence_display_extension(s);
2418                 break;
2419             case 0x3:
2420                 mpeg_decode_quant_matrix_extension(s2);
2421                 break;
2422             case 0x7:
2423                 mpeg_decode_picture_display_extension(s);
2424                 break;
2425             case 0x8:
2426                 if (last_code == PICTURE_START_CODE) {
2427                     mpeg_decode_picture_coding_extension(s);
2428                 } else {
2429                     av_log(avctx, AV_LOG_ERROR,
2430                            "ignoring pic cod ext after %X\n", last_code);
2431                     if (avctx->err_recognition & AV_EF_EXPLODE)
2432                         return AVERROR_INVALIDDATA;
2433                 }
2434                 break;
2435             }
2436             break;
2437         case USER_START_CODE:
2438             mpeg_decode_user_data(avctx, buf_ptr, input_size);
2439             break;
2440         case GOP_START_CODE:
2441             if (last_code == 0) {
2442                 s2->first_field = 0;
2443                 mpeg_decode_gop(avctx, buf_ptr, input_size);
2444                 s->sync = 1;
2445             } else {
2446                 av_log(avctx, AV_LOG_ERROR,
2447                        "ignoring GOP_START_CODE after %X\n", last_code);
2448                 if (avctx->err_recognition & AV_EF_EXPLODE)
2449                     return AVERROR_INVALIDDATA;
2450             }
2451             break;
2452         default:
2453             if (start_code >= SLICE_MIN_START_CODE &&
2454                 start_code <= SLICE_MAX_START_CODE && last_code != 0) {
2455                 const int field_pic = s2->picture_structure != PICT_FRAME;
2456                 int mb_y = (start_code - SLICE_MIN_START_CODE) << field_pic;
2457                 last_code = SLICE_MIN_START_CODE;
2458
2459                 if (s2->picture_structure == PICT_BOTTOM_FIELD)
2460                     mb_y++;
2461
2462                 if (mb_y >= s2->mb_height) {
2463                     av_log(s2->avctx, AV_LOG_ERROR,
2464                            "slice below image (%d >= %d)\n", mb_y, s2->mb_height);
2465                     return -1;
2466                 }
2467
2468                 if (s2->last_picture_ptr == NULL) {
2469                     /* Skip B-frames if we do not have reference frames and
2470                      * GOP is not closed. */
2471                     if (s2->pict_type == AV_PICTURE_TYPE_B) {
2472                         if (!s->closed_gop) {
2473                             skip_frame = 1;
2474                             break;
2475                         }
2476                     }
2477                 }
2478                 if (s2->pict_type == AV_PICTURE_TYPE_I)
2479                     s->sync = 1;
2480                 if (s2->next_picture_ptr == NULL) {
2481                     /* Skip P-frames if we do not have a reference frame or
2482                      * we have an invalid header. */
2483                     if (s2->pict_type == AV_PICTURE_TYPE_P && !s->sync) {
2484                         skip_frame = 1;
2485                         break;
2486                     }
2487                 }
2488                 if ((avctx->skip_frame >= AVDISCARD_NONREF &&
2489                      s2->pict_type == AV_PICTURE_TYPE_B) ||
2490                     (avctx->skip_frame >= AVDISCARD_NONKEY &&
2491                      s2->pict_type != AV_PICTURE_TYPE_I) ||
2492                     avctx->skip_frame >= AVDISCARD_ALL) {
2493                     skip_frame = 1;
2494                     break;
2495                 }
2496
2497                 if (!s->mpeg_enc_ctx_allocated)
2498                     break;
2499
2500                 if (s2->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2501                     if (mb_y < avctx->skip_top ||
2502                         mb_y >= s2->mb_height - avctx->skip_bottom)
2503                         break;
2504                 }
2505
2506                 if (!s2->pict_type) {
2507                     av_log(avctx, AV_LOG_ERROR, "Missing picture start code\n");
2508                     if (avctx->err_recognition & AV_EF_EXPLODE)
2509                         return AVERROR_INVALIDDATA;
2510                     break;
2511                 }
2512
2513                 if (s->first_slice) {
2514                     skip_frame     = 0;
2515                     s->first_slice = 0;
2516                     if (mpeg_field_start(s2, buf, buf_size) < 0)
2517                         return -1;
2518                 }
2519                 if (!s2->current_picture_ptr) {
2520                     av_log(avctx, AV_LOG_ERROR,
2521                            "current_picture not initialized\n");
2522                     return AVERROR_INVALIDDATA;
2523                 }
2524
2525                 if (HAVE_THREADS &&
2526                     (avctx->active_thread_type & FF_THREAD_SLICE) &&
2527                     !avctx->hwaccel) {
2528                     int threshold = (s2->mb_height * s->slice_count +
2529                                      s2->slice_context_count / 2) /
2530                                     s2->slice_context_count;
2531                     if (threshold <= mb_y) {
2532                         MpegEncContext *thread_context = s2->thread_context[s->slice_count];
2533
2534                         thread_context->start_mb_y = mb_y;
2535                         thread_context->end_mb_y   = s2->mb_height;
2536                         if (s->slice_count) {
2537                             s2->thread_context[s->slice_count - 1]->end_mb_y = mb_y;
2538                             ret = ff_update_duplicate_context(thread_context, s2);
2539                             if (ret < 0)
2540                                 return ret;
2541                         }
2542                         init_get_bits(&thread_context->gb, buf_ptr, input_size * 8);
2543                         s->slice_count++;
2544                     }
2545                     buf_ptr += 2; // FIXME add minimum number of bytes per slice
2546                 } else {
2547                     ret = mpeg_decode_slice(s2, mb_y, &buf_ptr, input_size);
2548                     emms_c();
2549
2550                     if (ret < 0) {
2551                         if (avctx->err_recognition & AV_EF_EXPLODE)
2552                             return ret;
2553                         if (s2->resync_mb_x >= 0 && s2->resync_mb_y >= 0)
2554                             ff_er_add_slice(&s2->er, s2->resync_mb_x,
2555                                             s2->resync_mb_y, s2->mb_x, s2->mb_y,
2556                                             ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);
2557                     } else {
2558                         ff_er_add_slice(&s2->er, s2->resync_mb_x,
2559                                         s2->resync_mb_y, s2->mb_x - 1, s2->mb_y,
2560                                         ER_AC_END | ER_DC_END | ER_MV_END);
2561                     }
2562                 }
2563             }
2564             break;
2565         }
2566     }
2567 }
2568
2569 static int mpeg_decode_frame(AVCodecContext *avctx, void *data,
2570                              int *got_output, AVPacket *avpkt)
2571 {
2572     const uint8_t *buf = avpkt->data;
2573     int buf_size = avpkt->size;
2574     Mpeg1Context *s = avctx->priv_data;
2575     AVFrame *picture = data;
2576     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2577     av_dlog(avctx, "fill_buffer\n");
2578
2579     if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {
2580         /* special case for last picture */
2581         if (s2->low_delay == 0 && s2->next_picture_ptr) {
2582             int ret = av_frame_ref(picture, s2->next_picture_ptr->f);
2583             if (ret < 0)
2584                 return ret;
2585
2586             s2->next_picture_ptr = NULL;
2587
2588             *got_output = 1;
2589         }
2590         return buf_size;
2591     }
2592
2593     if (s2->flags & CODEC_FLAG_TRUNCATED) {
2594         int next = ff_mpeg1_find_frame_end(&s2->parse_context, buf,
2595                                            buf_size, NULL);
2596
2597         if (ff_combine_frame(&s2->parse_context, next,
2598                              (const uint8_t **) &buf, &buf_size) < 0)
2599             return buf_size;
2600     }
2601
2602     if (s->mpeg_enc_ctx_allocated == 0 && avctx->codec_tag == AV_RL32("VCR2"))
2603         vcr2_init_sequence(avctx);
2604
2605     s->slice_count = 0;
2606
2607     if (avctx->extradata && !s->extradata_decoded) {
2608         int ret = decode_chunks(avctx, picture, got_output,
2609                                 avctx->extradata, avctx->extradata_size);
2610         s->extradata_decoded = 1;
2611         if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
2612             return ret;
2613     }
2614
2615     return decode_chunks(avctx, picture, got_output, buf, buf_size);
2616 }
2617
2618 static void flush(AVCodecContext *avctx)
2619 {
2620     Mpeg1Context *s = avctx->priv_data;
2621
2622     s->sync       = 0;
2623     s->closed_gop = 0;
2624
2625     ff_mpeg_flush(avctx);
2626 }
2627
2628 static av_cold int mpeg_decode_end(AVCodecContext *avctx)
2629 {
2630     Mpeg1Context *s = avctx->priv_data;
2631
2632     if (s->mpeg_enc_ctx_allocated)
2633         ff_MPV_common_end(&s->mpeg_enc_ctx);
2634     av_freep(&s->a53_caption);
2635     return 0;
2636 }
2637
2638 static const AVProfile mpeg2_video_profiles[] = {
2639     { FF_PROFILE_MPEG2_422,          "4:2:2"              },
2640     { FF_PROFILE_MPEG2_HIGH,         "High"               },
2641     { FF_PROFILE_MPEG2_SS,           "Spatially Scalable" },
2642     { FF_PROFILE_MPEG2_SNR_SCALABLE, "SNR Scalable"       },
2643     { FF_PROFILE_MPEG2_MAIN,         "Main"               },
2644     { FF_PROFILE_MPEG2_SIMPLE,       "Simple"             },
2645     { FF_PROFILE_RESERVED,           "Reserved"           },
2646     { FF_PROFILE_RESERVED,           "Reserved"           },
2647     { FF_PROFILE_UNKNOWN                                  },
2648 };
2649
2650 AVCodec ff_mpeg1video_decoder = {
2651     .name                  = "mpeg1video",
2652     .long_name             = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
2653     .type                  = AVMEDIA_TYPE_VIDEO,
2654     .id                    = AV_CODEC_ID_MPEG1VIDEO,
2655     .priv_data_size        = sizeof(Mpeg1Context),
2656     .init                  = mpeg_decode_init,
2657     .close                 = mpeg_decode_end,
2658     .decode                = mpeg_decode_frame,
2659     .capabilities          = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2660                              CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2661                              CODEC_CAP_SLICE_THREADS,
2662     .flush                 = flush,
2663     .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg_decode_update_thread_context)
2664 };
2665
2666 AVCodec ff_mpeg2video_decoder = {
2667     .name           = "mpeg2video",
2668     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
2669     .type           = AVMEDIA_TYPE_VIDEO,
2670     .id             = AV_CODEC_ID_MPEG2VIDEO,
2671     .priv_data_size = sizeof(Mpeg1Context),
2672     .init           = mpeg_decode_init,
2673     .close          = mpeg_decode_end,
2674     .decode         = mpeg_decode_frame,
2675     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2676                       CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2677                       CODEC_CAP_SLICE_THREADS,
2678     .flush          = flush,
2679     .profiles       = NULL_IF_CONFIG_SMALL(mpeg2_video_profiles),
2680 };
2681
2682 #if FF_API_XVMC
2683 #if CONFIG_MPEG_XVMC_DECODER
2684 static av_cold int mpeg_mc_decode_init(AVCodecContext *avctx)
2685 {
2686     if (avctx->active_thread_type & FF_THREAD_SLICE)
2687         return -1;
2688     if (!(avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
2689         return -1;
2690     if (!(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD)) {
2691         av_dlog(avctx, "mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");
2692     }
2693     mpeg_decode_init(avctx);
2694
2695     avctx->pix_fmt           = AV_PIX_FMT_XVMC_MPEG2_IDCT;
2696     avctx->xvmc_acceleration = 2; // 2 - the blocks are packed!
2697
2698     return 0;
2699 }
2700
2701 AVCodec ff_mpeg_xvmc_decoder = {
2702     .name           = "mpegvideo_xvmc",
2703     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1/2 video XvMC (X-Video Motion Compensation)"),
2704     .type           = AVMEDIA_TYPE_VIDEO,
2705     .id             = AV_CODEC_ID_MPEG2VIDEO_XVMC,
2706     .priv_data_size = sizeof(Mpeg1Context),
2707     .init           = mpeg_mc_decode_init,
2708     .close          = mpeg_decode_end,
2709     .decode         = mpeg_decode_frame,
2710     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2711                       CODEC_CAP_TRUNCATED | CODEC_CAP_HWACCEL | CODEC_CAP_DELAY,
2712     .flush          = flush,
2713 };
2714
2715 #endif
2716 #endif /* FF_API_XVMC */