fix vdpau vc1 interlace modes
[ffmpeg.git] / libavcodec / mpeg12dec.c
1 /*
2  * MPEG-1/2 decoder
3  * Copyright (c) 2000, 2001 Fabrice Bellard
4  * Copyright (c) 2002-2013 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * MPEG-1/2 decoder
26  */
27
28 //#define DEBUG
29 #include "libavutil/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 //            assert(s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride - 1] & (MB_TYPE_16x16 | MB_TYPE_16x8));
676
677             if ((s->mv[0][0][0] | s->mv[0][0][1] | s->mv[1][0][0] | s->mv[1][0][1]) == 0)
678                 s->mb_skipped = 1;
679         }
680
681         return 0;
682     }
683
684     switch (s->pict_type) {
685     default:
686     case AV_PICTURE_TYPE_I:
687         if (get_bits1(&s->gb) == 0) {
688             if (get_bits1(&s->gb) == 0) {
689                 av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in I Frame at %d %d\n", s->mb_x, s->mb_y);
690                 return -1;
691             }
692             mb_type = MB_TYPE_QUANT | MB_TYPE_INTRA;
693         } else {
694             mb_type = MB_TYPE_INTRA;
695         }
696         break;
697     case AV_PICTURE_TYPE_P:
698         mb_type = get_vlc2(&s->gb, ff_mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
699         if (mb_type < 0) {
700             av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
701             return -1;
702         }
703         mb_type = ptype2mb_type[mb_type];
704         break;
705     case AV_PICTURE_TYPE_B:
706         mb_type = get_vlc2(&s->gb, ff_mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
707         if (mb_type < 0) {
708             av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
709             return -1;
710         }
711         mb_type = btype2mb_type[mb_type];
712         break;
713     }
714     av_dlog(s->avctx, "mb_type=%x\n", mb_type);
715 //    motion_type = 0; /* avoid warning */
716     if (IS_INTRA(mb_type)) {
717         s->dsp.clear_blocks(s->block[0]);
718
719         if (!s->chroma_y_shift) {
720             s->dsp.clear_blocks(s->block[6]);
721         }
722
723         /* compute DCT type */
724         if (s->picture_structure == PICT_FRAME && // FIXME add an interlaced_dct coded var?
725             !s->frame_pred_frame_dct) {
726             s->interlaced_dct = get_bits1(&s->gb);
727         }
728
729         if (IS_QUANT(mb_type))
730             s->qscale = get_qscale(s);
731
732         if (s->concealment_motion_vectors) {
733             /* just parse them */
734             if (s->picture_structure != PICT_FRAME)
735                 skip_bits1(&s->gb); /* field select */
736
737             s->mv[0][0][0]= s->last_mv[0][0][0]= s->last_mv[0][1][0] =
738                 mpeg_decode_motion(s, s->mpeg_f_code[0][0], s->last_mv[0][0][0]);
739             s->mv[0][0][1]= s->last_mv[0][0][1]= s->last_mv[0][1][1] =
740                 mpeg_decode_motion(s, s->mpeg_f_code[0][1], s->last_mv[0][0][1]);
741
742             skip_bits1(&s->gb); /* marker */
743         } else
744             memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
745         s->mb_intra = 1;
746         // if 1, we memcpy blocks in xvmcvideo
747         if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration > 1) {
748             ff_xvmc_pack_pblocks(s, -1); // inter are always full blocks
749             if (s->swap_uv) {
750                 exchange_uv(s);
751             }
752         }
753
754         if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
755             if (s->flags2 & CODEC_FLAG2_FAST) {
756                 for (i = 0; i < 6; i++) {
757                     mpeg2_fast_decode_block_intra(s, *s->pblocks[i], i);
758                 }
759             } else {
760                 for (i = 0; i < mb_block_count; i++) {
761                     if (mpeg2_decode_block_intra(s, *s->pblocks[i], i) < 0)
762                         return -1;
763                 }
764             }
765         } else {
766             for (i = 0; i < 6; i++) {
767                 if (mpeg1_decode_block_intra(s, *s->pblocks[i], i) < 0)
768                     return -1;
769             }
770         }
771     } else {
772         if (mb_type & MB_TYPE_ZERO_MV) {
773             av_assert2(mb_type & MB_TYPE_CBP);
774
775             s->mv_dir = MV_DIR_FORWARD;
776             if (s->picture_structure == PICT_FRAME) {
777                 if (s->picture_structure == PICT_FRAME
778                     && !s->frame_pred_frame_dct)
779                     s->interlaced_dct = get_bits1(&s->gb);
780                 s->mv_type = MV_TYPE_16X16;
781             } else {
782                 s->mv_type = MV_TYPE_FIELD;
783                 mb_type |= MB_TYPE_INTERLACED;
784                 s->field_select[0][0] = s->picture_structure - 1;
785             }
786
787             if (IS_QUANT(mb_type))
788                 s->qscale = get_qscale(s);
789
790             s->last_mv[0][0][0] = 0;
791             s->last_mv[0][0][1] = 0;
792             s->last_mv[0][1][0] = 0;
793             s->last_mv[0][1][1] = 0;
794             s->mv[0][0][0] = 0;
795             s->mv[0][0][1] = 0;
796         } else {
797             av_assert2(mb_type & MB_TYPE_L0L1);
798             // FIXME decide if MBs in field pictures are MB_TYPE_INTERLACED
799             /* get additional motion vector type */
800             if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct)
801                 motion_type = MT_FRAME;
802             else {
803                 motion_type = get_bits(&s->gb, 2);
804                 if (s->picture_structure == PICT_FRAME && HAS_CBP(mb_type))
805                     s->interlaced_dct = get_bits1(&s->gb);
806             }
807
808             if (IS_QUANT(mb_type))
809                 s->qscale = get_qscale(s);
810
811             /* motion vectors */
812             s->mv_dir = (mb_type >> 13) & 3;
813             av_dlog(s->avctx, "motion_type=%d\n", motion_type);
814             switch (motion_type) {
815             case MT_FRAME: /* or MT_16X8 */
816                 if (s->picture_structure == PICT_FRAME) {
817                     mb_type |= MB_TYPE_16x16;
818                     s->mv_type = MV_TYPE_16X16;
819                     for (i = 0; i < 2; i++) {
820                         if (USES_LIST(mb_type, i)) {
821                             /* MT_FRAME */
822                             s->mv[i][0][0]= s->last_mv[i][0][0]= s->last_mv[i][1][0] =
823                                 mpeg_decode_motion(s, s->mpeg_f_code[i][0], s->last_mv[i][0][0]);
824                             s->mv[i][0][1]= s->last_mv[i][0][1]= s->last_mv[i][1][1] =
825                                 mpeg_decode_motion(s, s->mpeg_f_code[i][1], s->last_mv[i][0][1]);
826                             /* full_pel: only for MPEG-1 */
827                             if (s->full_pel[i]) {
828                                 s->mv[i][0][0] <<= 1;
829                                 s->mv[i][0][1] <<= 1;
830                             }
831                         }
832                     }
833                 } else {
834                     mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
835                     s->mv_type = MV_TYPE_16X8;
836                     for (i = 0; i < 2; i++) {
837                         if (USES_LIST(mb_type, i)) {
838                             /* MT_16X8 */
839                             for (j = 0; j < 2; j++) {
840                                 s->field_select[i][j] = get_bits1(&s->gb);
841                                 for (k = 0; k < 2; k++) {
842                                     val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
843                                                              s->last_mv[i][j][k]);
844                                     s->last_mv[i][j][k] = val;
845                                     s->mv[i][j][k]      = val;
846                                 }
847                             }
848                         }
849                     }
850                 }
851                 break;
852             case MT_FIELD:
853                 s->mv_type = MV_TYPE_FIELD;
854                 if (s->picture_structure == PICT_FRAME) {
855                     mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
856                     for (i = 0; i < 2; i++) {
857                         if (USES_LIST(mb_type, i)) {
858                             for (j = 0; j < 2; j++) {
859                                 s->field_select[i][j] = get_bits1(&s->gb);
860                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
861                                                          s->last_mv[i][j][0]);
862                                 s->last_mv[i][j][0] = val;
863                                 s->mv[i][j][0]      = val;
864                                 av_dlog(s->avctx, "fmx=%d\n", val);
865                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
866                                                          s->last_mv[i][j][1] >> 1);
867                                 s->last_mv[i][j][1] = val << 1;
868                                 s->mv[i][j][1]      = val;
869                                 av_dlog(s->avctx, "fmy=%d\n", val);
870                             }
871                         }
872                     }
873                 } else {
874                     av_assert0(!s->progressive_sequence);
875                     mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
876                     for (i = 0; i < 2; i++) {
877                         if (USES_LIST(mb_type, i)) {
878                             s->field_select[i][0] = get_bits1(&s->gb);
879                             for (k = 0; k < 2; k++) {
880                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
881                                                          s->last_mv[i][0][k]);
882                                 s->last_mv[i][0][k] = val;
883                                 s->last_mv[i][1][k] = val;
884                                 s->mv[i][0][k]      = val;
885                             }
886                         }
887                     }
888                 }
889                 break;
890             case MT_DMV:
891                 if(s->progressive_sequence){
892                     av_log(s->avctx, AV_LOG_ERROR, "MT_DMV in progressive_sequence\n");
893                     return -1;
894                 }
895                 s->mv_type = MV_TYPE_DMV;
896                 for (i = 0; i < 2; i++) {
897                     if (USES_LIST(mb_type, i)) {
898                         int dmx, dmy, mx, my, m;
899                         const int my_shift = s->picture_structure == PICT_FRAME;
900
901                         mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
902                                                 s->last_mv[i][0][0]);
903                         s->last_mv[i][0][0] = mx;
904                         s->last_mv[i][1][0] = mx;
905                         dmx = get_dmv(s);
906                         my  = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
907                                                  s->last_mv[i][0][1] >> my_shift);
908                         dmy = get_dmv(s);
909
910
911                         s->last_mv[i][0][1] = my << my_shift;
912                         s->last_mv[i][1][1] = my << my_shift;
913
914                         s->mv[i][0][0] = mx;
915                         s->mv[i][0][1] = my;
916                         s->mv[i][1][0] = mx; // not used
917                         s->mv[i][1][1] = my; // not used
918
919                         if (s->picture_structure == PICT_FRAME) {
920                             mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
921
922                             // m = 1 + 2 * s->top_field_first;
923                             m = s->top_field_first ? 1 : 3;
924
925                             /* top -> top pred */
926                             s->mv[i][2][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
927                             s->mv[i][2][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
928                             m = 4 - m;
929                             s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
930                             s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
931                         } else {
932                             mb_type |= MB_TYPE_16x16;
933
934                             s->mv[i][2][0] = ((mx + (mx > 0)) >> 1) + dmx;
935                             s->mv[i][2][1] = ((my + (my > 0)) >> 1) + dmy;
936                             if (s->picture_structure == PICT_TOP_FIELD)
937                                 s->mv[i][2][1]--;
938                             else
939                                 s->mv[i][2][1]++;
940                         }
941                     }
942                 }
943                 break;
944             default:
945                 av_log(s->avctx, AV_LOG_ERROR, "00 motion_type at %d %d\n", s->mb_x, s->mb_y);
946                 return -1;
947             }
948         }
949
950         s->mb_intra = 0;
951         if (HAS_CBP(mb_type)) {
952             s->dsp.clear_blocks(s->block[0]);
953
954             cbp = get_vlc2(&s->gb, ff_mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
955             if (mb_block_count > 6) {
956                  cbp <<= mb_block_count - 6;
957                  cbp  |= get_bits(&s->gb, mb_block_count - 6);
958                  s->dsp.clear_blocks(s->block[6]);
959             }
960             if (cbp <= 0) {
961                 av_log(s->avctx, AV_LOG_ERROR, "invalid cbp %d at %d %d\n", cbp, s->mb_x, s->mb_y);
962                 return -1;
963             }
964
965             //if 1, we memcpy blocks in xvmcvideo
966             if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration > 1) {
967                 ff_xvmc_pack_pblocks(s, cbp);
968                 if (s->swap_uv) {
969                     exchange_uv(s);
970                 }
971             }
972
973             if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
974                 if (s->flags2 & CODEC_FLAG2_FAST) {
975                     for (i = 0; i < 6; i++) {
976                         if (cbp & 32) {
977                             mpeg2_fast_decode_block_non_intra(s, *s->pblocks[i], i);
978                         } else {
979                             s->block_last_index[i] = -1;
980                         }
981                         cbp += cbp;
982                     }
983                 } else {
984                     cbp <<= 12-mb_block_count;
985
986                     for (i = 0; i < mb_block_count; i++) {
987                         if (cbp & (1 << 11)) {
988                             if (mpeg2_decode_block_non_intra(s, *s->pblocks[i], i) < 0)
989                                 return -1;
990                         } else {
991                             s->block_last_index[i] = -1;
992                         }
993                         cbp += cbp;
994                     }
995                 }
996             } else {
997                 if (s->flags2 & CODEC_FLAG2_FAST) {
998                     for (i = 0; i < 6; i++) {
999                         if (cbp & 32) {
1000                             mpeg1_fast_decode_block_inter(s, *s->pblocks[i], i);
1001                         } else {
1002                             s->block_last_index[i] = -1;
1003                         }
1004                         cbp += cbp;
1005                     }
1006                 } else {
1007                     for (i = 0; i < 6; i++) {
1008                         if (cbp & 32) {
1009                             if (mpeg1_decode_block_inter(s, *s->pblocks[i], i) < 0)
1010                                 return -1;
1011                         } else {
1012                             s->block_last_index[i] = -1;
1013                         }
1014                         cbp += cbp;
1015                     }
1016                 }
1017             }
1018         } else {
1019             for (i = 0; i < 12; i++)
1020                 s->block_last_index[i] = -1;
1021         }
1022     }
1023
1024     s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride] = mb_type;
1025
1026     return 0;
1027 }
1028
1029 static av_cold int mpeg_decode_init(AVCodecContext *avctx)
1030 {
1031     Mpeg1Context *s = avctx->priv_data;
1032     MpegEncContext *s2 = &s->mpeg_enc_ctx;
1033     int i;
1034
1035     /* we need some permutation to store matrices,
1036      * until MPV_common_init() sets the real permutation. */
1037     for (i = 0; i < 64; i++)
1038        s2->dsp.idct_permutation[i]=i;
1039
1040     ff_MPV_decode_defaults(s2);
1041
1042     s->mpeg_enc_ctx.avctx  = avctx;
1043     s->mpeg_enc_ctx.flags  = avctx->flags;
1044     s->mpeg_enc_ctx.flags2 = avctx->flags2;
1045     ff_mpeg12_common_init(&s->mpeg_enc_ctx);
1046     ff_mpeg12_init_vlcs();
1047
1048     s->mpeg_enc_ctx_allocated      = 0;
1049     s->mpeg_enc_ctx.picture_number = 0;
1050     s->repeat_field                = 0;
1051     s->mpeg_enc_ctx.codec_id       = avctx->codec->id;
1052     avctx->color_range = AVCOL_RANGE_MPEG;
1053     if (avctx->codec->id == AV_CODEC_ID_MPEG1VIDEO)
1054         avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1055     else
1056         avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1057     return 0;
1058 }
1059
1060 static int mpeg_decode_update_thread_context(AVCodecContext *avctx, const AVCodecContext *avctx_from)
1061 {
1062     Mpeg1Context *ctx = avctx->priv_data, *ctx_from = avctx_from->priv_data;
1063     MpegEncContext *s = &ctx->mpeg_enc_ctx, *s1 = &ctx_from->mpeg_enc_ctx;
1064     int err;
1065
1066     if (avctx == avctx_from || !ctx_from->mpeg_enc_ctx_allocated || !s1->context_initialized)
1067         return 0;
1068
1069     err = ff_mpeg_update_thread_context(avctx, avctx_from);
1070     if (err) return err;
1071
1072     if (!ctx->mpeg_enc_ctx_allocated)
1073         memcpy(s + 1, s1 + 1, sizeof(Mpeg1Context) - sizeof(MpegEncContext));
1074
1075     if (!(s->pict_type == AV_PICTURE_TYPE_B || s->low_delay))
1076         s->picture_number++;
1077
1078     return 0;
1079 }
1080
1081 static void quant_matrix_rebuild(uint16_t *matrix, const uint8_t *old_perm,
1082                                  const uint8_t *new_perm)
1083 {
1084     uint16_t temp_matrix[64];
1085     int i;
1086
1087     memcpy(temp_matrix, matrix, 64 * sizeof(uint16_t));
1088
1089     for (i = 0; i < 64; i++) {
1090         matrix[new_perm[i]] = temp_matrix[old_perm[i]];
1091     }
1092 }
1093
1094 static const enum AVPixelFormat mpeg1_hwaccel_pixfmt_list_420[] = {
1095 #if CONFIG_MPEG_XVMC_DECODER
1096     AV_PIX_FMT_XVMC_MPEG2_IDCT,
1097     AV_PIX_FMT_XVMC_MPEG2_MC,
1098 #endif
1099 #if CONFIG_MPEG1_VDPAU_HWACCEL
1100     AV_PIX_FMT_VDPAU_MPEG1,
1101 #endif
1102     AV_PIX_FMT_YUV420P,
1103     AV_PIX_FMT_NONE
1104 };
1105
1106 static const enum AVPixelFormat mpeg2_hwaccel_pixfmt_list_420[] = {
1107 #if CONFIG_MPEG_XVMC_DECODER
1108     AV_PIX_FMT_XVMC_MPEG2_IDCT,
1109     AV_PIX_FMT_XVMC_MPEG2_MC,
1110 #endif
1111 #if CONFIG_MPEG2_VDPAU_HWACCEL
1112     AV_PIX_FMT_VDPAU_MPEG2,
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 ||
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;
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 (s2->pict_type != AV_PICTURE_TYPE_B || avctx->skip_frame <= AVDISCARD_DEFAULT) {
2131                 if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE)) {
2132                     int i;
2133                     av_assert0(avctx->thread_count > 1);
2134
2135                     avctx->execute(avctx, slice_decode_thread,  &s2->thread_context[0], NULL, s->slice_count, sizeof(void*));
2136                     for (i = 0; i < s->slice_count; i++)
2137                         s2->er.error_count += s2->thread_context[i]->er.error_count;
2138                 }
2139
2140                 if ((CONFIG_MPEG_VDPAU_DECODER || CONFIG_MPEG1_VDPAU_DECODER)
2141                     && uses_vdpau(avctx))
2142                     ff_vdpau_mpeg_picture_complete(s2, buf, buf_size, s->slice_count);
2143
2144                 ret = slice_end(avctx, picture);
2145                 if (ret < 0)
2146                     return ret;
2147                 else if (ret) {
2148                     if (s2->last_picture_ptr || s2->low_delay) //FIXME merge with the stuff in mpeg_decode_slice
2149                         *got_output = 1;
2150                 }
2151             }
2152             s2->pict_type = 0;
2153             return FFMAX(0, buf_ptr - buf - s2->parse_context.last_index);
2154         }
2155
2156         input_size = buf_end - buf_ptr;
2157
2158         if (avctx->debug & FF_DEBUG_STARTCODE) {
2159             av_log(avctx, AV_LOG_DEBUG, "%3X at %td left %d\n", start_code, buf_ptr-buf, input_size);
2160         }
2161
2162         /* prepare data for next start code */
2163         switch (start_code) {
2164         case SEQ_START_CODE:
2165             if (last_code == 0) {
2166                 mpeg1_decode_sequence(avctx, buf_ptr, input_size);
2167                 if(buf != avctx->extradata)
2168                     s->sync=1;
2169             } else {
2170                 av_log(avctx, AV_LOG_ERROR, "ignoring SEQ_START_CODE after %X\n", last_code);
2171                 if (avctx->err_recognition & AV_EF_EXPLODE)
2172                     return AVERROR_INVALIDDATA;
2173             }
2174             break;
2175
2176         case PICTURE_START_CODE:
2177             if (picture_start_code_seen && s2->picture_structure == PICT_FRAME) {
2178                /* If it's a frame picture, there can't be more than one picture header.
2179                   Yet, it does happen and we need to handle it. */
2180                av_log(avctx, AV_LOG_WARNING, "ignoring extra picture following a frame-picture\n");
2181                break;
2182             }
2183             picture_start_code_seen = 1;
2184
2185             if (s2->width <= 0 || s2->height <= 0) {
2186                 av_log(avctx, AV_LOG_ERROR, "Invalid frame dimensions %dx%d.\n",
2187                        s2->width, s2->height);
2188                 return AVERROR_INVALIDDATA;
2189             }
2190
2191             if(s->tmpgexs){
2192                 s2->intra_dc_precision= 3;
2193                 s2->intra_matrix[0]= 1;
2194             }
2195             if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE) && s->slice_count) {
2196                 int i;
2197
2198                 avctx->execute(avctx, slice_decode_thread,
2199                                s2->thread_context, NULL,
2200                                s->slice_count, sizeof(void*));
2201                 for (i = 0; i < s->slice_count; i++)
2202                     s2->er.error_count += s2->thread_context[i]->er.error_count;
2203                 s->slice_count = 0;
2204             }
2205             if (last_code == 0 || last_code == SLICE_MIN_START_CODE) {
2206                 ret = mpeg_decode_postinit(avctx);
2207                 if (ret < 0) {
2208                     av_log(avctx, AV_LOG_ERROR, "mpeg_decode_postinit() failure\n");
2209                     return ret;
2210                 }
2211
2212                 /* we have a complete image: we try to decompress it */
2213                 if (mpeg1_decode_picture(avctx, buf_ptr, input_size) < 0)
2214                     s2->pict_type = 0;
2215                 s2->first_slice = 1;
2216                 last_code = PICTURE_START_CODE;
2217             } else {
2218                 av_log(avctx, AV_LOG_ERROR, "ignoring pic after %X\n", last_code);
2219                 if (avctx->err_recognition & AV_EF_EXPLODE)
2220                     return AVERROR_INVALIDDATA;
2221             }
2222             break;
2223         case EXT_START_CODE:
2224             init_get_bits(&s2->gb, buf_ptr, input_size*8);
2225
2226             switch (get_bits(&s2->gb, 4)) {
2227             case 0x1:
2228                 if (last_code == 0) {
2229                 mpeg_decode_sequence_extension(s);
2230                 } else {
2231                     av_log(avctx, AV_LOG_ERROR, "ignoring seq ext after %X\n", last_code);
2232                     if (avctx->err_recognition & AV_EF_EXPLODE)
2233                         return AVERROR_INVALIDDATA;
2234                 }
2235                 break;
2236             case 0x2:
2237                 mpeg_decode_sequence_display_extension(s);
2238                 break;
2239             case 0x3:
2240                 mpeg_decode_quant_matrix_extension(s2);
2241                 break;
2242             case 0x7:
2243                 mpeg_decode_picture_display_extension(s);
2244                 break;
2245             case 0x8:
2246                 if (last_code == PICTURE_START_CODE) {
2247                     mpeg_decode_picture_coding_extension(s);
2248                 } else {
2249                     av_log(avctx, AV_LOG_ERROR, "ignoring pic cod ext after %X\n", last_code);
2250                     if (avctx->err_recognition & AV_EF_EXPLODE)
2251                         return AVERROR_INVALIDDATA;
2252                 }
2253                 break;
2254             }
2255             break;
2256         case USER_START_CODE:
2257             mpeg_decode_user_data(avctx, buf_ptr, input_size);
2258             break;
2259         case GOP_START_CODE:
2260             if (last_code == 0) {
2261                 s2->first_field=0;
2262                 mpeg_decode_gop(avctx, buf_ptr, input_size);
2263                 s->sync=1;
2264             } else {
2265                 av_log(avctx, AV_LOG_ERROR, "ignoring GOP_START_CODE after %X\n", last_code);
2266                 if (avctx->err_recognition & AV_EF_EXPLODE)
2267                     return AVERROR_INVALIDDATA;
2268             }
2269             break;
2270         default:
2271             if (start_code >= SLICE_MIN_START_CODE &&
2272                 start_code <= SLICE_MAX_START_CODE && last_code == PICTURE_START_CODE) {
2273
2274                 if (s2->progressive_sequence && !s2->progressive_frame) {
2275                     s2->progressive_frame = 1;
2276                     av_log(s2->avctx, AV_LOG_ERROR, "interlaced frame in progressive sequence, ignoring\n");
2277                 }
2278
2279                 if (s2->picture_structure == 0 || (s2->progressive_frame && s2->picture_structure != PICT_FRAME)) {
2280                     av_log(s2->avctx, AV_LOG_ERROR, "picture_structure %d invalid, ignoring\n", s2->picture_structure);
2281                     s2->picture_structure = PICT_FRAME;
2282                 }
2283
2284                 if (s2->progressive_sequence && !s2->frame_pred_frame_dct) {
2285                     av_log(s2->avctx, AV_LOG_WARNING, "invalid frame_pred_frame_dct\n");
2286                 }
2287
2288                 if (s2->picture_structure == PICT_FRAME) {
2289                     s2->first_field = 0;
2290                     s2->v_edge_pos  = 16 * s2->mb_height;
2291                 } else {
2292                     s2->first_field ^= 1;
2293                     s2->v_edge_pos   = 8 * s2->mb_height;
2294                     memset(s2->mbskip_table, 0, s2->mb_stride * s2->mb_height);
2295                 }
2296             }
2297             if (start_code >= SLICE_MIN_START_CODE &&
2298                 start_code <= SLICE_MAX_START_CODE && last_code != 0) {
2299                 const int field_pic = s2->picture_structure != PICT_FRAME;
2300                 int mb_y = start_code - SLICE_MIN_START_CODE;
2301                 last_code = SLICE_MIN_START_CODE;
2302                 if(s2->codec_id != AV_CODEC_ID_MPEG1VIDEO && s2->mb_height > 2800/16)
2303                     mb_y += (*buf_ptr&0xE0)<<2;
2304
2305                 mb_y <<= field_pic;
2306                 if (s2->picture_structure == PICT_BOTTOM_FIELD)
2307                     mb_y++;
2308
2309                 if (mb_y >= s2->mb_height) {
2310                     av_log(s2->avctx, AV_LOG_ERROR, "slice below image (%d >= %d)\n", mb_y, s2->mb_height);
2311                     return -1;
2312                 }
2313
2314                 if (s2->last_picture_ptr == NULL) {
2315                 /* Skip B-frames if we do not have reference frames and gop is not closed */
2316                     if (s2->pict_type == AV_PICTURE_TYPE_B) {
2317                         if (!s2->closed_gop)
2318                             break;
2319                     }
2320                 }
2321                 if (s2->pict_type == AV_PICTURE_TYPE_I || (s2->flags2 & CODEC_FLAG2_SHOW_ALL))
2322                     s->sync=1;
2323                 if (s2->next_picture_ptr == NULL) {
2324                 /* Skip P-frames if we do not have a reference frame or we have an invalid header. */
2325                     if (s2->pict_type == AV_PICTURE_TYPE_P && !s->sync) break;
2326                 }
2327                 if ((avctx->skip_frame >= AVDISCARD_NONREF && s2->pict_type == AV_PICTURE_TYPE_B) ||
2328                     (avctx->skip_frame >= AVDISCARD_NONKEY && s2->pict_type != AV_PICTURE_TYPE_I) ||
2329                      avctx->skip_frame >= AVDISCARD_ALL)
2330                     break;
2331
2332                 if (!s->mpeg_enc_ctx_allocated)
2333                     break;
2334
2335                 if (s2->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2336                     if (mb_y < avctx->skip_top || mb_y >= s2->mb_height - avctx->skip_bottom)
2337                         break;
2338                 }
2339
2340                 if (!s2->pict_type) {
2341                     av_log(avctx, AV_LOG_ERROR, "Missing picture start code\n");
2342                     if (avctx->err_recognition & AV_EF_EXPLODE)
2343                         return AVERROR_INVALIDDATA;
2344                     break;
2345                 }
2346
2347                 if (s2->first_slice) {
2348                     s2->first_slice = 0;
2349                     if (mpeg_field_start(s2, buf, buf_size) < 0)
2350                         return -1;
2351                 }
2352                 if (!s2->current_picture_ptr) {
2353                     av_log(avctx, AV_LOG_ERROR, "current_picture not initialized\n");
2354                     return AVERROR_INVALIDDATA;
2355                 }
2356
2357                 if (uses_vdpau(avctx)) {
2358                     s->slice_count++;
2359                     break;
2360                 }
2361
2362                 if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE)) {
2363                     int threshold = (s2->mb_height * s->slice_count +
2364                                      s2->slice_context_count / 2) /
2365                                     s2->slice_context_count;
2366                     av_assert0(avctx->thread_count > 1);
2367                     if (threshold <= mb_y) {
2368                         MpegEncContext *thread_context = s2->thread_context[s->slice_count];
2369
2370                         thread_context->start_mb_y = mb_y;
2371                         thread_context->end_mb_y   = s2->mb_height;
2372                         if (s->slice_count) {
2373                             s2->thread_context[s->slice_count-1]->end_mb_y = mb_y;
2374                             ret = ff_update_duplicate_context(thread_context,
2375                                                               s2);
2376                             if (ret < 0)
2377                                 return ret;
2378                         }
2379                         init_get_bits(&thread_context->gb, buf_ptr, input_size*8);
2380                         s->slice_count++;
2381                     }
2382                     buf_ptr += 2; // FIXME add minimum number of bytes per slice
2383                 } else {
2384                     ret = mpeg_decode_slice(s2, mb_y, &buf_ptr, input_size);
2385                     emms_c();
2386
2387                     if (ret < 0) {
2388                         if (avctx->err_recognition & AV_EF_EXPLODE)
2389                             return ret;
2390                         if (s2->resync_mb_x >= 0 && s2->resync_mb_y >= 0)
2391                             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);
2392                     } else {
2393                         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);
2394                     }
2395                 }
2396             }
2397             break;
2398         }
2399     }
2400 }
2401
2402 static int mpeg_decode_frame(AVCodecContext *avctx,
2403                              void *data, int *got_output,
2404                              AVPacket *avpkt)
2405 {
2406     const uint8_t *buf = avpkt->data;
2407     int ret;
2408     int buf_size = avpkt->size;
2409     Mpeg1Context *s = avctx->priv_data;
2410     AVFrame *picture = data;
2411     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2412     av_dlog(avctx, "fill_buffer\n");
2413
2414     if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {
2415         /* special case for last picture */
2416         if (s2->low_delay == 0 && s2->next_picture_ptr) {
2417             int ret = av_frame_ref(picture, &s2->next_picture_ptr->f);
2418             if (ret < 0)
2419                 return ret;
2420
2421             s2->next_picture_ptr = NULL;
2422
2423             *got_output = 1;
2424         }
2425         return buf_size;
2426     }
2427
2428     if (s2->flags & CODEC_FLAG_TRUNCATED) {
2429         int next = ff_mpeg1_find_frame_end(&s2->parse_context, buf, buf_size, NULL);
2430
2431         if (ff_combine_frame(&s2->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0)
2432             return buf_size;
2433     }
2434
2435     s2->codec_tag = avpriv_toupper4(avctx->codec_tag);
2436     if (s->mpeg_enc_ctx_allocated == 0 && (   s2->codec_tag == AV_RL32("VCR2")
2437                                            || s2->codec_tag == AV_RL32("BW10")
2438                                           ))
2439         vcr2_init_sequence(avctx);
2440
2441     s->slice_count = 0;
2442
2443     if (avctx->extradata && !s->extradata_decoded) {
2444         ret = decode_chunks(avctx, picture, got_output, avctx->extradata, avctx->extradata_size);
2445         if(*got_output) {
2446             av_log(avctx, AV_LOG_ERROR, "picture in extradata\n");
2447             *got_output = 0;
2448         }
2449         s->extradata_decoded = 1;
2450         if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE)) {
2451             s2->current_picture_ptr = NULL;
2452             return ret;
2453         }
2454     }
2455
2456     ret = decode_chunks(avctx, picture, got_output, buf, buf_size);
2457     if (ret<0 || *got_output)
2458         s2->current_picture_ptr = NULL;
2459
2460     return ret;
2461 }
2462
2463
2464 static void flush(AVCodecContext *avctx)
2465 {
2466     Mpeg1Context *s = avctx->priv_data;
2467
2468     s->sync=0;
2469
2470     ff_mpeg_flush(avctx);
2471 }
2472
2473 static int mpeg_decode_end(AVCodecContext *avctx)
2474 {
2475     Mpeg1Context *s = avctx->priv_data;
2476
2477     if (s->mpeg_enc_ctx_allocated)
2478         ff_MPV_common_end(&s->mpeg_enc_ctx);
2479     return 0;
2480 }
2481
2482 static const AVProfile mpeg2_video_profiles[] = {
2483     { FF_PROFILE_MPEG2_422,          "4:2:2"              },
2484     { FF_PROFILE_MPEG2_HIGH,         "High"               },
2485     { FF_PROFILE_MPEG2_SS,           "Spatially Scalable" },
2486     { FF_PROFILE_MPEG2_SNR_SCALABLE, "SNR Scalable"       },
2487     { FF_PROFILE_MPEG2_MAIN,         "Main"               },
2488     { FF_PROFILE_MPEG2_SIMPLE,       "Simple"             },
2489     { FF_PROFILE_RESERVED,           "Reserved"           },
2490     { FF_PROFILE_RESERVED,           "Reserved"           },
2491     { FF_PROFILE_UNKNOWN },
2492 };
2493
2494
2495 AVCodec ff_mpeg1video_decoder = {
2496     .name                  = "mpeg1video",
2497     .type                  = AVMEDIA_TYPE_VIDEO,
2498     .id                    = AV_CODEC_ID_MPEG1VIDEO,
2499     .priv_data_size        = sizeof(Mpeg1Context),
2500     .init                  = mpeg_decode_init,
2501     .close                 = mpeg_decode_end,
2502     .decode                = mpeg_decode_frame,
2503     .capabilities          = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2504                              CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2505                              CODEC_CAP_SLICE_THREADS,
2506     .flush                 = flush,
2507     .max_lowres            = 3,
2508     .long_name             = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
2509     .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg_decode_update_thread_context)
2510 };
2511
2512 AVCodec ff_mpeg2video_decoder = {
2513     .name           = "mpeg2video",
2514     .type           = AVMEDIA_TYPE_VIDEO,
2515     .id             = AV_CODEC_ID_MPEG2VIDEO,
2516     .priv_data_size = sizeof(Mpeg1Context),
2517     .init           = mpeg_decode_init,
2518     .close          = mpeg_decode_end,
2519     .decode         = mpeg_decode_frame,
2520     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2521                       CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2522                       CODEC_CAP_SLICE_THREADS,
2523     .flush          = flush,
2524     .max_lowres     = 3,
2525     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
2526     .profiles       = NULL_IF_CONFIG_SMALL(mpeg2_video_profiles),
2527 };
2528
2529 //legacy decoder
2530 AVCodec ff_mpegvideo_decoder = {
2531     .name           = "mpegvideo",
2532     .type           = AVMEDIA_TYPE_VIDEO,
2533     .id             = AV_CODEC_ID_MPEG2VIDEO,
2534     .priv_data_size = sizeof(Mpeg1Context),
2535     .init           = mpeg_decode_init,
2536     .close          = mpeg_decode_end,
2537     .decode         = mpeg_decode_frame,
2538     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
2539     .flush          = flush,
2540     .max_lowres     = 3,
2541     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
2542 };
2543
2544 #if CONFIG_MPEG_XVMC_DECODER
2545 static av_cold int mpeg_mc_decode_init(AVCodecContext *avctx)
2546 {
2547     if (avctx->active_thread_type & FF_THREAD_SLICE)
2548         return -1;
2549     if (!(avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
2550         return -1;
2551     if (!(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD)) {
2552         av_dlog(avctx, "mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");
2553     }
2554     mpeg_decode_init(avctx);
2555
2556     avctx->pix_fmt           = AV_PIX_FMT_XVMC_MPEG2_IDCT;
2557     avctx->xvmc_acceleration = 2; // 2 - the blocks are packed!
2558
2559     return 0;
2560 }
2561
2562 AVCodec ff_mpeg_xvmc_decoder = {
2563     .name           = "mpegvideo_xvmc",
2564     .type           = AVMEDIA_TYPE_VIDEO,
2565     .id             = AV_CODEC_ID_MPEG2VIDEO_XVMC,
2566     .priv_data_size = sizeof(Mpeg1Context),
2567     .init           = mpeg_mc_decode_init,
2568     .close          = mpeg_decode_end,
2569     .decode         = mpeg_decode_frame,
2570     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2571                       CODEC_CAP_TRUNCATED| CODEC_CAP_HWACCEL | CODEC_CAP_DELAY,
2572     .flush          = flush,
2573     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1/2 video XvMC (X-Video Motion Compensation)"),
2574 };
2575
2576 #endif
2577
2578 #if CONFIG_MPEG_VDPAU_DECODER
2579 AVCodec ff_mpeg_vdpau_decoder = {
2580     .name           = "mpegvideo_vdpau",
2581     .type           = AVMEDIA_TYPE_VIDEO,
2582     .id             = AV_CODEC_ID_MPEG2VIDEO,
2583     .priv_data_size = sizeof(Mpeg1Context),
2584     .init           = mpeg_decode_init,
2585     .close          = mpeg_decode_end,
2586     .decode         = mpeg_decode_frame,
2587     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED |
2588                       CODEC_CAP_HWACCEL_VDPAU | CODEC_CAP_DELAY,
2589     .flush          = flush,
2590     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1/2 video (VDPAU acceleration)"),
2591 };
2592 #endif
2593
2594 #if CONFIG_MPEG1_VDPAU_DECODER
2595 AVCodec ff_mpeg1_vdpau_decoder = {
2596     .name           = "mpeg1video_vdpau",
2597     .type           = AVMEDIA_TYPE_VIDEO,
2598     .id             = AV_CODEC_ID_MPEG1VIDEO,
2599     .priv_data_size = sizeof(Mpeg1Context),
2600     .init           = mpeg_decode_init,
2601     .close          = mpeg_decode_end,
2602     .decode         = mpeg_decode_frame,
2603     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED |
2604                       CODEC_CAP_HWACCEL_VDPAU | CODEC_CAP_DELAY,
2605     .flush          = flush,
2606     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1 video (VDPAU acceleration)"),
2607 };
2608 #endif