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