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