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