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