44a1d987cfd3026e2338ed4d53537d554a67d202
[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 (ff_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 inline int ff_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 static inline int mpeg1_decode_block_inter(MpegEncContext *s,
682                                DCTELEM *block,
683                                int n)
684 {
685     int level, i, j, run;
686     RLTable *rl = &ff_rl_mpeg1;
687     uint8_t * const scantable= s->intra_scantable.permutated;
688     const uint16_t *quant_matrix= s->inter_matrix;
689     const int qscale= s->qscale;
690
691     {
692         OPEN_READER(re, &s->gb);
693         i = -1;
694         // special case for first coefficient, no need to add second VLC table
695         UPDATE_CACHE(re, &s->gb);
696         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
697             level= (3*qscale*quant_matrix[0])>>5;
698             level= (level-1)|1;
699             if(GET_CACHE(re, &s->gb)&0x40000000)
700                 level= -level;
701             block[0] = level;
702             i++;
703             SKIP_BITS(re, &s->gb, 2);
704             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
705                 goto end;
706         }
707 #if MIN_CACHE_BITS < 19
708         UPDATE_CACHE(re, &s->gb);
709 #endif
710         /* now quantify & encode AC coefficients */
711         for(;;) {
712             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
713
714             if(level != 0) {
715                 i += run;
716                 j = scantable[i];
717                 level= ((level*2+1)*qscale*quant_matrix[j])>>5;
718                 level= (level-1)|1;
719                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
720                 SKIP_BITS(re, &s->gb, 1);
721             } else {
722                 /* escape */
723                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
724                 UPDATE_CACHE(re, &s->gb);
725                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
726                 if (level == -128) {
727                     level = SHOW_UBITS(re, &s->gb, 8) - 256; SKIP_BITS(re, &s->gb, 8);
728                 } else if (level == 0) {
729                     level = SHOW_UBITS(re, &s->gb, 8)      ; SKIP_BITS(re, &s->gb, 8);
730                 }
731                 i += run;
732                 j = scantable[i];
733                 if(level<0){
734                     level= -level;
735                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
736                     level= (level-1)|1;
737                     level= -level;
738                 }else{
739                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
740                     level= (level-1)|1;
741                 }
742             }
743             if (i > 63){
744                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
745                 return -1;
746             }
747
748             block[j] = level;
749 #if MIN_CACHE_BITS < 19
750             UPDATE_CACHE(re, &s->gb);
751 #endif
752             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
753                 break;
754 #if MIN_CACHE_BITS >= 19
755             UPDATE_CACHE(re, &s->gb);
756 #endif
757         }
758 end:
759         LAST_SKIP_BITS(re, &s->gb, 2);
760         CLOSE_READER(re, &s->gb);
761     }
762     s->block_last_index[n] = i;
763     return 0;
764 }
765
766 static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s, DCTELEM *block, int n)
767 {
768     int level, i, j, run;
769     RLTable *rl = &ff_rl_mpeg1;
770     uint8_t * const scantable= s->intra_scantable.permutated;
771     const int qscale= s->qscale;
772
773     {
774         OPEN_READER(re, &s->gb);
775         i = -1;
776         // special case for first coefficient, no need to add second VLC table
777         UPDATE_CACHE(re, &s->gb);
778         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
779             level= (3*qscale)>>1;
780             level= (level-1)|1;
781             if(GET_CACHE(re, &s->gb)&0x40000000)
782                 level= -level;
783             block[0] = level;
784             i++;
785             SKIP_BITS(re, &s->gb, 2);
786             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
787                 goto end;
788         }
789 #if MIN_CACHE_BITS < 19
790         UPDATE_CACHE(re, &s->gb);
791 #endif
792
793         /* now quantify & encode AC coefficients */
794         for(;;) {
795             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
796
797             if(level != 0) {
798                 i += run;
799                 j = scantable[i];
800                 level= ((level*2+1)*qscale)>>1;
801                 level= (level-1)|1;
802                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
803                 SKIP_BITS(re, &s->gb, 1);
804             } else {
805                 /* escape */
806                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
807                 UPDATE_CACHE(re, &s->gb);
808                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
809                 if (level == -128) {
810                     level = SHOW_UBITS(re, &s->gb, 8) - 256; SKIP_BITS(re, &s->gb, 8);
811                 } else if (level == 0) {
812                     level = SHOW_UBITS(re, &s->gb, 8)      ; SKIP_BITS(re, &s->gb, 8);
813                 }
814                 i += run;
815                 j = scantable[i];
816                 if(level<0){
817                     level= -level;
818                     level= ((level*2+1)*qscale)>>1;
819                     level= (level-1)|1;
820                     level= -level;
821                 }else{
822                     level= ((level*2+1)*qscale)>>1;
823                     level= (level-1)|1;
824                 }
825             }
826
827             block[j] = level;
828 #if MIN_CACHE_BITS < 19
829             UPDATE_CACHE(re, &s->gb);
830 #endif
831             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
832                 break;
833 #if MIN_CACHE_BITS >= 19
834             UPDATE_CACHE(re, &s->gb);
835 #endif
836         }
837 end:
838         LAST_SKIP_BITS(re, &s->gb, 2);
839         CLOSE_READER(re, &s->gb);
840     }
841     s->block_last_index[n] = i;
842     return 0;
843 }
844
845
846 static inline int mpeg2_decode_block_non_intra(MpegEncContext *s,
847                                DCTELEM *block,
848                                int n)
849 {
850     int level, i, j, run;
851     RLTable *rl = &ff_rl_mpeg1;
852     uint8_t * const scantable= s->intra_scantable.permutated;
853     const uint16_t *quant_matrix;
854     const int qscale= s->qscale;
855     int mismatch;
856
857     mismatch = 1;
858
859     {
860         OPEN_READER(re, &s->gb);
861         i = -1;
862         if (n < 4)
863             quant_matrix = s->inter_matrix;
864         else
865             quant_matrix = s->chroma_inter_matrix;
866
867         // special case for first coefficient, no need to add second VLC table
868         UPDATE_CACHE(re, &s->gb);
869         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
870             level= (3*qscale*quant_matrix[0])>>5;
871             if(GET_CACHE(re, &s->gb)&0x40000000)
872                 level= -level;
873             block[0] = level;
874             mismatch ^= level;
875             i++;
876             SKIP_BITS(re, &s->gb, 2);
877             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
878                 goto end;
879         }
880 #if MIN_CACHE_BITS < 19
881         UPDATE_CACHE(re, &s->gb);
882 #endif
883
884         /* now quantify & encode AC coefficients */
885         for(;;) {
886             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
887
888             if(level != 0) {
889                 i += run;
890                 j = scantable[i];
891                 level= ((level*2+1)*qscale*quant_matrix[j])>>5;
892                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
893                 SKIP_BITS(re, &s->gb, 1);
894             } else {
895                 /* escape */
896                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
897                 UPDATE_CACHE(re, &s->gb);
898                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
899
900                 i += run;
901                 j = scantable[i];
902                 if(level<0){
903                     level= ((-level*2+1)*qscale*quant_matrix[j])>>5;
904                     level= -level;
905                 }else{
906                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
907                 }
908             }
909             if (i > 63){
910                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
911                 return -1;
912             }
913
914             mismatch ^= level;
915             block[j] = level;
916 #if MIN_CACHE_BITS < 19
917             UPDATE_CACHE(re, &s->gb);
918 #endif
919             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
920                 break;
921 #if MIN_CACHE_BITS >= 19
922             UPDATE_CACHE(re, &s->gb);
923 #endif
924         }
925 end:
926         LAST_SKIP_BITS(re, &s->gb, 2);
927         CLOSE_READER(re, &s->gb);
928     }
929     block[63] ^= (mismatch & 1);
930
931     s->block_last_index[n] = i;
932     return 0;
933 }
934
935 static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s,
936                                DCTELEM *block,
937                                int n)
938 {
939     int level, i, j, run;
940     RLTable *rl = &ff_rl_mpeg1;
941     uint8_t * const scantable= s->intra_scantable.permutated;
942     const int qscale= s->qscale;
943     OPEN_READER(re, &s->gb);
944     i = -1;
945
946     // special case for first coefficient, no need to add second VLC table
947     UPDATE_CACHE(re, &s->gb);
948     if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
949         level= (3*qscale)>>1;
950         if(GET_CACHE(re, &s->gb)&0x40000000)
951             level= -level;
952         block[0] = level;
953         i++;
954         SKIP_BITS(re, &s->gb, 2);
955         if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
956             goto end;
957     }
958 #if MIN_CACHE_BITS < 19
959     UPDATE_CACHE(re, &s->gb);
960 #endif
961
962     /* now quantify & encode AC coefficients */
963     for(;;) {
964         GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
965
966         if(level != 0) {
967             i += run;
968             j = scantable[i];
969             level= ((level*2+1)*qscale)>>1;
970             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
971             SKIP_BITS(re, &s->gb, 1);
972         } else {
973             /* escape */
974             run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
975             UPDATE_CACHE(re, &s->gb);
976             level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
977
978             i += run;
979             j = scantable[i];
980             if(level<0){
981                 level= ((-level*2+1)*qscale)>>1;
982                 level= -level;
983             }else{
984                 level= ((level*2+1)*qscale)>>1;
985             }
986         }
987
988         block[j] = level;
989 #if MIN_CACHE_BITS < 19
990         UPDATE_CACHE(re, &s->gb);
991 #endif
992         if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
993             break;
994 #if MIN_CACHE_BITS >=19
995         UPDATE_CACHE(re, &s->gb);
996 #endif
997     }
998 end:
999     LAST_SKIP_BITS(re, &s->gb, 2);
1000     CLOSE_READER(re, &s->gb);
1001     s->block_last_index[n] = i;
1002     return 0;
1003 }
1004
1005
1006 static inline int mpeg2_decode_block_intra(MpegEncContext *s,
1007                                DCTELEM *block,
1008                                int n)
1009 {
1010     int level, dc, diff, i, j, run;
1011     int component;
1012     RLTable *rl;
1013     uint8_t * const scantable= s->intra_scantable.permutated;
1014     const uint16_t *quant_matrix;
1015     const int qscale= s->qscale;
1016     int mismatch;
1017
1018     /* DC coefficient */
1019     if (n < 4){
1020         quant_matrix = s->intra_matrix;
1021         component = 0;
1022     }else{
1023         quant_matrix = s->chroma_intra_matrix;
1024         component = (n&1) + 1;
1025     }
1026     diff = decode_dc(&s->gb, component);
1027     if (diff >= 0xffff)
1028         return -1;
1029     dc = s->last_dc[component];
1030     dc += diff;
1031     s->last_dc[component] = dc;
1032     block[0] = dc << (3 - s->intra_dc_precision);
1033     dprintf(s->avctx, "dc=%d\n", block[0]);
1034     mismatch = block[0] ^ 1;
1035     i = 0;
1036     if (s->intra_vlc_format)
1037         rl = &ff_rl_mpeg2;
1038     else
1039         rl = &ff_rl_mpeg1;
1040
1041     {
1042         OPEN_READER(re, &s->gb);
1043         /* now quantify & encode AC coefficients */
1044         for(;;) {
1045             UPDATE_CACHE(re, &s->gb);
1046             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1047
1048             if(level == 127){
1049                 break;
1050             } else if(level != 0) {
1051                 i += run;
1052                 j = scantable[i];
1053                 level= (level*qscale*quant_matrix[j])>>4;
1054                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1055                 LAST_SKIP_BITS(re, &s->gb, 1);
1056             } else {
1057                 /* escape */
1058                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1059                 UPDATE_CACHE(re, &s->gb);
1060                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1061                 i += run;
1062                 j = scantable[i];
1063                 if(level<0){
1064                     level= (-level*qscale*quant_matrix[j])>>4;
1065                     level= -level;
1066                 }else{
1067                     level= (level*qscale*quant_matrix[j])>>4;
1068                 }
1069             }
1070             if (i > 63){
1071                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1072                 return -1;
1073             }
1074
1075             mismatch^= level;
1076             block[j] = level;
1077         }
1078         CLOSE_READER(re, &s->gb);
1079     }
1080     block[63]^= mismatch&1;
1081
1082     s->block_last_index[n] = i;
1083     return 0;
1084 }
1085
1086 static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s,
1087                                DCTELEM *block,
1088                                int n)
1089 {
1090     int level, dc, diff, j, run;
1091     int component;
1092     RLTable *rl;
1093     uint8_t * scantable= s->intra_scantable.permutated;
1094     const uint16_t *quant_matrix;
1095     const int qscale= s->qscale;
1096
1097     /* DC coefficient */
1098     if (n < 4){
1099         quant_matrix = s->intra_matrix;
1100         component = 0;
1101     }else{
1102         quant_matrix = s->chroma_intra_matrix;
1103         component = (n&1) + 1;
1104     }
1105     diff = decode_dc(&s->gb, component);
1106     if (diff >= 0xffff)
1107         return -1;
1108     dc = s->last_dc[component];
1109     dc += diff;
1110     s->last_dc[component] = dc;
1111     block[0] = dc << (3 - s->intra_dc_precision);
1112     if (s->intra_vlc_format)
1113         rl = &ff_rl_mpeg2;
1114     else
1115         rl = &ff_rl_mpeg1;
1116
1117     {
1118         OPEN_READER(re, &s->gb);
1119         /* now quantify & encode AC coefficients */
1120         for(;;) {
1121             UPDATE_CACHE(re, &s->gb);
1122             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1123
1124             if(level == 127){
1125                 break;
1126             } else if(level != 0) {
1127                 scantable += run;
1128                 j = *scantable;
1129                 level= (level*qscale*quant_matrix[j])>>4;
1130                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1131                 LAST_SKIP_BITS(re, &s->gb, 1);
1132             } else {
1133                 /* escape */
1134                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1135                 UPDATE_CACHE(re, &s->gb);
1136                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1137                 scantable += run;
1138                 j = *scantable;
1139                 if(level<0){
1140                     level= (-level*qscale*quant_matrix[j])>>4;
1141                     level= -level;
1142                 }else{
1143                     level= (level*qscale*quant_matrix[j])>>4;
1144                 }
1145             }
1146
1147             block[j] = level;
1148         }
1149         CLOSE_READER(re, &s->gb);
1150     }
1151
1152     s->block_last_index[n] = scantable - s->intra_scantable.permutated;
1153     return 0;
1154 }
1155
1156 typedef struct Mpeg1Context {
1157     MpegEncContext mpeg_enc_ctx;
1158     int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1159     int repeat_field; /* true if we must repeat the field */
1160     AVPanScan pan_scan; /** some temporary storage for the panscan */
1161     int slice_count;
1162     int swap_uv;//indicate VCR2
1163     int save_aspect_info;
1164     int save_width, save_height, save_progressive_seq;
1165     AVRational frame_rate_ext;       ///< MPEG-2 specific framerate modificator
1166
1167 } Mpeg1Context;
1168
1169 static av_cold int mpeg_decode_init(AVCodecContext *avctx)
1170 {
1171     Mpeg1Context *s = avctx->priv_data;
1172     MpegEncContext *s2 = &s->mpeg_enc_ctx;
1173     int i;
1174
1175     /* we need some permutation to store matrices,
1176      * until MPV_common_init() sets the real permutation. */
1177     for(i=0;i<64;i++)
1178        s2->dsp.idct_permutation[i]=i;
1179
1180     MPV_decode_defaults(s2);
1181
1182     s->mpeg_enc_ctx.avctx= avctx;
1183     s->mpeg_enc_ctx.flags= avctx->flags;
1184     s->mpeg_enc_ctx.flags2= avctx->flags2;
1185     ff_mpeg12_common_init(&s->mpeg_enc_ctx);
1186     ff_mpeg12_init_vlcs();
1187
1188     s->mpeg_enc_ctx_allocated = 0;
1189     s->mpeg_enc_ctx.picture_number = 0;
1190     s->repeat_field = 0;
1191     s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1192     avctx->color_range= AVCOL_RANGE_MPEG;
1193     if (avctx->codec->id == CODEC_ID_MPEG1VIDEO)
1194         avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1195     else
1196         avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1197     return 0;
1198 }
1199
1200 static void quant_matrix_rebuild(uint16_t *matrix, const uint8_t *old_perm,
1201                                      const uint8_t *new_perm){
1202     uint16_t temp_matrix[64];
1203     int i;
1204
1205     memcpy(temp_matrix,matrix,64*sizeof(uint16_t));
1206
1207     for(i=0;i<64;i++){
1208         matrix[new_perm[i]] = temp_matrix[old_perm[i]];
1209     }
1210 }
1211
1212 static enum PixelFormat mpeg_get_pixelformat(AVCodecContext *avctx){
1213     Mpeg1Context *s1 = avctx->priv_data;
1214     MpegEncContext *s = &s1->mpeg_enc_ctx;
1215
1216     if(avctx->xvmc_acceleration)
1217         return avctx->get_format(avctx,pixfmt_xvmc_mpg2_420);
1218     else if(avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
1219         if(avctx->codec_id == CODEC_ID_MPEG1VIDEO)
1220             return PIX_FMT_VDPAU_MPEG1;
1221         else
1222             return PIX_FMT_VDPAU_MPEG2;
1223     }else{
1224         if(s->chroma_format <  2)
1225             return avctx->get_format(avctx,ff_hwaccel_pixfmt_list_420);
1226         else if(s->chroma_format == 2)
1227             return PIX_FMT_YUV422P;
1228         else
1229             return PIX_FMT_YUV444P;
1230     }
1231 }
1232
1233 /* Call this function when we know all parameters.
1234  * It may be called in different places for MPEG-1 and MPEG-2. */
1235 static int mpeg_decode_postinit(AVCodecContext *avctx){
1236     Mpeg1Context *s1 = avctx->priv_data;
1237     MpegEncContext *s = &s1->mpeg_enc_ctx;
1238     uint8_t old_permutation[64];
1239
1240     if (
1241         (s1->mpeg_enc_ctx_allocated == 0)||
1242         avctx->coded_width  != s->width ||
1243         avctx->coded_height != s->height||
1244         s1->save_width != s->width ||
1245         s1->save_height != s->height ||
1246         s1->save_aspect_info != s->aspect_ratio_info||
1247         s1->save_progressive_seq != s->progressive_sequence ||
1248         0)
1249     {
1250
1251         if (s1->mpeg_enc_ctx_allocated) {
1252             ParseContext pc= s->parse_context;
1253             s->parse_context.buffer=0;
1254             MPV_common_end(s);
1255             s->parse_context= pc;
1256         }
1257
1258         if( (s->width == 0 )||(s->height == 0))
1259             return -2;
1260
1261         avcodec_set_dimensions(avctx, s->width, s->height);
1262         avctx->bit_rate = s->bit_rate;
1263         s1->save_aspect_info = s->aspect_ratio_info;
1264         s1->save_width = s->width;
1265         s1->save_height = s->height;
1266         s1->save_progressive_seq = s->progressive_sequence;
1267
1268         /* low_delay may be forced, in this case we will have B-frames
1269          * that behave like P-frames. */
1270         avctx->has_b_frames = !(s->low_delay);
1271
1272         assert((avctx->sub_id==1) == (avctx->codec_id==CODEC_ID_MPEG1VIDEO));
1273         if(avctx->codec_id==CODEC_ID_MPEG1VIDEO){
1274             //MPEG-1 fps
1275             avctx->time_base.den= ff_frame_rate_tab[s->frame_rate_index].num;
1276             avctx->time_base.num= ff_frame_rate_tab[s->frame_rate_index].den;
1277             //MPEG-1 aspect
1278             avctx->sample_aspect_ratio= av_d2q(
1279                     1.0/ff_mpeg1_aspect[s->aspect_ratio_info], 255);
1280             avctx->ticks_per_frame=1;
1281         }else{//MPEG-2
1282         //MPEG-2 fps
1283             av_reduce(
1284                 &s->avctx->time_base.den,
1285                 &s->avctx->time_base.num,
1286                 ff_frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num*2,
1287                 ff_frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den,
1288                 1<<30);
1289             avctx->ticks_per_frame=2;
1290         //MPEG-2 aspect
1291             if(s->aspect_ratio_info > 1){
1292                 //we ignore the spec here as reality does not match the spec, see for example
1293                 // res_change_ffmpeg_aspect.ts and sequence-display-aspect.mpg
1294                 if( (s1->pan_scan.width == 0 )||(s1->pan_scan.height == 0) || 1){
1295                     s->avctx->sample_aspect_ratio=
1296                         av_div_q(
1297                          ff_mpeg2_aspect[s->aspect_ratio_info],
1298                          (AVRational){s->width, s->height}
1299                          );
1300                 }else{
1301                     s->avctx->sample_aspect_ratio=
1302                         av_div_q(
1303                          ff_mpeg2_aspect[s->aspect_ratio_info],
1304                          (AVRational){s1->pan_scan.width, s1->pan_scan.height}
1305                         );
1306                 }
1307             }else{
1308                 s->avctx->sample_aspect_ratio=
1309                     ff_mpeg2_aspect[s->aspect_ratio_info];
1310             }
1311         }//MPEG-2
1312
1313         avctx->pix_fmt = mpeg_get_pixelformat(avctx);
1314         avctx->hwaccel = ff_find_hwaccel(avctx->codec->id, avctx->pix_fmt);
1315         //until then pix_fmt may be changed right after codec init
1316         if( avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT ||
1317             avctx->hwaccel ||
1318             s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU )
1319             if( avctx->idct_algo == FF_IDCT_AUTO )
1320                 avctx->idct_algo = FF_IDCT_SIMPLE;
1321
1322         /* Quantization matrices may need reordering
1323          * if DCT permutation is changed. */
1324         memcpy(old_permutation,s->dsp.idct_permutation,64*sizeof(uint8_t));
1325
1326         if (MPV_common_init(s) < 0)
1327             return -2;
1328
1329         quant_matrix_rebuild(s->intra_matrix,       old_permutation,s->dsp.idct_permutation);
1330         quant_matrix_rebuild(s->inter_matrix,       old_permutation,s->dsp.idct_permutation);
1331         quant_matrix_rebuild(s->chroma_intra_matrix,old_permutation,s->dsp.idct_permutation);
1332         quant_matrix_rebuild(s->chroma_inter_matrix,old_permutation,s->dsp.idct_permutation);
1333
1334         s1->mpeg_enc_ctx_allocated = 1;
1335     }
1336     return 0;
1337 }
1338
1339 static int mpeg1_decode_picture(AVCodecContext *avctx,
1340                                 const uint8_t *buf, int buf_size)
1341 {
1342     Mpeg1Context *s1 = avctx->priv_data;
1343     MpegEncContext *s = &s1->mpeg_enc_ctx;
1344     int ref, f_code, vbv_delay;
1345
1346     if(mpeg_decode_postinit(s->avctx) < 0)
1347        return -2;
1348
1349     init_get_bits(&s->gb, buf, buf_size*8);
1350
1351     ref = get_bits(&s->gb, 10); /* temporal ref */
1352     s->pict_type = get_bits(&s->gb, 3);
1353     if(s->pict_type == 0 || s->pict_type > 3)
1354         return -1;
1355
1356     vbv_delay= get_bits(&s->gb, 16);
1357     if (s->pict_type == FF_P_TYPE || s->pict_type == FF_B_TYPE) {
1358         s->full_pel[0] = get_bits1(&s->gb);
1359         f_code = get_bits(&s->gb, 3);
1360         if (f_code == 0 && avctx->error_recognition >= FF_ER_COMPLIANT)
1361             return -1;
1362         s->mpeg_f_code[0][0] = f_code;
1363         s->mpeg_f_code[0][1] = f_code;
1364     }
1365     if (s->pict_type == FF_B_TYPE) {
1366         s->full_pel[1] = get_bits1(&s->gb);
1367         f_code = get_bits(&s->gb, 3);
1368         if (f_code == 0 && avctx->error_recognition >= FF_ER_COMPLIANT)
1369             return -1;
1370         s->mpeg_f_code[1][0] = f_code;
1371         s->mpeg_f_code[1][1] = f_code;
1372     }
1373     s->current_picture.pict_type= s->pict_type;
1374     s->current_picture.key_frame= s->pict_type == FF_I_TYPE;
1375
1376     if(avctx->debug & FF_DEBUG_PICT_INFO)
1377         av_log(avctx, AV_LOG_DEBUG, "vbv_delay %d, ref %d type:%d\n", vbv_delay, ref, s->pict_type);
1378
1379     s->y_dc_scale = 8;
1380     s->c_dc_scale = 8;
1381     s->first_slice = 1;
1382     return 0;
1383 }
1384
1385 static void mpeg_decode_sequence_extension(Mpeg1Context *s1)
1386 {
1387     MpegEncContext *s= &s1->mpeg_enc_ctx;
1388     int horiz_size_ext, vert_size_ext;
1389     int bit_rate_ext;
1390
1391     skip_bits(&s->gb, 1); /* profile and level esc*/
1392     s->avctx->profile= get_bits(&s->gb, 3);
1393     s->avctx->level= get_bits(&s->gb, 4);
1394     s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1395     s->chroma_format = get_bits(&s->gb, 2); /* chroma_format 1=420, 2=422, 3=444 */
1396     horiz_size_ext = get_bits(&s->gb, 2);
1397     vert_size_ext = get_bits(&s->gb, 2);
1398     s->width |= (horiz_size_ext << 12);
1399     s->height |= (vert_size_ext << 12);
1400     bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1401     s->bit_rate += (bit_rate_ext << 18) * 400;
1402     skip_bits1(&s->gb); /* marker */
1403     s->avctx->rc_buffer_size += get_bits(&s->gb, 8)*1024*16<<10;
1404
1405     s->low_delay = get_bits1(&s->gb);
1406     if(s->flags & CODEC_FLAG_LOW_DELAY) s->low_delay=1;
1407
1408     s1->frame_rate_ext.num = get_bits(&s->gb, 2)+1;
1409     s1->frame_rate_ext.den = get_bits(&s->gb, 5)+1;
1410
1411     dprintf(s->avctx, "sequence extension\n");
1412     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG2VIDEO;
1413     s->avctx->sub_id = 2; /* indicates MPEG-2 found */
1414
1415     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1416         av_log(s->avctx, AV_LOG_DEBUG, "profile: %d, level: %d vbv buffer: %d, bitrate:%d\n",
1417                s->avctx->profile, s->avctx->level, s->avctx->rc_buffer_size, s->bit_rate);
1418
1419 }
1420
1421 static void mpeg_decode_sequence_display_extension(Mpeg1Context *s1)
1422 {
1423     MpegEncContext *s= &s1->mpeg_enc_ctx;
1424     int color_description, w, h;
1425
1426     skip_bits(&s->gb, 3); /* video format */
1427     color_description= get_bits1(&s->gb);
1428     if(color_description){
1429         s->avctx->color_primaries= get_bits(&s->gb, 8);
1430         s->avctx->color_trc      = get_bits(&s->gb, 8);
1431         s->avctx->colorspace     = get_bits(&s->gb, 8);
1432     }
1433     w= get_bits(&s->gb, 14);
1434     skip_bits(&s->gb, 1); //marker
1435     h= get_bits(&s->gb, 14);
1436     skip_bits(&s->gb, 1); //marker
1437
1438     s1->pan_scan.width= 16*w;
1439     s1->pan_scan.height=16*h;
1440
1441     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1442         av_log(s->avctx, AV_LOG_DEBUG, "sde w:%d, h:%d\n", w, h);
1443 }
1444
1445 static void mpeg_decode_picture_display_extension(Mpeg1Context *s1)
1446 {
1447     MpegEncContext *s= &s1->mpeg_enc_ctx;
1448     int i,nofco;
1449
1450     nofco = 1;
1451     if(s->progressive_sequence){
1452         if(s->repeat_first_field){
1453             nofco++;
1454             if(s->top_field_first)
1455                 nofco++;
1456         }
1457     }else{
1458         if(s->picture_structure == PICT_FRAME){
1459             nofco++;
1460             if(s->repeat_first_field)
1461                 nofco++;
1462         }
1463     }
1464     for(i=0; i<nofco; i++){
1465         s1->pan_scan.position[i][0]= get_sbits(&s->gb, 16);
1466         skip_bits(&s->gb, 1); //marker
1467         s1->pan_scan.position[i][1]= get_sbits(&s->gb, 16);
1468         skip_bits(&s->gb, 1); //marker
1469     }
1470
1471     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1472         av_log(s->avctx, AV_LOG_DEBUG, "pde (%d,%d) (%d,%d) (%d,%d)\n",
1473             s1->pan_scan.position[0][0], s1->pan_scan.position[0][1],
1474             s1->pan_scan.position[1][0], s1->pan_scan.position[1][1],
1475             s1->pan_scan.position[2][0], s1->pan_scan.position[2][1]
1476         );
1477 }
1478
1479 static int load_matrix(MpegEncContext *s, uint16_t matrix0[64], uint16_t matrix1[64], int intra){
1480     int i;
1481
1482     for(i=0; i<64; i++) {
1483         int j = s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1484         int v = get_bits(&s->gb, 8);
1485         if(v==0){
1486             av_log(s->avctx, AV_LOG_ERROR, "matrix damaged\n");
1487             return -1;
1488         }
1489         if(intra && i==0 && v!=8){
1490             av_log(s->avctx, AV_LOG_ERROR, "intra matrix invalid, ignoring\n");
1491             v= 8; // needed by pink.mpg / issue1046
1492         }
1493         matrix0[j] = v;
1494         if(matrix1)
1495             matrix1[j] = v;
1496     }
1497     return 0;
1498 }
1499
1500 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1501 {
1502     dprintf(s->avctx, "matrix extension\n");
1503
1504     if(get_bits1(&s->gb)) load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
1505     if(get_bits1(&s->gb)) load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
1506     if(get_bits1(&s->gb)) load_matrix(s, s->chroma_intra_matrix, NULL           , 1);
1507     if(get_bits1(&s->gb)) load_matrix(s, s->chroma_inter_matrix, NULL           , 0);
1508 }
1509
1510 static void mpeg_decode_picture_coding_extension(Mpeg1Context *s1)
1511 {
1512     MpegEncContext *s= &s1->mpeg_enc_ctx;
1513
1514     s->full_pel[0] = s->full_pel[1] = 0;
1515     s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1516     s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1517     s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1518     s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1519     if(!s->pict_type && s1->mpeg_enc_ctx_allocated){
1520         av_log(s->avctx, AV_LOG_ERROR, "Missing picture start code, guessing missing values\n");
1521         if(s->mpeg_f_code[1][0] == 15 && s->mpeg_f_code[1][1]==15){
1522             if(s->mpeg_f_code[0][0] == 15 && s->mpeg_f_code[0][1] == 15)
1523                 s->pict_type= FF_I_TYPE;
1524             else
1525                 s->pict_type= FF_P_TYPE;
1526         }else
1527             s->pict_type= FF_B_TYPE;
1528         s->current_picture.pict_type= s->pict_type;
1529         s->current_picture.key_frame= s->pict_type == FF_I_TYPE;
1530         s->first_slice= 1;
1531     }
1532     s->intra_dc_precision = get_bits(&s->gb, 2);
1533     s->picture_structure = get_bits(&s->gb, 2);
1534     s->top_field_first = get_bits1(&s->gb);
1535     s->frame_pred_frame_dct = get_bits1(&s->gb);
1536     s->concealment_motion_vectors = get_bits1(&s->gb);
1537     s->q_scale_type = get_bits1(&s->gb);
1538     s->intra_vlc_format = get_bits1(&s->gb);
1539     s->alternate_scan = get_bits1(&s->gb);
1540     s->repeat_first_field = get_bits1(&s->gb);
1541     s->chroma_420_type = get_bits1(&s->gb);
1542     s->progressive_frame = get_bits1(&s->gb);
1543
1544     if(s->picture_structure == PICT_FRAME){
1545         s->first_field=0;
1546         s->v_edge_pos= 16*s->mb_height;
1547     }else{
1548         s->first_field ^= 1;
1549         s->v_edge_pos=  8*s->mb_height;
1550         memset(s->mbskip_table, 0, s->mb_stride*s->mb_height);
1551     }
1552
1553     if(s->alternate_scan){
1554         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
1555         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
1556     }else{
1557         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
1558         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
1559     }
1560
1561     /* composite display not parsed */
1562     dprintf(s->avctx, "intra_dc_precision=%d\n", s->intra_dc_precision);
1563     dprintf(s->avctx, "picture_structure=%d\n", s->picture_structure);
1564     dprintf(s->avctx, "top field first=%d\n", s->top_field_first);
1565     dprintf(s->avctx, "repeat first field=%d\n", s->repeat_first_field);
1566     dprintf(s->avctx, "conceal=%d\n", s->concealment_motion_vectors);
1567     dprintf(s->avctx, "intra_vlc_format=%d\n", s->intra_vlc_format);
1568     dprintf(s->avctx, "alternate_scan=%d\n", s->alternate_scan);
1569     dprintf(s->avctx, "frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1570     dprintf(s->avctx, "progressive_frame=%d\n", s->progressive_frame);
1571 }
1572
1573 static void mpeg_decode_extension(AVCodecContext *avctx,
1574                                   const uint8_t *buf, int buf_size)
1575 {
1576     Mpeg1Context *s1 = avctx->priv_data;
1577     MpegEncContext *s = &s1->mpeg_enc_ctx;
1578     int ext_type;
1579
1580     init_get_bits(&s->gb, buf, buf_size*8);
1581
1582     ext_type = get_bits(&s->gb, 4);
1583     switch(ext_type) {
1584     case 0x1:
1585         mpeg_decode_sequence_extension(s1);
1586         break;
1587     case 0x2:
1588         mpeg_decode_sequence_display_extension(s1);
1589         break;
1590     case 0x3:
1591         mpeg_decode_quant_matrix_extension(s);
1592         break;
1593     case 0x7:
1594         mpeg_decode_picture_display_extension(s1);
1595         break;
1596     case 0x8:
1597         mpeg_decode_picture_coding_extension(s1);
1598         break;
1599     }
1600 }
1601
1602 static void exchange_uv(MpegEncContext *s){
1603     DCTELEM (*tmp)[64];
1604
1605     tmp           = s->pblocks[4];
1606     s->pblocks[4] = s->pblocks[5];
1607     s->pblocks[5] = tmp;
1608 }
1609
1610 static int mpeg_field_start(MpegEncContext *s, const uint8_t *buf, int buf_size){
1611     AVCodecContext *avctx= s->avctx;
1612     Mpeg1Context *s1 = (Mpeg1Context*)s;
1613
1614     /* start frame decoding */
1615     if(s->first_field || s->picture_structure==PICT_FRAME){
1616         if(MPV_frame_start(s, avctx) < 0)
1617             return -1;
1618
1619         ff_er_frame_start(s);
1620
1621         /* first check if we must repeat the frame */
1622         s->current_picture_ptr->repeat_pict = 0;
1623         if (s->repeat_first_field) {
1624             if (s->progressive_sequence) {
1625                 if (s->top_field_first)
1626                     s->current_picture_ptr->repeat_pict = 4;
1627                 else
1628                     s->current_picture_ptr->repeat_pict = 2;
1629             } else if (s->progressive_frame) {
1630                 s->current_picture_ptr->repeat_pict = 1;
1631             }
1632         }
1633
1634         *s->current_picture_ptr->pan_scan= s1->pan_scan;
1635     }else{ //second field
1636             int i;
1637
1638             if(!s->current_picture_ptr){
1639                 av_log(s->avctx, AV_LOG_ERROR, "first field missing\n");
1640                 return -1;
1641             }
1642
1643             for(i=0; i<4; i++){
1644                 s->current_picture.data[i] = s->current_picture_ptr->data[i];
1645                 if(s->picture_structure == PICT_BOTTOM_FIELD){
1646                     s->current_picture.data[i] += s->current_picture_ptr->linesize[i];
1647                 }
1648             }
1649     }
1650
1651     if (avctx->hwaccel) {
1652         if (avctx->hwaccel->start_frame(avctx, buf, buf_size) < 0)
1653             return -1;
1654     }
1655
1656 // MPV_frame_start will call this function too,
1657 // but we need to call it on every field
1658     if(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)
1659         if(ff_xvmc_field_start(s,avctx) < 0)
1660             return -1;
1661
1662     return 0;
1663 }
1664
1665 #define DECODE_SLICE_ERROR -1
1666 #define DECODE_SLICE_OK 0
1667
1668 /**
1669  * decodes a slice. MpegEncContext.mb_y must be set to the MB row from the startcode
1670  * @return DECODE_SLICE_ERROR if the slice is damaged<br>
1671  *         DECODE_SLICE_OK if this slice is ok<br>
1672  */
1673 static int mpeg_decode_slice(Mpeg1Context *s1, int mb_y,
1674                              const uint8_t **buf, int buf_size)
1675 {
1676     MpegEncContext *s = &s1->mpeg_enc_ctx;
1677     AVCodecContext *avctx= s->avctx;
1678     const int field_pic= s->picture_structure != PICT_FRAME;
1679     const int lowres= s->avctx->lowres;
1680
1681     s->resync_mb_x=
1682     s->resync_mb_y= -1;
1683
1684     if (mb_y<<field_pic >= s->mb_height){
1685         av_log(s->avctx, AV_LOG_ERROR, "slice below image (%d >= %d)\n", mb_y, s->mb_height);
1686         return -1;
1687     }
1688
1689     init_get_bits(&s->gb, *buf, buf_size*8);
1690
1691     ff_mpeg1_clean_buffers(s);
1692     s->interlaced_dct = 0;
1693
1694     s->qscale = get_qscale(s);
1695
1696     if(s->qscale == 0){
1697         av_log(s->avctx, AV_LOG_ERROR, "qscale == 0\n");
1698         return -1;
1699     }
1700
1701     /* extra slice info */
1702     while (get_bits1(&s->gb) != 0) {
1703         skip_bits(&s->gb, 8);
1704     }
1705
1706     s->mb_x=0;
1707
1708     if (avctx->hwaccel) {
1709         const uint8_t *buf_end, *buf_start = *buf - 4; /* include start_code */
1710         int start_code = -1;
1711         buf_end = ff_find_start_code(buf_start + 2, *buf + buf_size, &start_code);
1712         if (buf_end < *buf + buf_size)
1713             buf_end -= 4;
1714         s->mb_y = mb_y;
1715         if (avctx->hwaccel->decode_slice(avctx, buf_start, buf_end - buf_start) < 0)
1716             return DECODE_SLICE_ERROR;
1717         *buf = buf_end;
1718         return DECODE_SLICE_OK;
1719     }
1720
1721     for(;;) {
1722         int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
1723         if (code < 0){
1724             av_log(s->avctx, AV_LOG_ERROR, "first mb_incr damaged\n");
1725             return -1;
1726         }
1727         if (code >= 33) {
1728             if (code == 33) {
1729                 s->mb_x += 33;
1730             }
1731             /* otherwise, stuffing, nothing to do */
1732         } else {
1733             s->mb_x += code;
1734             break;
1735         }
1736     }
1737     if(s->mb_x >= (unsigned)s->mb_width){
1738         av_log(s->avctx, AV_LOG_ERROR, "initial skip overflow\n");
1739         return -1;
1740     }
1741
1742     s->resync_mb_x= s->mb_x;
1743     s->resync_mb_y= s->mb_y= mb_y;
1744     s->mb_skip_run= 0;
1745     ff_init_block_index(s);
1746
1747     if (s->mb_y==0 && s->mb_x==0 && (s->first_field || s->picture_structure==PICT_FRAME)) {
1748         if(s->avctx->debug&FF_DEBUG_PICT_INFO){
1749              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",
1750                  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],
1751                  s->pict_type == FF_I_TYPE ? "I" : (s->pict_type == FF_P_TYPE ? "P" : (s->pict_type == FF_B_TYPE ? "B" : "S")),
1752                  s->progressive_sequence ? "ps" :"", s->progressive_frame ? "pf" : "", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"",
1753                  s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors,
1754                  s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :"");
1755         }
1756     }
1757
1758     for(;;) {
1759         //If 1, we memcpy blocks in xvmcvideo.
1760         if(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration > 1)
1761             ff_xvmc_init_block(s);//set s->block
1762
1763         if(mpeg_decode_mb(s, s->block) < 0)
1764             return -1;
1765
1766         if(s->current_picture.motion_val[0] && !s->encoding){ //note motion_val is normally NULL unless we want to extract the MVs
1767             const int wrap = field_pic ? 2*s->b8_stride : s->b8_stride;
1768             int xy = s->mb_x*2 + s->mb_y*2*wrap;
1769             int motion_x, motion_y, dir, i;
1770             if(field_pic && !s->first_field)
1771                 xy += wrap/2;
1772
1773             for(i=0; i<2; i++){
1774                 for(dir=0; dir<2; dir++){
1775                     if (s->mb_intra || (dir==1 && s->pict_type != FF_B_TYPE)) {
1776                         motion_x = motion_y = 0;
1777                     }else if (s->mv_type == MV_TYPE_16X16 || (s->mv_type == MV_TYPE_FIELD && field_pic)){
1778                         motion_x = s->mv[dir][0][0];
1779                         motion_y = s->mv[dir][0][1];
1780                     } else /*if ((s->mv_type == MV_TYPE_FIELD) || (s->mv_type == MV_TYPE_16X8))*/ {
1781                         motion_x = s->mv[dir][i][0];
1782                         motion_y = s->mv[dir][i][1];
1783                     }
1784
1785                     s->current_picture.motion_val[dir][xy    ][0] = motion_x;
1786                     s->current_picture.motion_val[dir][xy    ][1] = motion_y;
1787                     s->current_picture.motion_val[dir][xy + 1][0] = motion_x;
1788                     s->current_picture.motion_val[dir][xy + 1][1] = motion_y;
1789                     s->current_picture.ref_index [dir][xy    ]=
1790                     s->current_picture.ref_index [dir][xy + 1]= s->field_select[dir][i];
1791                     assert(s->field_select[dir][i]==0 || s->field_select[dir][i]==1);
1792                 }
1793                 xy += wrap;
1794             }
1795         }
1796
1797         s->dest[0] += 16 >> lowres;
1798         s->dest[1] +=(16 >> lowres) >> s->chroma_x_shift;
1799         s->dest[2] +=(16 >> lowres) >> s->chroma_x_shift;
1800
1801         MPV_decode_mb(s, s->block);
1802
1803         if (++s->mb_x >= s->mb_width) {
1804             const int mb_size= 16>>s->avctx->lowres;
1805
1806             ff_draw_horiz_band(s, mb_size*s->mb_y, mb_size);
1807
1808             s->mb_x = 0;
1809             s->mb_y++;
1810
1811             if(s->mb_y<<field_pic >= s->mb_height){
1812                 int left= s->gb.size_in_bits - get_bits_count(&s->gb);
1813                 int is_d10= s->chroma_format==2 && s->pict_type==FF_I_TYPE && avctx->profile==0 && avctx->level==5
1814                             && s->intra_dc_precision == 2 && s->q_scale_type == 1 && s->alternate_scan == 0
1815                             && s->progressive_frame == 0 /* vbv_delay == 0xBBB || 0xE10*/;
1816
1817                 if(left < 0 || (left && show_bits(&s->gb, FFMIN(left, 23)) && !is_d10)
1818                    || (avctx->error_recognition >= FF_ER_AGGRESSIVE && left>8)){
1819                     av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d %0X\n", left, show_bits(&s->gb, FFMIN(left, 23)));
1820                     return -1;
1821                 }else
1822                     goto eos;
1823             }
1824
1825             ff_init_block_index(s);
1826         }
1827
1828         /* skip mb handling */
1829         if (s->mb_skip_run == -1) {
1830             /* read increment again */
1831             s->mb_skip_run = 0;
1832             for(;;) {
1833                 int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
1834                 if (code < 0){
1835                     av_log(s->avctx, AV_LOG_ERROR, "mb incr damaged\n");
1836                     return -1;
1837                 }
1838                 if (code >= 33) {
1839                     if (code == 33) {
1840                         s->mb_skip_run += 33;
1841                     }else if(code == 35){
1842                         if(s->mb_skip_run != 0 || show_bits(&s->gb, 15) != 0){
1843                             av_log(s->avctx, AV_LOG_ERROR, "slice mismatch\n");
1844                             return -1;
1845                         }
1846                         goto eos; /* end of slice */
1847                     }
1848                     /* otherwise, stuffing, nothing to do */
1849                 } else {
1850                     s->mb_skip_run += code;
1851                     break;
1852                 }
1853             }
1854             if(s->mb_skip_run){
1855                 int i;
1856                 if(s->pict_type == FF_I_TYPE){
1857                     av_log(s->avctx, AV_LOG_ERROR, "skipped MB in I frame at %d %d\n", s->mb_x, s->mb_y);
1858                     return -1;
1859                 }
1860
1861                 /* skip mb */
1862                 s->mb_intra = 0;
1863                 for(i=0;i<12;i++)
1864                     s->block_last_index[i] = -1;
1865                 if(s->picture_structure == PICT_FRAME)
1866                     s->mv_type = MV_TYPE_16X16;
1867                 else
1868                     s->mv_type = MV_TYPE_FIELD;
1869                 if (s->pict_type == FF_P_TYPE) {
1870                     /* if P type, zero motion vector is implied */
1871                     s->mv_dir = MV_DIR_FORWARD;
1872                     s->mv[0][0][0] = s->mv[0][0][1] = 0;
1873                     s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
1874                     s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
1875                     s->field_select[0][0]= s->picture_structure - 1;
1876                 } else {
1877                     /* if B type, reuse previous vectors and directions */
1878                     s->mv[0][0][0] = s->last_mv[0][0][0];
1879                     s->mv[0][0][1] = s->last_mv[0][0][1];
1880                     s->mv[1][0][0] = s->last_mv[1][0][0];
1881                     s->mv[1][0][1] = s->last_mv[1][0][1];
1882                 }
1883             }
1884         }
1885     }
1886 eos: // end of slice
1887     *buf += (get_bits_count(&s->gb)-1)/8;
1888 //printf("y %d %d %d %d\n", s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y);
1889     return 0;
1890 }
1891
1892 static int slice_decode_thread(AVCodecContext *c, void *arg){
1893     MpegEncContext *s= *(void**)arg;
1894     const uint8_t *buf= s->gb.buffer;
1895     int mb_y= s->start_mb_y;
1896
1897     s->error_count= 3*(s->end_mb_y - s->start_mb_y)*s->mb_width;
1898
1899     for(;;){
1900         uint32_t start_code;
1901         int ret;
1902
1903         ret= mpeg_decode_slice((Mpeg1Context*)s, mb_y, &buf, s->gb.buffer_end - buf);
1904         emms_c();
1905 //av_log(c, AV_LOG_DEBUG, "ret:%d resync:%d/%d mb:%d/%d ts:%d/%d ec:%d\n",
1906 //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);
1907         if(ret < 0){
1908             if(s->resync_mb_x>=0 && s->resync_mb_y>=0)
1909                 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);
1910         }else{
1911             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);
1912         }
1913
1914         if(s->mb_y == s->end_mb_y)
1915             return 0;
1916
1917         start_code= -1;
1918         buf = ff_find_start_code(buf, s->gb.buffer_end, &start_code);
1919         mb_y= start_code - SLICE_MIN_START_CODE;
1920         if(mb_y < 0 || mb_y >= s->end_mb_y)
1921             return -1;
1922     }
1923
1924     return 0; //not reached
1925 }
1926
1927 /**
1928  * Handles slice ends.
1929  * @return 1 if it seems to be the last slice
1930  */
1931 static int slice_end(AVCodecContext *avctx, AVFrame *pict)
1932 {
1933     Mpeg1Context *s1 = avctx->priv_data;
1934     MpegEncContext *s = &s1->mpeg_enc_ctx;
1935
1936     if (!s1->mpeg_enc_ctx_allocated || !s->current_picture_ptr)
1937         return 0;
1938
1939     if (s->avctx->hwaccel) {
1940         if (s->avctx->hwaccel->end_frame(s->avctx) < 0)
1941             av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
1942     }
1943
1944     if(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)
1945         ff_xvmc_field_end(s);
1946
1947     /* end of slice reached */
1948     if (/*s->mb_y<<field_pic == s->mb_height &&*/ !s->first_field) {
1949         /* end of image */
1950
1951         s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_MPEG2;
1952
1953         ff_er_frame_end(s);
1954
1955         MPV_frame_end(s);
1956
1957         if (s->pict_type == FF_B_TYPE || s->low_delay) {
1958             *pict= *(AVFrame*)s->current_picture_ptr;
1959             ff_print_debug_info(s, pict);
1960         } else {
1961             s->picture_number++;
1962             /* latency of 1 frame for I- and P-frames */
1963             /* XXX: use another variable than picture_number */
1964             if (s->last_picture_ptr != NULL) {
1965                 *pict= *(AVFrame*)s->last_picture_ptr;
1966                  ff_print_debug_info(s, pict);
1967             }
1968         }
1969
1970         return 1;
1971     } else {
1972         return 0;
1973     }
1974 }
1975
1976 static int mpeg1_decode_sequence(AVCodecContext *avctx,
1977                                  const uint8_t *buf, int buf_size)
1978 {
1979     Mpeg1Context *s1 = avctx->priv_data;
1980     MpegEncContext *s = &s1->mpeg_enc_ctx;
1981     int width,height;
1982     int i, v, j;
1983
1984     init_get_bits(&s->gb, buf, buf_size*8);
1985
1986     width = get_bits(&s->gb, 12);
1987     height = get_bits(&s->gb, 12);
1988     if (width <= 0 || height <= 0)
1989         return -1;
1990     s->aspect_ratio_info= get_bits(&s->gb, 4);
1991     if (s->aspect_ratio_info == 0) {
1992         av_log(avctx, AV_LOG_ERROR, "aspect ratio has forbidden 0 value\n");
1993         if (avctx->error_recognition >= FF_ER_COMPLIANT)
1994             return -1;
1995     }
1996     s->frame_rate_index = get_bits(&s->gb, 4);
1997     if (s->frame_rate_index == 0 || s->frame_rate_index > 13)
1998         return -1;
1999     s->bit_rate = get_bits(&s->gb, 18) * 400;
2000     if (get_bits1(&s->gb) == 0) /* marker */
2001         return -1;
2002     s->width = width;
2003     s->height = height;
2004
2005     s->avctx->rc_buffer_size= get_bits(&s->gb, 10) * 1024*16;
2006     skip_bits(&s->gb, 1);
2007
2008     /* get matrix */
2009     if (get_bits1(&s->gb)) {
2010         load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
2011     } else {
2012         for(i=0;i<64;i++) {
2013             j = s->dsp.idct_permutation[i];
2014             v = ff_mpeg1_default_intra_matrix[i];
2015             s->intra_matrix[j] = v;
2016             s->chroma_intra_matrix[j] = v;
2017         }
2018     }
2019     if (get_bits1(&s->gb)) {
2020         load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
2021     } else {
2022         for(i=0;i<64;i++) {
2023             int j= s->dsp.idct_permutation[i];
2024             v = ff_mpeg1_default_non_intra_matrix[i];
2025             s->inter_matrix[j] = v;
2026             s->chroma_inter_matrix[j] = v;
2027         }
2028     }
2029
2030     if(show_bits(&s->gb, 23) != 0){
2031         av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");
2032         return -1;
2033     }
2034
2035     /* we set MPEG-2 parameters so that it emulates MPEG-1 */
2036     s->progressive_sequence = 1;
2037     s->progressive_frame = 1;
2038     s->picture_structure = PICT_FRAME;
2039     s->frame_pred_frame_dct = 1;
2040     s->chroma_format = 1;
2041     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG1VIDEO;
2042     avctx->sub_id = 1; /* indicates MPEG-1 */
2043     s->out_format = FMT_MPEG1;
2044     s->swap_uv = 0;//AFAIK VCR2 does not have SEQ_HEADER
2045     if(s->flags & CODEC_FLAG_LOW_DELAY) s->low_delay=1;
2046
2047     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2048         av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%d\n",
2049                s->avctx->rc_buffer_size, s->bit_rate);
2050
2051     return 0;
2052 }
2053
2054 static int vcr2_init_sequence(AVCodecContext *avctx)
2055 {
2056     Mpeg1Context *s1 = avctx->priv_data;
2057     MpegEncContext *s = &s1->mpeg_enc_ctx;
2058     int i, v;
2059
2060     /* start new MPEG-1 context decoding */
2061     s->out_format = FMT_MPEG1;
2062     if (s1->mpeg_enc_ctx_allocated) {
2063         MPV_common_end(s);
2064     }
2065     s->width  = avctx->coded_width;
2066     s->height = avctx->coded_height;
2067     avctx->has_b_frames= 0; //true?
2068     s->low_delay= 1;
2069
2070     avctx->pix_fmt = mpeg_get_pixelformat(avctx);
2071     avctx->hwaccel = ff_find_hwaccel(avctx->codec->id, avctx->pix_fmt);
2072
2073     if( avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT || avctx->hwaccel ||
2074         s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU )
2075         if( avctx->idct_algo == FF_IDCT_AUTO )
2076             avctx->idct_algo = FF_IDCT_SIMPLE;
2077
2078     if (MPV_common_init(s) < 0)
2079         return -1;
2080     exchange_uv(s);//common init reset pblocks, so we swap them here
2081     s->swap_uv = 1;// in case of xvmc we need to swap uv for each MB
2082     s1->mpeg_enc_ctx_allocated = 1;
2083
2084     for(i=0;i<64;i++) {
2085         int j= s->dsp.idct_permutation[i];
2086         v = ff_mpeg1_default_intra_matrix[i];
2087         s->intra_matrix[j] = v;
2088         s->chroma_intra_matrix[j] = v;
2089
2090         v = ff_mpeg1_default_non_intra_matrix[i];
2091         s->inter_matrix[j] = v;
2092         s->chroma_inter_matrix[j] = v;
2093     }
2094
2095     s->progressive_sequence = 1;
2096     s->progressive_frame = 1;
2097     s->picture_structure = PICT_FRAME;
2098     s->frame_pred_frame_dct = 1;
2099     s->chroma_format = 1;
2100     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG2VIDEO;
2101     avctx->sub_id = 2; /* indicates MPEG-2 */
2102     return 0;
2103 }
2104
2105
2106 static void mpeg_decode_user_data(AVCodecContext *avctx,
2107                                   const uint8_t *buf, int buf_size)
2108 {
2109     const uint8_t *p;
2110     int len, flags;
2111     p = buf;
2112     len = buf_size;
2113
2114     /* we parse the DTG active format information */
2115     if (len >= 5 &&
2116         p[0] == 'D' && p[1] == 'T' && p[2] == 'G' && p[3] == '1') {
2117         flags = p[4];
2118         p += 5;
2119         len -= 5;
2120         if (flags & 0x80) {
2121             /* skip event id */
2122             if (len < 2)
2123                 return;
2124             p += 2;
2125             len -= 2;
2126         }
2127         if (flags & 0x40) {
2128             if (len < 1)
2129                 return;
2130             avctx->dtg_active_format = p[0] & 0x0f;
2131         }
2132     }
2133 }
2134
2135 static void mpeg_decode_gop(AVCodecContext *avctx,
2136                             const uint8_t *buf, int buf_size){
2137     Mpeg1Context *s1 = avctx->priv_data;
2138     MpegEncContext *s = &s1->mpeg_enc_ctx;
2139
2140     int drop_frame_flag;
2141     int time_code_hours, time_code_minutes;
2142     int time_code_seconds, time_code_pictures;
2143     int broken_link;
2144
2145     init_get_bits(&s->gb, buf, buf_size*8);
2146
2147     drop_frame_flag = get_bits1(&s->gb);
2148
2149     time_code_hours=get_bits(&s->gb,5);
2150     time_code_minutes = get_bits(&s->gb,6);
2151     skip_bits1(&s->gb);//marker bit
2152     time_code_seconds = get_bits(&s->gb,6);
2153     time_code_pictures = get_bits(&s->gb,6);
2154
2155     s->closed_gop = get_bits1(&s->gb);
2156     /*broken_link indicate that after editing the
2157       reference frames of the first B-Frames after GOP I-Frame
2158       are missing (open gop)*/
2159     broken_link = get_bits1(&s->gb);
2160
2161     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2162         av_log(s->avctx, AV_LOG_DEBUG, "GOP (%2d:%02d:%02d.[%02d]) closed_gop=%d broken_link=%d\n",
2163             time_code_hours, time_code_minutes, time_code_seconds,
2164             time_code_pictures, s->closed_gop, broken_link);
2165 }
2166 /**
2167  * Finds the end of the current frame in the bitstream.
2168  * @return the position of the first byte of the next frame, or -1
2169  */
2170 int ff_mpeg1_find_frame_end(ParseContext *pc, const uint8_t *buf, int buf_size, AVCodecParserContext *s)
2171 {
2172     int i;
2173     uint32_t state= pc->state;
2174
2175     /* EOF considered as end of frame */
2176     if (buf_size == 0)
2177         return 0;
2178
2179 /*
2180  0  frame start         -> 1/4
2181  1  first_SEQEXT        -> 0/2
2182  2  first field start   -> 3/0
2183  3  second_SEQEXT       -> 2/0
2184  4  searching end
2185 */
2186
2187     for(i=0; i<buf_size; i++){
2188         assert(pc->frame_start_found>=0 && pc->frame_start_found<=4);
2189         if(pc->frame_start_found&1){
2190             if(state == EXT_START_CODE && (buf[i]&0xF0) != 0x80)
2191                 pc->frame_start_found--;
2192             else if(state == EXT_START_CODE+2){
2193                 if((buf[i]&3) == 3) pc->frame_start_found= 0;
2194                 else                pc->frame_start_found= (pc->frame_start_found+1)&3;
2195             }
2196             state++;
2197         }else{
2198             i= ff_find_start_code(buf+i, buf+buf_size, &state) - buf - 1;
2199             if(pc->frame_start_found==0 && state >= SLICE_MIN_START_CODE && state <= SLICE_MAX_START_CODE){
2200                 i++;
2201                 pc->frame_start_found=4;
2202             }
2203             if(state == SEQ_END_CODE){
2204                 pc->state=-1;
2205                 return i+1;
2206             }
2207             if(pc->frame_start_found==2 && state == SEQ_START_CODE)
2208                 pc->frame_start_found= 0;
2209             if(pc->frame_start_found<4 && state == EXT_START_CODE)
2210                 pc->frame_start_found++;
2211             if(pc->frame_start_found == 4 && (state&0xFFFFFF00) == 0x100){
2212                 if(state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE){
2213                     pc->frame_start_found=0;
2214                     pc->state=-1;
2215                     return i-3;
2216                 }
2217             }
2218             if(s && state == PICTURE_START_CODE){
2219                 ff_fetch_timestamp(s, i-4, 1);
2220             }
2221         }
2222     }
2223     pc->state= state;
2224     return END_NOT_FOUND;
2225 }
2226
2227 static int decode_chunks(AVCodecContext *avctx,
2228                              AVFrame *picture, int *data_size,
2229                              const uint8_t *buf, int buf_size);
2230
2231 /* handle buffering and image synchronisation */
2232 static int mpeg_decode_frame(AVCodecContext *avctx,
2233                              void *data, int *data_size,
2234                              AVPacket *avpkt)
2235 {
2236     const uint8_t *buf = avpkt->data;
2237     int buf_size = avpkt->size;
2238     Mpeg1Context *s = avctx->priv_data;
2239     AVFrame *picture = data;
2240     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2241     dprintf(avctx, "fill_buffer\n");
2242
2243     if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {
2244         /* special case for last picture */
2245         if (s2->low_delay==0 && s2->next_picture_ptr) {
2246             *picture= *(AVFrame*)s2->next_picture_ptr;
2247             s2->next_picture_ptr= NULL;
2248
2249             *data_size = sizeof(AVFrame);
2250         }
2251         return buf_size;
2252     }
2253
2254     if(s2->flags&CODEC_FLAG_TRUNCATED){
2255         int next= ff_mpeg1_find_frame_end(&s2->parse_context, buf, buf_size, NULL);
2256
2257         if( ff_combine_frame(&s2->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0 )
2258             return buf_size;
2259     }
2260
2261 #if 0
2262     if (s->repeat_field % 2 == 1) {
2263         s->repeat_field++;
2264         //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
2265         //        s2->picture_number, s->repeat_field);
2266         if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
2267             *data_size = sizeof(AVPicture);
2268             goto the_end;
2269         }
2270     }
2271 #endif
2272
2273     if(s->mpeg_enc_ctx_allocated==0 && avctx->codec_tag == AV_RL32("VCR2"))
2274         vcr2_init_sequence(avctx);
2275
2276     s->slice_count= 0;
2277
2278     if(avctx->extradata && !avctx->frame_number)
2279         decode_chunks(avctx, picture, data_size, avctx->extradata, avctx->extradata_size);
2280
2281     return decode_chunks(avctx, picture, data_size, buf, buf_size);
2282 }
2283
2284 static int decode_chunks(AVCodecContext *avctx,
2285                              AVFrame *picture, int *data_size,
2286                              const uint8_t *buf, int buf_size)
2287 {
2288     Mpeg1Context *s = avctx->priv_data;
2289     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2290     const uint8_t *buf_ptr = buf;
2291     const uint8_t *buf_end = buf + buf_size;
2292     int ret, input_size;
2293
2294     for(;;) {
2295         /* find next start code */
2296         uint32_t start_code = -1;
2297         buf_ptr = ff_find_start_code(buf_ptr,buf_end, &start_code);
2298         if (start_code > 0x1ff){
2299             if(s2->pict_type != FF_B_TYPE || avctx->skip_frame <= AVDISCARD_DEFAULT){
2300                 if(avctx->thread_count > 1){
2301                     int i;
2302
2303                     avctx->execute(avctx, slice_decode_thread,  (void**)&(s2->thread_context[0]), NULL, s->slice_count, sizeof(void*));
2304                     for(i=0; i<s->slice_count; i++)
2305                         s2->error_count += s2->thread_context[i]->error_count;
2306                 }
2307
2308                 if (CONFIG_MPEG_VDPAU_DECODER && avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2309                     ff_vdpau_mpeg_picture_complete(s2, buf, buf_size, s->slice_count);
2310
2311                 if (slice_end(avctx, picture)) {
2312                     if(s2->last_picture_ptr || s2->low_delay) //FIXME merge with the stuff in mpeg_decode_slice
2313                         *data_size = sizeof(AVPicture);
2314                 }
2315             }
2316             s2->pict_type= 0;
2317             return FFMAX(0, buf_ptr - buf - s2->parse_context.last_index);
2318         }
2319
2320         input_size = buf_end - buf_ptr;
2321
2322         if(avctx->debug & FF_DEBUG_STARTCODE){
2323             av_log(avctx, AV_LOG_DEBUG, "%3X at %td left %d\n", start_code, buf_ptr-buf, input_size);
2324         }
2325
2326         /* prepare data for next start code */
2327         switch(start_code) {
2328         case SEQ_START_CODE:
2329             mpeg1_decode_sequence(avctx, buf_ptr,
2330                                     input_size);
2331             break;
2332
2333         case PICTURE_START_CODE:
2334             /* we have a complete image: we try to decompress it */
2335             if(mpeg1_decode_picture(avctx,
2336                                     buf_ptr, input_size) < 0)
2337                 s2->pict_type=0;
2338             break;
2339         case EXT_START_CODE:
2340             mpeg_decode_extension(avctx,
2341                                     buf_ptr, input_size);
2342             break;
2343         case USER_START_CODE:
2344             mpeg_decode_user_data(avctx,
2345                                     buf_ptr, input_size);
2346             break;
2347         case GOP_START_CODE:
2348             s2->first_field=0;
2349             mpeg_decode_gop(avctx,
2350                                     buf_ptr, input_size);
2351             break;
2352         default:
2353             if (start_code >= SLICE_MIN_START_CODE &&
2354                 start_code <= SLICE_MAX_START_CODE) {
2355                 int mb_y= start_code - SLICE_MIN_START_CODE;
2356
2357                 if(s2->last_picture_ptr==NULL){
2358                 /* Skip B-frames if we do not have reference frames and gop is not closed */
2359                     if(s2->pict_type==FF_B_TYPE){
2360                         int i;
2361                         if(!s2->closed_gop)
2362                             break;
2363                         /* Allocate a dummy frame */
2364                         i= ff_find_unused_picture(s2, 0);
2365                         s2->last_picture_ptr= &s2->picture[i];
2366                         if(alloc_picture(s2, s2->last_picture_ptr, 0) < 0)
2367                             return -1;
2368                     }
2369                 }
2370                 if(s2->next_picture_ptr==NULL){
2371                 /* Skip P-frames if we do not have a reference frame or we have an invalid header. */
2372                     if(s2->pict_type==FF_P_TYPE && (s2->first_field || s2->picture_structure==PICT_FRAME)) break;
2373                 }
2374                 /* Skip B-frames if we are in a hurry. */
2375                 if(avctx->hurry_up && s2->pict_type==FF_B_TYPE) break;
2376                 if(  (avctx->skip_frame >= AVDISCARD_NONREF && s2->pict_type==FF_B_TYPE)
2377                     ||(avctx->skip_frame >= AVDISCARD_NONKEY && s2->pict_type!=FF_I_TYPE)
2378                     || avctx->skip_frame >= AVDISCARD_ALL)
2379                     break;
2380                 /* Skip everything if we are in a hurry>=5. */
2381                 if(avctx->hurry_up>=5) break;
2382
2383                 if (!s->mpeg_enc_ctx_allocated) break;
2384
2385                 if(s2->codec_id == CODEC_ID_MPEG2VIDEO){
2386                     if(mb_y < avctx->skip_top || mb_y >= s2->mb_height - avctx->skip_bottom)
2387                         break;
2388                 }
2389
2390                 if(!s2->pict_type){
2391                     av_log(avctx, AV_LOG_ERROR, "Missing picture start code\n");
2392                     break;
2393                 }
2394
2395                 if(s2->first_slice){
2396                     s2->first_slice=0;
2397                     if(mpeg_field_start(s2, buf, buf_size) < 0)
2398                         return -1;
2399                 }
2400                 if(!s2->current_picture_ptr){
2401                     av_log(avctx, AV_LOG_ERROR, "current_picture not initialized\n");
2402                     return -1;
2403                 }
2404
2405                 if (avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU) {
2406                     s->slice_count++;
2407                     break;
2408                 }
2409
2410                 if(avctx->thread_count > 1){
2411                     int threshold= (s2->mb_height*s->slice_count + avctx->thread_count/2) / avctx->thread_count;
2412                     if(threshold <= mb_y){
2413                         MpegEncContext *thread_context= s2->thread_context[s->slice_count];
2414
2415                         thread_context->start_mb_y= mb_y;
2416                         thread_context->end_mb_y  = s2->mb_height;
2417                         if(s->slice_count){
2418                             s2->thread_context[s->slice_count-1]->end_mb_y= mb_y;
2419                             ff_update_duplicate_context(thread_context, s2);
2420                         }
2421                         init_get_bits(&thread_context->gb, buf_ptr, input_size*8);
2422                         s->slice_count++;
2423                     }
2424                     buf_ptr += 2; //FIXME add minimum number of bytes per slice
2425                 }else{
2426                     ret = mpeg_decode_slice(s, mb_y, &buf_ptr, input_size);
2427                     emms_c();
2428
2429                     if(ret < 0){
2430                         if(s2->resync_mb_x>=0 && s2->resync_mb_y>=0)
2431                             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);
2432                     }else{
2433                         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);
2434                     }
2435                 }
2436             }
2437             break;
2438         }
2439     }
2440 }
2441
2442 static int mpeg_decode_end(AVCodecContext *avctx)
2443 {
2444     Mpeg1Context *s = avctx->priv_data;
2445
2446     if (s->mpeg_enc_ctx_allocated)
2447         MPV_common_end(&s->mpeg_enc_ctx);
2448     return 0;
2449 }
2450
2451 AVCodec mpeg1video_decoder = {
2452     "mpeg1video",
2453     CODEC_TYPE_VIDEO,
2454     CODEC_ID_MPEG1VIDEO,
2455     sizeof(Mpeg1Context),
2456     mpeg_decode_init,
2457     NULL,
2458     mpeg_decode_end,
2459     mpeg_decode_frame,
2460     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
2461     .flush= ff_mpeg_flush,
2462     .long_name= NULL_IF_CONFIG_SMALL("MPEG-1 video"),
2463 };
2464
2465 AVCodec mpeg2video_decoder = {
2466     "mpeg2video",
2467     CODEC_TYPE_VIDEO,
2468     CODEC_ID_MPEG2VIDEO,
2469     sizeof(Mpeg1Context),
2470     mpeg_decode_init,
2471     NULL,
2472     mpeg_decode_end,
2473     mpeg_decode_frame,
2474     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
2475     .flush= ff_mpeg_flush,
2476     .long_name= NULL_IF_CONFIG_SMALL("MPEG-2 video"),
2477 };
2478
2479 //legacy decoder
2480 AVCodec mpegvideo_decoder = {
2481     "mpegvideo",
2482     CODEC_TYPE_VIDEO,
2483     CODEC_ID_MPEG2VIDEO,
2484     sizeof(Mpeg1Context),
2485     mpeg_decode_init,
2486     NULL,
2487     mpeg_decode_end,
2488     mpeg_decode_frame,
2489     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
2490     .flush= ff_mpeg_flush,
2491     .long_name= NULL_IF_CONFIG_SMALL("MPEG-1 video"),
2492 };
2493
2494 #if CONFIG_MPEG_XVMC_DECODER
2495 static av_cold int mpeg_mc_decode_init(AVCodecContext *avctx){
2496     if( avctx->thread_count > 1)
2497         return -1;
2498     if( !(avctx->slice_flags & SLICE_FLAG_CODED_ORDER) )
2499         return -1;
2500     if( !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD) ){
2501         dprintf(avctx, "mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");
2502     }
2503     mpeg_decode_init(avctx);
2504
2505     avctx->pix_fmt = PIX_FMT_XVMC_MPEG2_IDCT;
2506     avctx->xvmc_acceleration = 2;//2 - the blocks are packed!
2507
2508     return 0;
2509 }
2510
2511 AVCodec mpeg_xvmc_decoder = {
2512     "mpegvideo_xvmc",
2513     CODEC_TYPE_VIDEO,
2514     CODEC_ID_MPEG2VIDEO_XVMC,
2515     sizeof(Mpeg1Context),
2516     mpeg_mc_decode_init,
2517     NULL,
2518     mpeg_decode_end,
2519     mpeg_decode_frame,
2520     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED| CODEC_CAP_HWACCEL | CODEC_CAP_DELAY,
2521     .flush= ff_mpeg_flush,
2522     .long_name = NULL_IF_CONFIG_SMALL("MPEG-1/2 video XvMC (X-Video Motion Compensation)"),
2523 };
2524
2525 #endif
2526
2527 #if CONFIG_MPEG_VDPAU_DECODER
2528 AVCodec mpeg_vdpau_decoder = {
2529     "mpegvideo_vdpau",
2530     CODEC_TYPE_VIDEO,
2531     CODEC_ID_MPEG2VIDEO,
2532     sizeof(Mpeg1Context),
2533     mpeg_decode_init,
2534     NULL,
2535     mpeg_decode_end,
2536     mpeg_decode_frame,
2537     CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_HWACCEL_VDPAU | CODEC_CAP_DELAY,
2538     .flush= ff_mpeg_flush,
2539     .long_name = NULL_IF_CONFIG_SMALL("MPEG-1/2 video (VDPAU acceleration)"),
2540 };
2541 #endif
2542
2543 #if CONFIG_MPEG1_VDPAU_DECODER
2544 AVCodec mpeg1_vdpau_decoder = {
2545     "mpeg1video_vdpau",
2546     CODEC_TYPE_VIDEO,
2547     CODEC_ID_MPEG1VIDEO,
2548     sizeof(Mpeg1Context),
2549     mpeg_decode_init,
2550     NULL,
2551     mpeg_decode_end,
2552     mpeg_decode_frame,
2553     CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_HWACCEL_VDPAU | CODEC_CAP_DELAY,
2554     .flush= ff_mpeg_flush,
2555     .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 video (VDPAU acceleration)"),
2556 };
2557 #endif
2558