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