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