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