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