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