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