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