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