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