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