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