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