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