]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpeg12.c
add MPEG-2 intra vlc support
[ffmpeg] / libavcodec / mpeg12.c
1 /*
2  * MPEG1 codec / MPEG2 decoder
3  * Copyright (c) 2000,2001 Fabrice Bellard.
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file mpeg12.c
23  * MPEG1/2 codec
24  */
25
26 //#define DEBUG
27 #include "avcodec.h"
28 #include "dsputil.h"
29 #include "mpegvideo.h"
30
31 #include "mpeg12data.h"
32
33 //#undef NDEBUG
34 //#include <assert.h>
35
36
37 /* Start codes. */
38 #define SEQ_END_CODE            0x000001b7
39 #define SEQ_START_CODE          0x000001b3
40 #define GOP_START_CODE          0x000001b8
41 #define PICTURE_START_CODE      0x00000100
42 #define SLICE_MIN_START_CODE    0x00000101
43 #define SLICE_MAX_START_CODE    0x000001af
44 #define EXT_START_CODE          0x000001b5
45 #define USER_START_CODE         0x000001b2
46
47 #define DC_VLC_BITS 9
48 #define MV_VLC_BITS 9
49 #define MBINCR_VLC_BITS 9
50 #define MB_PAT_VLC_BITS 9
51 #define MB_PTYPE_VLC_BITS 6
52 #define MB_BTYPE_VLC_BITS 6
53 #define TEX_VLC_BITS 9
54
55 #ifdef CONFIG_ENCODERS
56 static void mpeg1_encode_block(MpegEncContext *s,
57                          DCTELEM *block,
58                          int component);
59 static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code);    // RAL: f_code parameter added
60 #endif //CONFIG_ENCODERS
61 static inline int mpeg1_decode_block_inter(MpegEncContext *s,
62                               DCTELEM *block,
63                               int n);
64 static inline int mpeg1_decode_block_intra(MpegEncContext *s,
65                               DCTELEM *block,
66                               int n);
67 static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s, DCTELEM *block, int n);
68 static inline int mpeg2_decode_block_non_intra(MpegEncContext *s,
69                                         DCTELEM *block,
70                                         int n);
71 static inline int mpeg2_decode_block_intra(MpegEncContext *s,
72                                     DCTELEM *block,
73                                     int n);
74 static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s, DCTELEM *block, int n);
75 static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s, DCTELEM *block, int n);
76 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred);
77 static void exchange_uv(MpegEncContext *s);
78
79 #ifdef HAVE_XVMC
80 extern int XVMC_field_start(MpegEncContext *s, AVCodecContext *avctx);
81 extern int XVMC_field_end(MpegEncContext *s);
82 extern void XVMC_pack_pblocks(MpegEncContext *s,int cbp);
83 extern void XVMC_init_block(MpegEncContext *s);//set s->block
84 #endif
85
86 const enum PixelFormat pixfmt_yuv_420[]= {PIX_FMT_YUV420P,-1};
87 const enum PixelFormat pixfmt_yuv_422[]= {PIX_FMT_YUV422P,-1};
88 const enum PixelFormat pixfmt_yuv_444[]= {PIX_FMT_YUV444P,-1};
89 const enum PixelFormat pixfmt_xvmc_mpg2_420[] = {
90                                            PIX_FMT_XVMC_MPEG2_IDCT,
91                                            PIX_FMT_XVMC_MPEG2_MC,
92                                            -1};
93 #ifdef CONFIG_ENCODERS
94 static uint8_t (*mv_penalty)[MAX_MV*2+1]= NULL;
95 static uint8_t fcode_tab[MAX_MV*2+1];
96
97 static uint8_t  uni_mpeg1_ac_vlc_len [64*64*2];
98 static uint8_t  uni_mpeg2_ac_vlc_len [64*64*2];
99
100 /* simple include everything table for dc, first byte is bits number next 3 are code*/
101 static uint32_t mpeg1_lum_dc_uni[512];
102 static uint32_t mpeg1_chr_dc_uni[512];
103
104 static uint8_t mpeg1_index_run[2][64];
105 static int8_t mpeg1_max_level[2][64];
106 #endif //CONFIG_ENCODERS
107
108 static void init_2d_vlc_rl(RLTable *rl, int use_static)
109 {
110     int i;
111
112     init_vlc(&rl->vlc, TEX_VLC_BITS, rl->n + 2,
113              &rl->table_vlc[0][1], 4, 2,
114              &rl->table_vlc[0][0], 4, 2, use_static);
115
116     if(use_static)
117         rl->rl_vlc[0]= av_mallocz_static(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
118     else
119         rl->rl_vlc[0]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
120
121     for(i=0; i<rl->vlc.table_size; i++){
122         int code= rl->vlc.table[i][0];
123         int len = rl->vlc.table[i][1];
124         int level, run;
125
126         if(len==0){ // illegal code
127             run= 65;
128             level= MAX_LEVEL;
129         }else if(len<0){ //more bits needed
130             run= 0;
131             level= code;
132         }else{
133             if(code==rl->n){ //esc
134                 run= 65;
135                 level= 0;
136             }else if(code==rl->n+1){ //eob
137                 run= 0;
138                 level= 127;
139             }else{
140                 run=   rl->table_run  [code] + 1;
141                 level= rl->table_level[code];
142             }
143         }
144         rl->rl_vlc[0][i].len= len;
145         rl->rl_vlc[0][i].level= level;
146         rl->rl_vlc[0][i].run= run;
147     }
148 }
149
150 #ifdef CONFIG_ENCODERS
151 static void init_uni_ac_vlc(RLTable *rl, uint8_t *uni_ac_vlc_len){
152     int i;
153
154     for(i=0; i<128; i++){
155         int level= i-64;
156         int run;
157         for(run=0; run<64; run++){
158             int len, bits, code;
159
160             int alevel= ABS(level);
161             int sign= (level>>31)&1;
162
163             if (alevel > rl->max_level[0][run])
164                 code= 111; /*rl->n*/
165             else
166                 code= rl->index_run[0][run] + alevel - 1;
167
168             if (code < 111 /* rl->n */) {
169                 /* store the vlc & sign at once */
170                 len=   rl->table_vlc[code][1]+1;
171                 bits= (rl->table_vlc[code][0]<<1) + sign;
172             } else {
173                 len=  rl->table_vlc[111/*rl->n*/][1]+6;
174                 bits= rl->table_vlc[111/*rl->n*/][0]<<6;
175
176                 bits|= run;
177                 if (alevel < 128) {
178                     bits<<=8; len+=8;
179                     bits|= level & 0xff;
180                 } else {
181                     bits<<=16; len+=16;
182                     bits|= level & 0xff;
183                     if (level < 0) {
184                         bits|= 0x8001 + level + 255;
185                     } else {
186                         bits|= level & 0xffff;
187                     }
188                 }
189             }
190
191             uni_ac_vlc_len [UNI_AC_ENC_INDEX(run, i)]= len;
192         }
193     }
194 }
195
196
197 static int find_frame_rate_index(MpegEncContext *s){
198     int i;
199     int64_t dmin= INT64_MAX;
200     int64_t d;
201
202     for(i=1;i<14;i++) {
203         int64_t n0= 1001LL/frame_rate_tab[i].den*frame_rate_tab[i].num*s->avctx->time_base.num;
204         int64_t n1= 1001LL*s->avctx->time_base.den;
205         if(s->avctx->strict_std_compliance > FF_COMPLIANCE_INOFFICIAL && i>=9) break;
206
207         d = ABS(n0 - n1);
208         if(d < dmin){
209             dmin=d;
210             s->frame_rate_index= i;
211         }
212     }
213     if(dmin)
214         return -1;
215     else
216         return 0;
217 }
218
219 static int encode_init(AVCodecContext *avctx)
220 {
221     MpegEncContext *s = avctx->priv_data;
222
223     if(MPV_encode_init(avctx) < 0)
224         return -1;
225
226     if(find_frame_rate_index(s) < 0){
227         if(s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL){
228             av_log(avctx, AV_LOG_ERROR, "MPEG1/2 does not support %d/%d fps\n", avctx->time_base.den, avctx->time_base.num);
229             return -1;
230         }else{
231             av_log(avctx, AV_LOG_INFO, "MPEG1/2 does not support %d/%d fps, there may be AV sync issues\n", avctx->time_base.den, avctx->time_base.num);
232         }
233     }
234
235     return 0;
236 }
237
238 static void put_header(MpegEncContext *s, int header)
239 {
240     align_put_bits(&s->pb);
241     put_bits(&s->pb, 16, header>>16);
242     put_bits(&s->pb, 16, header&0xFFFF);
243 }
244
245 /* put sequence header if needed */
246 static void mpeg1_encode_sequence_header(MpegEncContext *s)
247 {
248         unsigned int vbv_buffer_size;
249         unsigned int fps, v;
250         int i;
251         uint64_t time_code;
252         float best_aspect_error= 1E10;
253         float aspect_ratio= av_q2d(s->avctx->sample_aspect_ratio);
254         int constraint_parameter_flag;
255
256         if(aspect_ratio==0.0) aspect_ratio= 1.0; //pixel aspect 1:1 (VGA)
257
258         if (s->current_picture.key_frame) {
259             AVRational framerate= frame_rate_tab[s->frame_rate_index];
260
261             /* mpeg1 header repeated every gop */
262             put_header(s, SEQ_START_CODE);
263
264             put_bits(&s->pb, 12, s->width);
265             put_bits(&s->pb, 12, s->height);
266
267             for(i=1; i<15; i++){
268                 float error= aspect_ratio;
269                 if(s->codec_id == CODEC_ID_MPEG1VIDEO || i <=1)
270                     error-= 1.0/mpeg1_aspect[i];
271                 else
272                     error-= av_q2d(mpeg2_aspect[i])*s->height/s->width;
273
274                 error= ABS(error);
275
276                 if(error < best_aspect_error){
277                     best_aspect_error= error;
278                     s->aspect_ratio_info= i;
279                 }
280             }
281
282             put_bits(&s->pb, 4, s->aspect_ratio_info);
283             put_bits(&s->pb, 4, s->frame_rate_index);
284
285             if(s->avctx->rc_max_rate){
286                 v = (s->avctx->rc_max_rate + 399) / 400;
287                 if (v > 0x3ffff && s->codec_id == CODEC_ID_MPEG1VIDEO)
288                     v = 0x3ffff;
289             }else{
290                 v= 0x3FFFF;
291             }
292
293             if(s->avctx->rc_buffer_size)
294                 vbv_buffer_size = s->avctx->rc_buffer_size;
295             else
296                 /* VBV calculation: Scaled so that a VCD has the proper VBV size of 40 kilobytes */
297                 vbv_buffer_size = (( 20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;
298             vbv_buffer_size= (vbv_buffer_size + 16383) / 16384;
299
300             put_bits(&s->pb, 18, v & 0x3FFFF);
301             put_bits(&s->pb, 1, 1); /* marker */
302             put_bits(&s->pb, 10, vbv_buffer_size & 0x3FF);
303
304             constraint_parameter_flag=
305                 s->width <= 768 && s->height <= 576 &&
306                 s->mb_width * s->mb_height <= 396 &&
307                 s->mb_width * s->mb_height * framerate.num <= framerate.den*396*25 &&
308                 framerate.num <= framerate.den*30 &&
309                 s->avctx->me_range && s->avctx->me_range < 128 &&
310                 vbv_buffer_size <= 20 &&
311                 v <= 1856000/400 &&
312                 s->codec_id == CODEC_ID_MPEG1VIDEO;
313
314             put_bits(&s->pb, 1, constraint_parameter_flag);
315
316             ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
317             ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
318
319             if(s->codec_id == CODEC_ID_MPEG2VIDEO){
320                 put_header(s, EXT_START_CODE);
321                 put_bits(&s->pb, 4, 1); //seq ext
322                 put_bits(&s->pb, 1, 0); //esc
323
324                 if(s->avctx->profile == FF_PROFILE_UNKNOWN){
325                     put_bits(&s->pb, 3, 4); //profile
326                 }else{
327                     put_bits(&s->pb, 3, s->avctx->profile); //profile
328                 }
329
330                 if(s->avctx->level == FF_LEVEL_UNKNOWN){
331                     put_bits(&s->pb, 4, 8); //level
332                 }else{
333                     put_bits(&s->pb, 4, s->avctx->level); //level
334                 }
335
336                 put_bits(&s->pb, 1, s->progressive_sequence);
337                 put_bits(&s->pb, 2, 1); //chroma format 4:2:0
338                 put_bits(&s->pb, 2, 0); //horizontal size ext
339                 put_bits(&s->pb, 2, 0); //vertical size ext
340                 put_bits(&s->pb, 12, v>>18); //bitrate ext
341                 put_bits(&s->pb, 1, 1); //marker
342                 put_bits(&s->pb, 8, vbv_buffer_size >>10); //vbv buffer ext
343                 put_bits(&s->pb, 1, s->low_delay);
344                 put_bits(&s->pb, 2, 0); // frame_rate_ext_n
345                 put_bits(&s->pb, 5, 0); // frame_rate_ext_d
346             }
347
348             put_header(s, GOP_START_CODE);
349             put_bits(&s->pb, 1, 0); /* do drop frame */
350             /* time code : we must convert from the real frame rate to a
351                fake mpeg frame rate in case of low frame rate */
352             fps = (framerate.num + framerate.den/2)/ framerate.den;
353             time_code = s->current_picture_ptr->coded_picture_number;
354
355             s->gop_picture_number = time_code;
356             put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));
357             put_bits(&s->pb, 6, (uint32_t)((time_code / (fps * 60)) % 60));
358             put_bits(&s->pb, 1, 1);
359             put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));
360             put_bits(&s->pb, 6, (uint32_t)((time_code % fps)));
361             put_bits(&s->pb, 1, !!(s->flags & CODEC_FLAG_CLOSED_GOP));
362             put_bits(&s->pb, 1, 0); /* broken link */
363         }
364 }
365
366 static inline void encode_mb_skip_run(MpegEncContext *s, int run){
367     while (run >= 33) {
368         put_bits(&s->pb, 11, 0x008);
369         run -= 33;
370     }
371     put_bits(&s->pb, mbAddrIncrTable[run][1],
372              mbAddrIncrTable[run][0]);
373 }
374 #endif //CONFIG_ENCODERS
375
376 static void common_init(MpegEncContext *s)
377 {
378
379     s->y_dc_scale_table=
380     s->c_dc_scale_table= mpeg2_dc_scale_table[s->intra_dc_precision];
381
382 }
383
384 void ff_mpeg1_clean_buffers(MpegEncContext *s){
385     s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
386     s->last_dc[1] = s->last_dc[0];
387     s->last_dc[2] = s->last_dc[0];
388     memset(s->last_mv, 0, sizeof(s->last_mv));
389 }
390
391 #ifdef CONFIG_ENCODERS
392
393 void ff_mpeg1_encode_slice_header(MpegEncContext *s){
394     put_header(s, SLICE_MIN_START_CODE + s->mb_y);
395     put_bits(&s->pb, 5, s->qscale); /* quantizer scale */
396     put_bits(&s->pb, 1, 0); /* slice extra information */
397 }
398
399 void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
400 {
401     mpeg1_encode_sequence_header(s);
402
403     /* mpeg1 picture header */
404     put_header(s, PICTURE_START_CODE);
405     /* temporal reference */
406
407     // RAL: s->picture_number instead of s->fake_picture_number
408     put_bits(&s->pb, 10, (s->picture_number -
409                           s->gop_picture_number) & 0x3ff);
410     put_bits(&s->pb, 3, s->pict_type);
411
412     s->vbv_delay_ptr= s->pb.buf + put_bits_count(&s->pb)/8;
413     put_bits(&s->pb, 16, 0xFFFF); /* vbv_delay */
414
415     // RAL: Forward f_code also needed for B frames
416     if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
417         put_bits(&s->pb, 1, 0); /* half pel coordinates */
418         if(s->codec_id == CODEC_ID_MPEG1VIDEO)
419             put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
420         else
421             put_bits(&s->pb, 3, 7); /* forward_f_code */
422     }
423
424     // RAL: Backward f_code necessary for B frames
425     if (s->pict_type == B_TYPE) {
426         put_bits(&s->pb, 1, 0); /* half pel coordinates */
427         if(s->codec_id == CODEC_ID_MPEG1VIDEO)
428             put_bits(&s->pb, 3, s->b_code); /* backward_f_code */
429         else
430             put_bits(&s->pb, 3, 7); /* backward_f_code */
431     }
432
433     put_bits(&s->pb, 1, 0); /* extra bit picture */
434
435     s->frame_pred_frame_dct = 1;
436     if(s->codec_id == CODEC_ID_MPEG2VIDEO){
437         put_header(s, EXT_START_CODE);
438         put_bits(&s->pb, 4, 8); //pic ext
439         if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
440             put_bits(&s->pb, 4, s->f_code);
441             put_bits(&s->pb, 4, s->f_code);
442         }else{
443             put_bits(&s->pb, 8, 255);
444         }
445         if (s->pict_type == B_TYPE) {
446             put_bits(&s->pb, 4, s->b_code);
447             put_bits(&s->pb, 4, s->b_code);
448         }else{
449             put_bits(&s->pb, 8, 255);
450         }
451         put_bits(&s->pb, 2, s->intra_dc_precision);
452
453         assert(s->picture_structure == PICT_FRAME);
454         put_bits(&s->pb, 2, s->picture_structure);
455         if (s->progressive_sequence) {
456             put_bits(&s->pb, 1, 0); /* no repeat */
457         } else {
458             put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
459         }
460         /* XXX: optimize the generation of this flag with entropy
461            measures */
462         s->frame_pred_frame_dct = s->progressive_sequence;
463
464         put_bits(&s->pb, 1, s->frame_pred_frame_dct);
465         put_bits(&s->pb, 1, s->concealment_motion_vectors);
466         put_bits(&s->pb, 1, s->q_scale_type);
467         put_bits(&s->pb, 1, s->intra_vlc_format);
468         put_bits(&s->pb, 1, s->alternate_scan);
469         put_bits(&s->pb, 1, s->repeat_first_field);
470         s->progressive_frame = s->progressive_sequence;
471         put_bits(&s->pb, 1, s->chroma_420_type=s->progressive_frame);
472         put_bits(&s->pb, 1, s->progressive_frame);
473         put_bits(&s->pb, 1, 0); //composite_display_flag
474     }
475     if(s->flags & CODEC_FLAG_SVCD_SCAN_OFFSET){
476         int i;
477
478         put_header(s, USER_START_CODE);
479         for(i=0; i<sizeof(svcd_scan_offset_placeholder); i++){
480             put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);
481         }
482     }
483
484     s->mb_y=0;
485     ff_mpeg1_encode_slice_header(s);
486 }
487
488 static inline void put_mb_modes(MpegEncContext *s, int n, int bits,
489                                 int has_mv, int field_motion)
490 {
491     put_bits(&s->pb, n, bits);
492     if (!s->frame_pred_frame_dct) {
493         if (has_mv)
494             put_bits(&s->pb, 2, 2 - field_motion); /* motion_type: frame/field */
495         put_bits(&s->pb, 1, s->interlaced_dct);
496     }
497 }
498
499 void mpeg1_encode_mb(MpegEncContext *s,
500                      DCTELEM block[6][64],
501                      int motion_x, int motion_y)
502 {
503     int i, cbp;
504     const int mb_x = s->mb_x;
505     const int mb_y = s->mb_y;
506     const int first_mb= mb_x == s->resync_mb_x && mb_y == s->resync_mb_y;
507
508     /* compute cbp */
509     cbp = 0;
510     for(i=0;i<6;i++) {
511         if (s->block_last_index[i] >= 0)
512             cbp |= 1 << (5 - i);
513     }
514
515     if (cbp == 0 && !first_mb && s->mv_type == MV_TYPE_16X16 &&
516         (mb_x != s->mb_width - 1 || (mb_y != s->mb_height - 1 && s->codec_id == CODEC_ID_MPEG1VIDEO)) &&
517         ((s->pict_type == P_TYPE && (motion_x | motion_y) == 0) ||
518         (s->pict_type == B_TYPE && s->mv_dir == s->last_mv_dir && (((s->mv_dir & MV_DIR_FORWARD) ? ((s->mv[0][0][0] - s->last_mv[0][0][0])|(s->mv[0][0][1] - s->last_mv[0][0][1])) : 0) |
519         ((s->mv_dir & MV_DIR_BACKWARD) ? ((s->mv[1][0][0] - s->last_mv[1][0][0])|(s->mv[1][0][1] - s->last_mv[1][0][1])) : 0)) == 0))) {
520         s->mb_skip_run++;
521         s->qscale -= s->dquant;
522         s->skip_count++;
523         s->misc_bits++;
524         s->last_bits++;
525         if(s->pict_type == P_TYPE){
526             s->last_mv[0][1][0]= s->last_mv[0][0][0]=
527             s->last_mv[0][1][1]= s->last_mv[0][0][1]= 0;
528         }
529     } else {
530         if(first_mb){
531             assert(s->mb_skip_run == 0);
532             encode_mb_skip_run(s, s->mb_x);
533         }else{
534             encode_mb_skip_run(s, s->mb_skip_run);
535         }
536
537         if (s->pict_type == I_TYPE) {
538             if(s->dquant && cbp){
539                 put_mb_modes(s, 2, 1, 0, 0); /* macroblock_type : macroblock_quant = 1 */
540                 put_bits(&s->pb, 5, s->qscale);
541             }else{
542                 put_mb_modes(s, 1, 1, 0, 0); /* macroblock_type : macroblock_quant = 0 */
543                 s->qscale -= s->dquant;
544             }
545             s->misc_bits+= get_bits_diff(s);
546             s->i_count++;
547         } else if (s->mb_intra) {
548             if(s->dquant && cbp){
549                 put_mb_modes(s, 6, 0x01, 0, 0);
550                 put_bits(&s->pb, 5, s->qscale);
551             }else{
552                 put_mb_modes(s, 5, 0x03, 0, 0);
553                 s->qscale -= s->dquant;
554             }
555             s->misc_bits+= get_bits_diff(s);
556             s->i_count++;
557             memset(s->last_mv, 0, sizeof(s->last_mv));
558         } else if (s->pict_type == P_TYPE) {
559             if(s->mv_type == MV_TYPE_16X16){
560                 if (cbp != 0) {
561                     if ((motion_x|motion_y) == 0) {
562                         if(s->dquant){
563                             put_mb_modes(s, 5, 1, 0, 0); /* macroblock_pattern & quant */
564                             put_bits(&s->pb, 5, s->qscale);
565                         }else{
566                             put_mb_modes(s, 2, 1, 0, 0); /* macroblock_pattern only */
567                         }
568                         s->misc_bits+= get_bits_diff(s);
569                     } else {
570                         if(s->dquant){
571                             put_mb_modes(s, 5, 2, 1, 0); /* motion + cbp */
572                             put_bits(&s->pb, 5, s->qscale);
573                         }else{
574                             put_mb_modes(s, 1, 1, 1, 0); /* motion + cbp */
575                         }
576                         s->misc_bits+= get_bits_diff(s);
577                         mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
578                         mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
579                         s->mv_bits+= get_bits_diff(s);
580                     }
581                 } else {
582                     put_bits(&s->pb, 3, 1); /* motion only */
583                     if (!s->frame_pred_frame_dct)
584                         put_bits(&s->pb, 2, 2); /* motion_type: frame */
585                     s->misc_bits+= get_bits_diff(s);
586                     mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
587                     mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
588                     s->qscale -= s->dquant;
589                     s->mv_bits+= get_bits_diff(s);
590                 }
591                 s->last_mv[0][1][0]= s->last_mv[0][0][0]= motion_x;
592                 s->last_mv[0][1][1]= s->last_mv[0][0][1]= motion_y;
593             }else{
594                 assert(!s->frame_pred_frame_dct && s->mv_type == MV_TYPE_FIELD);
595
596                 if (cbp) {
597                     if(s->dquant){
598                         put_mb_modes(s, 5, 2, 1, 1); /* motion + cbp */
599                         put_bits(&s->pb, 5, s->qscale);
600                     }else{
601                         put_mb_modes(s, 1, 1, 1, 1); /* motion + cbp */
602                     }
603                 } else {
604                     put_bits(&s->pb, 3, 1); /* motion only */
605                     put_bits(&s->pb, 2, 1); /* motion_type: field */
606                     s->qscale -= s->dquant;
607                 }
608                 s->misc_bits+= get_bits_diff(s);
609                 for(i=0; i<2; i++){
610                     put_bits(&s->pb, 1, s->field_select[0][i]);
611                     mpeg1_encode_motion(s, s->mv[0][i][0] -  s->last_mv[0][i][0]    , s->f_code);
612                     mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
613                     s->last_mv[0][i][0]=   s->mv[0][i][0];
614                     s->last_mv[0][i][1]= 2*s->mv[0][i][1];
615                 }
616                 s->mv_bits+= get_bits_diff(s);
617             }
618             if(cbp)
619                 put_bits(&s->pb, mbPatTable[cbp][1], mbPatTable[cbp][0]);
620             s->f_count++;
621         } else{
622             static const int mb_type_len[4]={0,3,4,2}; //bak,for,bi
623
624             if(s->mv_type == MV_TYPE_16X16){
625                 if (cbp){    // With coded bloc pattern
626                     if (s->dquant) {
627                         if(s->mv_dir == MV_DIR_FORWARD)
628                             put_mb_modes(s, 6, 3, 1, 0);
629                         else
630                             put_mb_modes(s, mb_type_len[s->mv_dir]+3, 2, 1, 0);
631                         put_bits(&s->pb, 5, s->qscale);
632                     } else {
633                         put_mb_modes(s, mb_type_len[s->mv_dir], 3, 1, 0);
634                     }
635                 }else{    // No coded bloc pattern
636                     put_bits(&s->pb, mb_type_len[s->mv_dir], 2);
637                     if (!s->frame_pred_frame_dct)
638                         put_bits(&s->pb, 2, 2); /* motion_type: frame */
639                     s->qscale -= s->dquant;
640                 }
641                 s->misc_bits += get_bits_diff(s);
642                 if (s->mv_dir&MV_DIR_FORWARD){
643                     mpeg1_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
644                     mpeg1_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
645                     s->last_mv[0][0][0]=s->last_mv[0][1][0]= s->mv[0][0][0];
646                     s->last_mv[0][0][1]=s->last_mv[0][1][1]= s->mv[0][0][1];
647                     s->f_count++;
648                 }
649                 if (s->mv_dir&MV_DIR_BACKWARD){
650                     mpeg1_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
651                     mpeg1_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
652                     s->last_mv[1][0][0]=s->last_mv[1][1][0]= s->mv[1][0][0];
653                     s->last_mv[1][0][1]=s->last_mv[1][1][1]= s->mv[1][0][1];
654                     s->b_count++;
655                 }
656             }else{
657                 assert(s->mv_type == MV_TYPE_FIELD);
658                 assert(!s->frame_pred_frame_dct);
659                 if (cbp){    // With coded bloc pattern
660                     if (s->dquant) {
661                         if(s->mv_dir == MV_DIR_FORWARD)
662                             put_mb_modes(s, 6, 3, 1, 1);
663                         else
664                             put_mb_modes(s, mb_type_len[s->mv_dir]+3, 2, 1, 1);
665                         put_bits(&s->pb, 5, s->qscale);
666                     } else {
667                         put_mb_modes(s, mb_type_len[s->mv_dir], 3, 1, 1);
668                     }
669                 }else{    // No coded bloc pattern
670                     put_bits(&s->pb, mb_type_len[s->mv_dir], 2);
671                     put_bits(&s->pb, 2, 1); /* motion_type: field */
672                     s->qscale -= s->dquant;
673                 }
674                 s->misc_bits += get_bits_diff(s);
675                 if (s->mv_dir&MV_DIR_FORWARD){
676                     for(i=0; i<2; i++){
677                         put_bits(&s->pb, 1, s->field_select[0][i]);
678                         mpeg1_encode_motion(s, s->mv[0][i][0] -  s->last_mv[0][i][0]    , s->f_code);
679                         mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
680                         s->last_mv[0][i][0]=   s->mv[0][i][0];
681                         s->last_mv[0][i][1]= 2*s->mv[0][i][1];
682                     }
683                     s->f_count++;
684                 }
685                 if (s->mv_dir&MV_DIR_BACKWARD){
686                     for(i=0; i<2; i++){
687                         put_bits(&s->pb, 1, s->field_select[1][i]);
688                         mpeg1_encode_motion(s, s->mv[1][i][0] -  s->last_mv[1][i][0]    , s->b_code);
689                         mpeg1_encode_motion(s, s->mv[1][i][1] - (s->last_mv[1][i][1]>>1), s->b_code);
690                         s->last_mv[1][i][0]=   s->mv[1][i][0];
691                         s->last_mv[1][i][1]= 2*s->mv[1][i][1];
692                     }
693                     s->b_count++;
694                 }
695             }
696             s->mv_bits += get_bits_diff(s);
697             if(cbp)
698                 put_bits(&s->pb, mbPatTable[cbp][1], mbPatTable[cbp][0]);
699         }
700         for(i=0;i<6;i++) {
701             if (cbp & (1 << (5 - i))) {
702                 mpeg1_encode_block(s, block[i], i);
703             }
704         }
705         s->mb_skip_run = 0;
706         if(s->mb_intra)
707             s->i_tex_bits+= get_bits_diff(s);
708         else
709             s->p_tex_bits+= get_bits_diff(s);
710     }
711 }
712
713 // RAL: Parameter added: f_or_b_code
714 static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code)
715 {
716     int code, bit_size, l, bits, range, sign;
717
718     if (val == 0) {
719         /* zero vector */
720         code = 0;
721         put_bits(&s->pb,
722                  mbMotionVectorTable[0][1],
723                  mbMotionVectorTable[0][0]);
724     } else {
725         bit_size = f_or_b_code - 1;
726         range = 1 << bit_size;
727         /* modulo encoding */
728         l= INT_BIT - 5 - bit_size;
729         val= (val<<l)>>l;
730
731         if (val >= 0) {
732             val--;
733             code = (val >> bit_size) + 1;
734             bits = val & (range - 1);
735             sign = 0;
736         } else {
737             val = -val;
738             val--;
739             code = (val >> bit_size) + 1;
740             bits = val & (range - 1);
741             sign = 1;
742         }
743
744         assert(code > 0 && code <= 16);
745
746         put_bits(&s->pb,
747                  mbMotionVectorTable[code][1],
748                  mbMotionVectorTable[code][0]);
749
750         put_bits(&s->pb, 1, sign);
751         if (bit_size > 0) {
752             put_bits(&s->pb, bit_size, bits);
753         }
754     }
755 }
756
757 void ff_mpeg1_encode_init(MpegEncContext *s)
758 {
759     static int done=0;
760
761     common_init(s);
762
763     if(!done){
764         int f_code;
765         int mv;
766         int i;
767
768         done=1;
769         init_rl(&rl_mpeg1, 1);
770         if(s->intra_vlc_format)
771             init_rl(&rl_mpeg2, 1);
772
773         for(i=0; i<64; i++)
774         {
775                 mpeg1_max_level[0][i]= rl_mpeg1.max_level[0][i];
776                 mpeg1_index_run[0][i]= rl_mpeg1.index_run[0][i];
777         }
778
779         init_uni_ac_vlc(&rl_mpeg1, uni_mpeg1_ac_vlc_len);
780         if(s->intra_vlc_format)
781             init_uni_ac_vlc(&rl_mpeg2, uni_mpeg2_ac_vlc_len);
782
783         /* build unified dc encoding tables */
784         for(i=-255; i<256; i++)
785         {
786                 int adiff, index;
787                 int bits, code;
788                 int diff=i;
789
790                 adiff = ABS(diff);
791                 if(diff<0) diff--;
792                 index = av_log2(2*adiff);
793
794                 bits= vlc_dc_lum_bits[index] + index;
795                 code= (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
796                 mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
797
798                 bits= vlc_dc_chroma_bits[index] + index;
799                 code= (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
800                 mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
801         }
802
803         mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
804
805         for(f_code=1; f_code<=MAX_FCODE; f_code++){
806             for(mv=-MAX_MV; mv<=MAX_MV; mv++){
807                 int len;
808
809                 if(mv==0) len= mbMotionVectorTable[0][1];
810                 else{
811                     int val, bit_size, range, code;
812
813                     bit_size = f_code - 1;
814                     range = 1 << bit_size;
815
816                     val=mv;
817                     if (val < 0)
818                         val = -val;
819                     val--;
820                     code = (val >> bit_size) + 1;
821                     if(code<17){
822                         len= mbMotionVectorTable[code][1] + 1 + bit_size;
823                     }else{
824                         len= mbMotionVectorTable[16][1] + 2 + bit_size;
825                     }
826                 }
827
828                 mv_penalty[f_code][mv+MAX_MV]= len;
829             }
830         }
831
832
833         for(f_code=MAX_FCODE; f_code>0; f_code--){
834             for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
835                 fcode_tab[mv+MAX_MV]= f_code;
836             }
837         }
838     }
839     s->me.mv_penalty= mv_penalty;
840     s->fcode_tab= fcode_tab;
841     if(s->codec_id == CODEC_ID_MPEG1VIDEO){
842         s->min_qcoeff=-255;
843         s->max_qcoeff= 255;
844     }else{
845         s->min_qcoeff=-2047;
846         s->max_qcoeff= 2047;
847     }
848     if (s->intra_vlc_format) {
849         s->intra_ac_vlc_length=
850         s->intra_ac_vlc_last_length= uni_mpeg2_ac_vlc_len;
851     } else {
852         s->intra_ac_vlc_length=
853         s->intra_ac_vlc_last_length= uni_mpeg1_ac_vlc_len;
854     }
855     s->inter_ac_vlc_length=
856     s->inter_ac_vlc_last_length= uni_mpeg1_ac_vlc_len;
857 }
858
859 static inline void encode_dc(MpegEncContext *s, int diff, int component)
860 {
861   if(((unsigned) (diff+255)) >= 511){
862         int index;
863
864         if(diff<0){
865             index= av_log2_16bit(-2*diff);
866             diff--;
867         }else{
868             index= av_log2_16bit(2*diff);
869         }
870         if (component == 0) {
871             put_bits(
872                 &s->pb,
873                 vlc_dc_lum_bits[index] + index,
874                 (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1)));
875         }else{
876             put_bits(
877                 &s->pb,
878                 vlc_dc_chroma_bits[index] + index,
879                 (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1)));
880         }
881   }else{
882     if (component == 0) {
883         put_bits(
884             &s->pb,
885             mpeg1_lum_dc_uni[diff+255]&0xFF,
886             mpeg1_lum_dc_uni[diff+255]>>8);
887     } else {
888         put_bits(
889             &s->pb,
890             mpeg1_chr_dc_uni[diff+255]&0xFF,
891             mpeg1_chr_dc_uni[diff+255]>>8);
892     }
893   }
894 }
895
896 static void mpeg1_encode_block(MpegEncContext *s,
897                                DCTELEM *block,
898                                int n)
899 {
900     int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
901     int code, component;
902     const uint16_t (*table_vlc)[2] = rl_mpeg1.table_vlc;
903
904     last_index = s->block_last_index[n];
905
906     /* DC coef */
907     if (s->mb_intra) {
908         component = (n <= 3 ? 0 : n - 4 + 1);
909         dc = block[0]; /* overflow is impossible */
910         diff = dc - s->last_dc[component];
911         encode_dc(s, diff, component);
912         s->last_dc[component] = dc;
913         i = 1;
914         if (s->intra_vlc_format)
915             table_vlc = rl_mpeg2.table_vlc;
916     } else {
917         /* encode the first coefficient : needs to be done here because
918            it is handled slightly differently */
919         level = block[0];
920         if (abs(level) == 1) {
921                 code = ((uint32_t)level >> 31); /* the sign bit */
922                 put_bits(&s->pb, 2, code | 0x02);
923                 i = 1;
924         } else {
925             i = 0;
926             last_non_zero = -1;
927             goto next_coef;
928         }
929     }
930
931     /* now quantify & encode AC coefs */
932     last_non_zero = i - 1;
933
934     for(;i<=last_index;i++) {
935         j = s->intra_scantable.permutated[i];
936         level = block[j];
937     next_coef:
938 #if 0
939         if (level != 0)
940             dprintf("level[%d]=%d\n", i, level);
941 #endif
942         /* encode using VLC */
943         if (level != 0) {
944             run = i - last_non_zero - 1;
945
946             alevel= level;
947             MASK_ABS(sign, alevel)
948             sign&=1;
949
950             if (alevel <= mpeg1_max_level[0][run]){
951                 code= mpeg1_index_run[0][run] + alevel - 1;
952                 /* store the vlc & sign at once */
953                 put_bits(&s->pb, table_vlc[code][1]+1, (table_vlc[code][0]<<1) + sign);
954             } else {
955                 /* escape seems to be pretty rare <5% so i dont optimize it */
956                 put_bits(&s->pb, table_vlc[111][1], table_vlc[111][0]);
957                 /* escape: only clip in this case */
958                 put_bits(&s->pb, 6, run);
959                 if(s->codec_id == CODEC_ID_MPEG1VIDEO){
960                     if (alevel < 128) {
961                         put_bits(&s->pb, 8, level & 0xff);
962                     } else {
963                         if (level < 0) {
964                             put_bits(&s->pb, 16, 0x8001 + level + 255);
965                         } else {
966                             put_bits(&s->pb, 16, level & 0xffff);
967                         }
968                     }
969                 }else{
970                     put_bits(&s->pb, 12, level & 0xfff);
971                 }
972             }
973             last_non_zero = i;
974         }
975     }
976     /* end of block */
977     put_bits(&s->pb, table_vlc[112][1], table_vlc[112][0]);
978 }
979 #endif //CONFIG_ENCODERS
980
981 /******************************************/
982 /* decoding */
983
984 static VLC dc_lum_vlc;
985 static VLC dc_chroma_vlc;
986 static VLC mv_vlc;
987 static VLC mbincr_vlc;
988 static VLC mb_ptype_vlc;
989 static VLC mb_btype_vlc;
990 static VLC mb_pat_vlc;
991
992 static void init_vlcs(void)
993 {
994     static int done = 0;
995
996     if (!done) {
997         done = 1;
998
999         init_vlc(&dc_lum_vlc, DC_VLC_BITS, 12,
1000                  vlc_dc_lum_bits, 1, 1,
1001                  vlc_dc_lum_code, 2, 2, 1);
1002         init_vlc(&dc_chroma_vlc,  DC_VLC_BITS, 12,
1003                  vlc_dc_chroma_bits, 1, 1,
1004                  vlc_dc_chroma_code, 2, 2, 1);
1005         init_vlc(&mv_vlc, MV_VLC_BITS, 17,
1006                  &mbMotionVectorTable[0][1], 2, 1,
1007                  &mbMotionVectorTable[0][0], 2, 1, 1);
1008         init_vlc(&mbincr_vlc, MBINCR_VLC_BITS, 36,
1009                  &mbAddrIncrTable[0][1], 2, 1,
1010                  &mbAddrIncrTable[0][0], 2, 1, 1);
1011         init_vlc(&mb_pat_vlc, MB_PAT_VLC_BITS, 64,
1012                  &mbPatTable[0][1], 2, 1,
1013                  &mbPatTable[0][0], 2, 1, 1);
1014
1015         init_vlc(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 7,
1016                  &table_mb_ptype[0][1], 2, 1,
1017                  &table_mb_ptype[0][0], 2, 1, 1);
1018         init_vlc(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 11,
1019                  &table_mb_btype[0][1], 2, 1,
1020                  &table_mb_btype[0][0], 2, 1, 1);
1021         init_rl(&rl_mpeg1, 1);
1022         init_rl(&rl_mpeg2, 1);
1023
1024         init_2d_vlc_rl(&rl_mpeg1, 1);
1025         init_2d_vlc_rl(&rl_mpeg2, 1);
1026     }
1027 }
1028
1029 static inline int get_dmv(MpegEncContext *s)
1030 {
1031     if(get_bits1(&s->gb))
1032         return 1 - (get_bits1(&s->gb) << 1);
1033     else
1034         return 0;
1035 }
1036
1037 static inline int get_qscale(MpegEncContext *s)
1038 {
1039     int qscale = get_bits(&s->gb, 5);
1040     if (s->q_scale_type) {
1041         return non_linear_qscale[qscale];
1042     } else {
1043         return qscale << 1;
1044     }
1045 }
1046
1047 /* motion type (for mpeg2) */
1048 #define MT_FIELD 1
1049 #define MT_FRAME 2
1050 #define MT_16X8  2
1051 #define MT_DMV   3
1052
1053 static int mpeg_decode_mb(MpegEncContext *s,
1054                           DCTELEM block[12][64])
1055 {
1056     int i, j, k, cbp, val, mb_type, motion_type;
1057     const int mb_block_count = 4 + (1<< s->chroma_format);
1058
1059     dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
1060
1061     assert(s->mb_skipped==0);
1062
1063     if (s->mb_skip_run-- != 0) {
1064         if(s->pict_type == I_TYPE){
1065             av_log(s->avctx, AV_LOG_ERROR, "skipped MB in I frame at %d %d\n", s->mb_x, s->mb_y);
1066             return -1;
1067         }
1068
1069         /* skip mb */
1070         s->mb_intra = 0;
1071         for(i=0;i<12;i++)
1072             s->block_last_index[i] = -1;
1073         if(s->picture_structure == PICT_FRAME)
1074             s->mv_type = MV_TYPE_16X16;
1075         else
1076             s->mv_type = MV_TYPE_FIELD;
1077         if (s->pict_type == P_TYPE) {
1078             /* if P type, zero motion vector is implied */
1079             s->mv_dir = MV_DIR_FORWARD;
1080             s->mv[0][0][0] = s->mv[0][0][1] = 0;
1081             s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
1082             s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
1083             s->field_select[0][0]= s->picture_structure - 1;
1084             s->mb_skipped = 1;
1085             s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride ]= MB_TYPE_SKIP | MB_TYPE_L0 | MB_TYPE_16x16;
1086         } else {
1087             int mb_type;
1088
1089             if(s->mb_x)
1090                 mb_type= s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride - 1];
1091             else
1092                 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,
1093             if(IS_INTRA(mb_type))
1094                 return -1;
1095
1096             /* if B type, reuse previous vectors and directions */
1097             s->mv[0][0][0] = s->last_mv[0][0][0];
1098             s->mv[0][0][1] = s->last_mv[0][0][1];
1099             s->mv[1][0][0] = s->last_mv[1][0][0];
1100             s->mv[1][0][1] = s->last_mv[1][0][1];
1101
1102             s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride ]=
1103                 mb_type | MB_TYPE_SKIP;
1104 //            assert(s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride - 1]&(MB_TYPE_16x16|MB_TYPE_16x8));
1105
1106             if((s->mv[0][0][0]|s->mv[0][0][1]|s->mv[1][0][0]|s->mv[1][0][1])==0)
1107                 s->mb_skipped = 1;
1108         }
1109
1110         return 0;
1111     }
1112
1113     switch(s->pict_type) {
1114     default:
1115     case I_TYPE:
1116         if (get_bits1(&s->gb) == 0) {
1117             if (get_bits1(&s->gb) == 0){
1118                 av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in I Frame at %d %d\n", s->mb_x, s->mb_y);
1119                 return -1;
1120             }
1121             mb_type = MB_TYPE_QUANT | MB_TYPE_INTRA;
1122         } else {
1123             mb_type = MB_TYPE_INTRA;
1124         }
1125         break;
1126     case P_TYPE:
1127         mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
1128         if (mb_type < 0){
1129             av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
1130             return -1;
1131         }
1132         mb_type = ptype2mb_type[ mb_type ];
1133         break;
1134     case B_TYPE:
1135         mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
1136         if (mb_type < 0){
1137             av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
1138             return -1;
1139         }
1140         mb_type = btype2mb_type[ mb_type ];
1141         break;
1142     }
1143     dprintf("mb_type=%x\n", mb_type);
1144 //    motion_type = 0; /* avoid warning */
1145     if (IS_INTRA(mb_type)) {
1146         s->dsp.clear_blocks(s->block[0]);
1147
1148         if(!s->chroma_y_shift){
1149             s->dsp.clear_blocks(s->block[6]);
1150         }
1151
1152         /* compute dct type */
1153         if (s->picture_structure == PICT_FRAME && //FIXME add a interlaced_dct coded var?
1154             !s->frame_pred_frame_dct) {
1155             s->interlaced_dct = get_bits1(&s->gb);
1156         }
1157
1158         if (IS_QUANT(mb_type))
1159             s->qscale = get_qscale(s);
1160
1161         if (s->concealment_motion_vectors) {
1162             /* just parse them */
1163             if (s->picture_structure != PICT_FRAME)
1164                 skip_bits1(&s->gb); /* field select */
1165
1166             s->mv[0][0][0]= s->last_mv[0][0][0]= s->last_mv[0][1][0] =
1167                 mpeg_decode_motion(s, s->mpeg_f_code[0][0], s->last_mv[0][0][0]);
1168             s->mv[0][0][1]= s->last_mv[0][0][1]= s->last_mv[0][1][1] =
1169                 mpeg_decode_motion(s, s->mpeg_f_code[0][1], s->last_mv[0][0][1]);
1170
1171             skip_bits1(&s->gb); /* marker */
1172         }else
1173             memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
1174         s->mb_intra = 1;
1175 #ifdef HAVE_XVMC
1176         //one 1 we memcpy blocks in xvmcvideo
1177         if(s->avctx->xvmc_acceleration > 1){
1178             XVMC_pack_pblocks(s,-1);//inter are always full blocks
1179             if(s->swap_uv){
1180                 exchange_uv(s);
1181             }
1182         }
1183 #endif
1184
1185         if (s->codec_id == CODEC_ID_MPEG2VIDEO) {
1186             if(s->flags2 & CODEC_FLAG2_FAST){
1187                 for(i=0;i<6;i++) {
1188                     mpeg2_fast_decode_block_intra(s, s->pblocks[i], i);
1189                 }
1190             }else{
1191                 for(i=0;i<mb_block_count;i++) {
1192                     if (mpeg2_decode_block_intra(s, s->pblocks[i], i) < 0)
1193                         return -1;
1194                 }
1195             }
1196         } else {
1197             for(i=0;i<6;i++) {
1198                 if (mpeg1_decode_block_intra(s, s->pblocks[i], i) < 0)
1199                     return -1;
1200             }
1201         }
1202     } else {
1203         if (mb_type & MB_TYPE_ZERO_MV){
1204             assert(mb_type & MB_TYPE_CBP);
1205
1206             /* compute dct type */
1207             if (s->picture_structure == PICT_FRAME && //FIXME add a interlaced_dct coded var?
1208                 !s->frame_pred_frame_dct) {
1209                 s->interlaced_dct = get_bits1(&s->gb);
1210             }
1211
1212             if (IS_QUANT(mb_type))
1213                 s->qscale = get_qscale(s);
1214
1215             s->mv_dir = MV_DIR_FORWARD;
1216             if(s->picture_structure == PICT_FRAME)
1217                 s->mv_type = MV_TYPE_16X16;
1218             else{
1219                 s->mv_type = MV_TYPE_FIELD;
1220                 mb_type |= MB_TYPE_INTERLACED;
1221                 s->field_select[0][0]= s->picture_structure - 1;
1222             }
1223             s->last_mv[0][0][0] = 0;
1224             s->last_mv[0][0][1] = 0;
1225             s->last_mv[0][1][0] = 0;
1226             s->last_mv[0][1][1] = 0;
1227             s->mv[0][0][0] = 0;
1228             s->mv[0][0][1] = 0;
1229         }else{
1230             assert(mb_type & MB_TYPE_L0L1);
1231 //FIXME decide if MBs in field pictures are MB_TYPE_INTERLACED
1232             /* get additionnal motion vector type */
1233             if (s->frame_pred_frame_dct)
1234                 motion_type = MT_FRAME;
1235             else{
1236                 motion_type = get_bits(&s->gb, 2);
1237             }
1238
1239             /* compute dct type */
1240             if (s->picture_structure == PICT_FRAME && //FIXME add a interlaced_dct coded var?
1241                 !s->frame_pred_frame_dct && HAS_CBP(mb_type)) {
1242                 s->interlaced_dct = get_bits1(&s->gb);
1243             }
1244
1245             if (IS_QUANT(mb_type))
1246                 s->qscale = get_qscale(s);
1247
1248             /* motion vectors */
1249             s->mv_dir = 0;
1250             for(i=0;i<2;i++) {
1251                 if (USES_LIST(mb_type, i)) {
1252                     s->mv_dir |= (MV_DIR_FORWARD >> i);
1253                     dprintf("motion_type=%d\n", motion_type);
1254                     switch(motion_type) {
1255                     case MT_FRAME: /* or MT_16X8 */
1256                         if (s->picture_structure == PICT_FRAME) {
1257                             /* MT_FRAME */
1258                             mb_type |= MB_TYPE_16x16;
1259                             s->mv_type = MV_TYPE_16X16;
1260                             s->mv[i][0][0]= s->last_mv[i][0][0]= s->last_mv[i][1][0] =
1261                                 mpeg_decode_motion(s, s->mpeg_f_code[i][0], s->last_mv[i][0][0]);
1262                             s->mv[i][0][1]= s->last_mv[i][0][1]= s->last_mv[i][1][1] =
1263                                 mpeg_decode_motion(s, s->mpeg_f_code[i][1], s->last_mv[i][0][1]);
1264                             /* full_pel: only for mpeg1 */
1265                             if (s->full_pel[i]){
1266                                 s->mv[i][0][0] <<= 1;
1267                                 s->mv[i][0][1] <<= 1;
1268                             }
1269                         } else {
1270                             /* MT_16X8 */
1271                             mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
1272                             s->mv_type = MV_TYPE_16X8;
1273                             for(j=0;j<2;j++) {
1274                                 s->field_select[i][j] = get_bits1(&s->gb);
1275                                 for(k=0;k<2;k++) {
1276                                     val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
1277                                                              s->last_mv[i][j][k]);
1278                                     s->last_mv[i][j][k] = val;
1279                                     s->mv[i][j][k] = val;
1280                                 }
1281                             }
1282                         }
1283                         break;
1284                     case MT_FIELD:
1285                         s->mv_type = MV_TYPE_FIELD;
1286                         if (s->picture_structure == PICT_FRAME) {
1287                             mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
1288                             for(j=0;j<2;j++) {
1289                                 s->field_select[i][j] = get_bits1(&s->gb);
1290                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
1291                                                          s->last_mv[i][j][0]);
1292                                 s->last_mv[i][j][0] = val;
1293                                 s->mv[i][j][0] = val;
1294                                 dprintf("fmx=%d\n", val);
1295                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
1296                                                          s->last_mv[i][j][1] >> 1);
1297                                 s->last_mv[i][j][1] = val << 1;
1298                                 s->mv[i][j][1] = val;
1299                                 dprintf("fmy=%d\n", val);
1300                             }
1301                         } else {
1302                             mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
1303                             s->field_select[i][0] = get_bits1(&s->gb);
1304                             for(k=0;k<2;k++) {
1305                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
1306                                                          s->last_mv[i][0][k]);
1307                                 s->last_mv[i][0][k] = val;
1308                                 s->last_mv[i][1][k] = val;
1309                                 s->mv[i][0][k] = val;
1310                             }
1311                         }
1312                         break;
1313                     case MT_DMV:
1314                         {
1315                             int dmx, dmy, mx, my, m;
1316
1317                             mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
1318                                                     s->last_mv[i][0][0]);
1319                             s->last_mv[i][0][0] = mx;
1320                             s->last_mv[i][1][0] = mx;
1321                             dmx = get_dmv(s);
1322                             my = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
1323                                                     s->last_mv[i][0][1] >> 1);
1324                             dmy = get_dmv(s);
1325                             s->mv_type = MV_TYPE_DMV;
1326
1327
1328                             s->last_mv[i][0][1] = my<<1;
1329                             s->last_mv[i][1][1] = my<<1;
1330
1331                             s->mv[i][0][0] = mx;
1332                             s->mv[i][0][1] = my;
1333                             s->mv[i][1][0] = mx;//not used
1334                             s->mv[i][1][1] = my;//not used
1335
1336                             if (s->picture_structure == PICT_FRAME) {
1337                                 mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
1338
1339                                 //m = 1 + 2 * s->top_field_first;
1340                                 m = s->top_field_first ? 1 : 3;
1341
1342                                 /* top -> top pred */
1343                                 s->mv[i][2][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
1344                                 s->mv[i][2][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
1345                                 m = 4 - m;
1346                                 s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
1347                                 s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
1348                             } else {
1349                                 mb_type |= MB_TYPE_16x16;
1350
1351                                 s->mv[i][2][0] = ((mx + (mx > 0)) >> 1) + dmx;
1352                                 s->mv[i][2][1] = ((my + (my > 0)) >> 1) + dmy;
1353                                 if(s->picture_structure == PICT_TOP_FIELD)
1354                                     s->mv[i][2][1]--;
1355                                 else
1356                                     s->mv[i][2][1]++;
1357                             }
1358                         }
1359                         break;
1360                     default:
1361                         av_log(s->avctx, AV_LOG_ERROR, "00 motion_type at %d %d\n", s->mb_x, s->mb_y);
1362                         return -1;
1363                     }
1364                 }
1365             }
1366         }
1367
1368         s->mb_intra = 0;
1369         if (HAS_CBP(mb_type)) {
1370             s->dsp.clear_blocks(s->block[0]);
1371
1372             if(!s->chroma_y_shift){
1373                 s->dsp.clear_blocks(s->block[6]);
1374             }
1375
1376             cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
1377             if (cbp < 0 || ((cbp == 0) && (s->chroma_format < 2)) ){
1378                 av_log(s->avctx, AV_LOG_ERROR, "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
1379                 return -1;
1380             }
1381             if(mb_block_count > 6){
1382                  cbp<<= mb_block_count-6;
1383                  cbp |= get_bits(&s->gb, mb_block_count-6);
1384             }
1385
1386 #ifdef HAVE_XVMC
1387             //on 1 we memcpy blocks in xvmcvideo
1388             if(s->avctx->xvmc_acceleration > 1){
1389                 XVMC_pack_pblocks(s,cbp);
1390                 if(s->swap_uv){
1391                     exchange_uv(s);
1392                 }
1393             }
1394 #endif
1395
1396             if (s->codec_id == CODEC_ID_MPEG2VIDEO) {
1397                 if(s->flags2 & CODEC_FLAG2_FAST){
1398                     for(i=0;i<6;i++) {
1399                         if(cbp & 32) {
1400                             mpeg2_fast_decode_block_non_intra(s, s->pblocks[i], i);
1401                         } else {
1402                             s->block_last_index[i] = -1;
1403                         }
1404                         cbp+=cbp;
1405                     }
1406                 }else{
1407                     cbp<<= 12-mb_block_count;
1408
1409                     for(i=0;i<mb_block_count;i++) {
1410                         if ( cbp & (1<<11) ) {
1411                             if (mpeg2_decode_block_non_intra(s, s->pblocks[i], i) < 0)
1412                                 return -1;
1413                         } else {
1414                             s->block_last_index[i] = -1;
1415                         }
1416                         cbp+=cbp;
1417                     }
1418                 }
1419             } else {
1420                 if(s->flags2 & CODEC_FLAG2_FAST){
1421                     for(i=0;i<6;i++) {
1422                         if (cbp & 32) {
1423                             mpeg1_fast_decode_block_inter(s, s->pblocks[i], i);
1424                         } else {
1425                             s->block_last_index[i] = -1;
1426                         }
1427                         cbp+=cbp;
1428                     }
1429                 }else{
1430                     for(i=0;i<6;i++) {
1431                         if (cbp & 32) {
1432                             if (mpeg1_decode_block_inter(s, s->pblocks[i], i) < 0)
1433                                 return -1;
1434                         } else {
1435                             s->block_last_index[i] = -1;
1436                         }
1437                         cbp+=cbp;
1438                     }
1439                 }
1440             }
1441         }else{
1442             for(i=0;i<12;i++)
1443                 s->block_last_index[i] = -1;
1444         }
1445     }
1446
1447     s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride ]= mb_type;
1448
1449     return 0;
1450 }
1451
1452 /* as h263, but only 17 codes */
1453 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
1454 {
1455     int code, sign, val, l, shift;
1456
1457     code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
1458     if (code == 0) {
1459         return pred;
1460     }
1461     if (code < 0) {
1462         return 0xffff;
1463     }
1464
1465     sign = get_bits1(&s->gb);
1466     shift = fcode - 1;
1467     val = code;
1468     if (shift) {
1469         val = (val - 1) << shift;
1470         val |= get_bits(&s->gb, shift);
1471         val++;
1472     }
1473     if (sign)
1474         val = -val;
1475     val += pred;
1476
1477     /* modulo decoding */
1478     l= INT_BIT - 5 - shift;
1479     val = (val<<l)>>l;
1480     return val;
1481 }
1482
1483 static inline int decode_dc(GetBitContext *gb, int component)
1484 {
1485     int code, diff;
1486
1487     if (component == 0) {
1488         code = get_vlc2(gb, dc_lum_vlc.table, DC_VLC_BITS, 2);
1489     } else {
1490         code = get_vlc2(gb, dc_chroma_vlc.table, DC_VLC_BITS, 2);
1491     }
1492     if (code < 0){
1493         av_log(NULL, AV_LOG_ERROR, "invalid dc code at\n");
1494         return 0xffff;
1495     }
1496     if (code == 0) {
1497         diff = 0;
1498     } else {
1499         diff = get_xbits(gb, code);
1500     }
1501     return diff;
1502 }
1503
1504 static inline int mpeg1_decode_block_intra(MpegEncContext *s,
1505                                DCTELEM *block,
1506                                int n)
1507 {
1508     int level, dc, diff, i, j, run;
1509     int component;
1510     RLTable *rl = &rl_mpeg1;
1511     uint8_t * const scantable= s->intra_scantable.permutated;
1512     const uint16_t *quant_matrix= s->intra_matrix;
1513     const int qscale= s->qscale;
1514
1515     /* DC coef */
1516     component = (n <= 3 ? 0 : n - 4 + 1);
1517     diff = decode_dc(&s->gb, component);
1518     if (diff >= 0xffff)
1519         return -1;
1520     dc = s->last_dc[component];
1521     dc += diff;
1522     s->last_dc[component] = dc;
1523     block[0] = dc<<3;
1524     dprintf("dc=%d diff=%d\n", dc, diff);
1525     i = 0;
1526     {
1527         OPEN_READER(re, &s->gb);
1528         /* now quantify & encode AC coefs */
1529         for(;;) {
1530             UPDATE_CACHE(re, &s->gb);
1531             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1532
1533             if(level == 127){
1534                 break;
1535             } else if(level != 0) {
1536                 i += run;
1537                 j = scantable[i];
1538                 level= (level*qscale*quant_matrix[j])>>4;
1539                 level= (level-1)|1;
1540                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1541                 LAST_SKIP_BITS(re, &s->gb, 1);
1542             } else {
1543                 /* escape */
1544                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1545                 UPDATE_CACHE(re, &s->gb);
1546                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1547                 if (level == -128) {
1548                     level = SHOW_UBITS(re, &s->gb, 8) - 256; LAST_SKIP_BITS(re, &s->gb, 8);
1549                 } else if (level == 0) {
1550                     level = SHOW_UBITS(re, &s->gb, 8)      ; LAST_SKIP_BITS(re, &s->gb, 8);
1551                 }
1552                 i += run;
1553                 j = scantable[i];
1554                 if(level<0){
1555                     level= -level;
1556                     level= (level*qscale*quant_matrix[j])>>4;
1557                     level= (level-1)|1;
1558                     level= -level;
1559                 }else{
1560                     level= (level*qscale*quant_matrix[j])>>4;
1561                     level= (level-1)|1;
1562                 }
1563             }
1564             if (i > 63){
1565                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1566                 return -1;
1567             }
1568
1569             block[j] = level;
1570         }
1571         CLOSE_READER(re, &s->gb);
1572     }
1573     s->block_last_index[n] = i;
1574    return 0;
1575 }
1576
1577 static inline int mpeg1_decode_block_inter(MpegEncContext *s,
1578                                DCTELEM *block,
1579                                int n)
1580 {
1581     int level, i, j, run;
1582     RLTable *rl = &rl_mpeg1;
1583     uint8_t * const scantable= s->intra_scantable.permutated;
1584     const uint16_t *quant_matrix= s->inter_matrix;
1585     const int qscale= s->qscale;
1586
1587     {
1588         OPEN_READER(re, &s->gb);
1589         i = -1;
1590         /* special case for the first coef. no need to add a second vlc table */
1591         UPDATE_CACHE(re, &s->gb);
1592         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
1593             level= (3*qscale*quant_matrix[0])>>5;
1594             level= (level-1)|1;
1595             if(GET_CACHE(re, &s->gb)&0x40000000)
1596                 level= -level;
1597             block[0] = level;
1598             i++;
1599             SKIP_BITS(re, &s->gb, 2);
1600             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1601                 goto end;
1602         }
1603
1604         /* now quantify & encode AC coefs */
1605         for(;;) {
1606             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1607
1608             if(level != 0) {
1609                 i += run;
1610                 j = scantable[i];
1611                 level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1612                 level= (level-1)|1;
1613                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1614                 SKIP_BITS(re, &s->gb, 1);
1615             } else {
1616                 /* escape */
1617                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1618                 UPDATE_CACHE(re, &s->gb);
1619                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1620                 if (level == -128) {
1621                     level = SHOW_UBITS(re, &s->gb, 8) - 256; SKIP_BITS(re, &s->gb, 8);
1622                 } else if (level == 0) {
1623                     level = SHOW_UBITS(re, &s->gb, 8)      ; SKIP_BITS(re, &s->gb, 8);
1624                 }
1625                 i += run;
1626                 j = scantable[i];
1627                 if(level<0){
1628                     level= -level;
1629                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1630                     level= (level-1)|1;
1631                     level= -level;
1632                 }else{
1633                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1634                     level= (level-1)|1;
1635                 }
1636             }
1637             if (i > 63){
1638                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1639                 return -1;
1640             }
1641
1642             block[j] = level;
1643             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1644                 break;
1645             UPDATE_CACHE(re, &s->gb);
1646         }
1647 end:
1648         LAST_SKIP_BITS(re, &s->gb, 2);
1649         CLOSE_READER(re, &s->gb);
1650     }
1651     s->block_last_index[n] = i;
1652     return 0;
1653 }
1654
1655 static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s, DCTELEM *block, int n)
1656 {
1657     int level, i, j, run;
1658     RLTable *rl = &rl_mpeg1;
1659     uint8_t * const scantable= s->intra_scantable.permutated;
1660     const int qscale= s->qscale;
1661
1662     {
1663         OPEN_READER(re, &s->gb);
1664         i = -1;
1665         /* special case for the first coef. no need to add a second vlc table */
1666         UPDATE_CACHE(re, &s->gb);
1667         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
1668             level= (3*qscale)>>1;
1669             level= (level-1)|1;
1670             if(GET_CACHE(re, &s->gb)&0x40000000)
1671                 level= -level;
1672             block[0] = level;
1673             i++;
1674             SKIP_BITS(re, &s->gb, 2);
1675             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1676                 goto end;
1677         }
1678
1679         /* now quantify & encode AC coefs */
1680         for(;;) {
1681             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1682
1683             if(level != 0) {
1684                 i += run;
1685                 j = scantable[i];
1686                 level= ((level*2+1)*qscale)>>1;
1687                 level= (level-1)|1;
1688                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1689                 SKIP_BITS(re, &s->gb, 1);
1690             } else {
1691                 /* escape */
1692                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1693                 UPDATE_CACHE(re, &s->gb);
1694                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1695                 if (level == -128) {
1696                     level = SHOW_UBITS(re, &s->gb, 8) - 256; SKIP_BITS(re, &s->gb, 8);
1697                 } else if (level == 0) {
1698                     level = SHOW_UBITS(re, &s->gb, 8)      ; SKIP_BITS(re, &s->gb, 8);
1699                 }
1700                 i += run;
1701                 j = scantable[i];
1702                 if(level<0){
1703                     level= -level;
1704                     level= ((level*2+1)*qscale)>>1;
1705                     level= (level-1)|1;
1706                     level= -level;
1707                 }else{
1708                     level= ((level*2+1)*qscale)>>1;
1709                     level= (level-1)|1;
1710                 }
1711             }
1712
1713             block[j] = level;
1714             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1715                 break;
1716             UPDATE_CACHE(re, &s->gb);
1717         }
1718 end:
1719         LAST_SKIP_BITS(re, &s->gb, 2);
1720         CLOSE_READER(re, &s->gb);
1721     }
1722     s->block_last_index[n] = i;
1723     return 0;
1724 }
1725
1726
1727 static inline int mpeg2_decode_block_non_intra(MpegEncContext *s,
1728                                DCTELEM *block,
1729                                int n)
1730 {
1731     int level, i, j, run;
1732     RLTable *rl = &rl_mpeg1;
1733     uint8_t * const scantable= s->intra_scantable.permutated;
1734     const uint16_t *quant_matrix;
1735     const int qscale= s->qscale;
1736     int mismatch;
1737
1738     mismatch = 1;
1739
1740     {
1741         OPEN_READER(re, &s->gb);
1742         i = -1;
1743         if (n < 4)
1744             quant_matrix = s->inter_matrix;
1745         else
1746             quant_matrix = s->chroma_inter_matrix;
1747
1748         /* special case for the first coef. no need to add a second vlc table */
1749         UPDATE_CACHE(re, &s->gb);
1750         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
1751             level= (3*qscale*quant_matrix[0])>>5;
1752             if(GET_CACHE(re, &s->gb)&0x40000000)
1753                 level= -level;
1754             block[0] = level;
1755             mismatch ^= level;
1756             i++;
1757             SKIP_BITS(re, &s->gb, 2);
1758             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1759                 goto end;
1760         }
1761
1762         /* now quantify & encode AC coefs */
1763         for(;;) {
1764             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1765
1766             if(level != 0) {
1767                 i += run;
1768                 j = scantable[i];
1769                 level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1770                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1771                 SKIP_BITS(re, &s->gb, 1);
1772             } else {
1773                 /* escape */
1774                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1775                 UPDATE_CACHE(re, &s->gb);
1776                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1777
1778                 i += run;
1779                 j = scantable[i];
1780                 if(level<0){
1781                     level= ((-level*2+1)*qscale*quant_matrix[j])>>5;
1782                     level= -level;
1783                 }else{
1784                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1785                 }
1786             }
1787             if (i > 63){
1788                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1789                 return -1;
1790             }
1791
1792             mismatch ^= level;
1793             block[j] = level;
1794             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1795                 break;
1796             UPDATE_CACHE(re, &s->gb);
1797         }
1798 end:
1799         LAST_SKIP_BITS(re, &s->gb, 2);
1800         CLOSE_READER(re, &s->gb);
1801     }
1802     block[63] ^= (mismatch & 1);
1803
1804     s->block_last_index[n] = i;
1805     return 0;
1806 }
1807
1808 static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s,
1809                                DCTELEM *block,
1810                                int n)
1811 {
1812     int level, i, j, run;
1813     RLTable *rl = &rl_mpeg1;
1814     uint8_t * const scantable= s->intra_scantable.permutated;
1815     const int qscale= s->qscale;
1816     OPEN_READER(re, &s->gb);
1817     i = -1;
1818
1819     /* special case for the first coef. no need to add a second vlc table */
1820     UPDATE_CACHE(re, &s->gb);
1821     if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
1822         level= (3*qscale)>>1;
1823         if(GET_CACHE(re, &s->gb)&0x40000000)
1824             level= -level;
1825         block[0] = level;
1826         i++;
1827         SKIP_BITS(re, &s->gb, 2);
1828         if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1829             goto end;
1830     }
1831
1832     /* now quantify & encode AC coefs */
1833     for(;;) {
1834         GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1835
1836         if(level != 0) {
1837             i += run;
1838             j = scantable[i];
1839             level= ((level*2+1)*qscale)>>1;
1840             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1841             SKIP_BITS(re, &s->gb, 1);
1842         } else {
1843             /* escape */
1844             run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1845             UPDATE_CACHE(re, &s->gb);
1846             level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1847
1848             i += run;
1849             j = scantable[i];
1850             if(level<0){
1851                 level= ((-level*2+1)*qscale)>>1;
1852                 level= -level;
1853             }else{
1854                 level= ((level*2+1)*qscale)>>1;
1855             }
1856         }
1857
1858         block[j] = level;
1859         if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1860             break;
1861         UPDATE_CACHE(re, &s->gb);
1862     }
1863 end:
1864     LAST_SKIP_BITS(re, &s->gb, 2);
1865     CLOSE_READER(re, &s->gb);
1866     s->block_last_index[n] = i;
1867     return 0;
1868 }
1869
1870
1871 static inline int mpeg2_decode_block_intra(MpegEncContext *s,
1872                                DCTELEM *block,
1873                                int n)
1874 {
1875     int level, dc, diff, i, j, run;
1876     int component;
1877     RLTable *rl;
1878     uint8_t * const scantable= s->intra_scantable.permutated;
1879     const uint16_t *quant_matrix;
1880     const int qscale= s->qscale;
1881     int mismatch;
1882
1883     /* DC coef */
1884     if (n < 4){
1885         quant_matrix = s->intra_matrix;
1886         component = 0;
1887     }else{
1888         quant_matrix = s->chroma_intra_matrix;
1889         component = (n&1) + 1;
1890     }
1891     diff = decode_dc(&s->gb, component);
1892     if (diff >= 0xffff)
1893         return -1;
1894     dc = s->last_dc[component];
1895     dc += diff;
1896     s->last_dc[component] = dc;
1897     block[0] = dc << (3 - s->intra_dc_precision);
1898     dprintf("dc=%d\n", block[0]);
1899     mismatch = block[0] ^ 1;
1900     i = 0;
1901     if (s->intra_vlc_format)
1902         rl = &rl_mpeg2;
1903     else
1904         rl = &rl_mpeg1;
1905
1906     {
1907         OPEN_READER(re, &s->gb);
1908         /* now quantify & encode AC coefs */
1909         for(;;) {
1910             UPDATE_CACHE(re, &s->gb);
1911             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1912
1913             if(level == 127){
1914                 break;
1915             } else if(level != 0) {
1916                 i += run;
1917                 j = scantable[i];
1918                 level= (level*qscale*quant_matrix[j])>>4;
1919                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1920                 LAST_SKIP_BITS(re, &s->gb, 1);
1921             } else {
1922                 /* escape */
1923                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1924                 UPDATE_CACHE(re, &s->gb);
1925                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1926                 i += run;
1927                 j = scantable[i];
1928                 if(level<0){
1929                     level= (-level*qscale*quant_matrix[j])>>4;
1930                     level= -level;
1931                 }else{
1932                     level= (level*qscale*quant_matrix[j])>>4;
1933                 }
1934             }
1935             if (i > 63){
1936                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1937                 return -1;
1938             }
1939
1940             mismatch^= level;
1941             block[j] = level;
1942         }
1943         CLOSE_READER(re, &s->gb);
1944     }
1945     block[63]^= mismatch&1;
1946
1947     s->block_last_index[n] = i;
1948     return 0;
1949 }
1950
1951 static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s,
1952                                DCTELEM *block,
1953                                int n)
1954 {
1955     int level, dc, diff, j, run;
1956     int component;
1957     RLTable *rl;
1958     uint8_t * scantable= s->intra_scantable.permutated;
1959     const uint16_t *quant_matrix;
1960     const int qscale= s->qscale;
1961
1962     /* DC coef */
1963     if (n < 4){
1964         quant_matrix = s->intra_matrix;
1965         component = 0;
1966     }else{
1967         quant_matrix = s->chroma_intra_matrix;
1968         component = (n&1) + 1;
1969     }
1970     diff = decode_dc(&s->gb, component);
1971     if (diff >= 0xffff)
1972         return -1;
1973     dc = s->last_dc[component];
1974     dc += diff;
1975     s->last_dc[component] = dc;
1976     block[0] = dc << (3 - s->intra_dc_precision);
1977     if (s->intra_vlc_format)
1978         rl = &rl_mpeg2;
1979     else
1980         rl = &rl_mpeg1;
1981
1982     {
1983         OPEN_READER(re, &s->gb);
1984         /* now quantify & encode AC coefs */
1985         for(;;) {
1986             UPDATE_CACHE(re, &s->gb);
1987             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1988
1989             if(level == 127){
1990                 break;
1991             } else if(level != 0) {
1992                 scantable += run;
1993                 j = *scantable;
1994                 level= (level*qscale*quant_matrix[j])>>4;
1995                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1996                 LAST_SKIP_BITS(re, &s->gb, 1);
1997             } else {
1998                 /* escape */
1999                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
2000                 UPDATE_CACHE(re, &s->gb);
2001                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
2002                 scantable += run;
2003                 j = *scantable;
2004                 if(level<0){
2005                     level= (-level*qscale*quant_matrix[j])>>4;
2006                     level= -level;
2007                 }else{
2008                     level= (level*qscale*quant_matrix[j])>>4;
2009                 }
2010             }
2011
2012             block[j] = level;
2013         }
2014         CLOSE_READER(re, &s->gb);
2015     }
2016
2017     s->block_last_index[n] = scantable - s->intra_scantable.permutated;
2018     return 0;
2019 }
2020
2021 typedef struct Mpeg1Context {
2022     MpegEncContext mpeg_enc_ctx;
2023     int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
2024     int repeat_field; /* true if we must repeat the field */
2025     AVPanScan pan_scan; /** some temporary storage for the panscan */
2026     int slice_count;
2027     int swap_uv;//indicate VCR2
2028     int save_aspect_info;
2029     AVRational frame_rate_ext;       ///< MPEG-2 specific framerate modificator
2030
2031 } Mpeg1Context;
2032
2033 static int mpeg_decode_init(AVCodecContext *avctx)
2034 {
2035     Mpeg1Context *s = avctx->priv_data;
2036     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2037     int i;
2038
2039     //we need some parmutation to store
2040     //matrixes, until MPV_common_init()
2041     //set the real permutatuon
2042     for(i=0;i<64;i++)
2043        s2->dsp.idct_permutation[i]=i;
2044
2045     MPV_decode_defaults(s2);
2046
2047     s->mpeg_enc_ctx.avctx= avctx;
2048     s->mpeg_enc_ctx.flags= avctx->flags;
2049     s->mpeg_enc_ctx.flags2= avctx->flags2;
2050     common_init(&s->mpeg_enc_ctx);
2051     init_vlcs();
2052
2053     s->mpeg_enc_ctx_allocated = 0;
2054     s->mpeg_enc_ctx.picture_number = 0;
2055     s->repeat_field = 0;
2056     s->mpeg_enc_ctx.codec_id= avctx->codec->id;
2057     return 0;
2058 }
2059
2060 static void quant_matrix_rebuild(uint16_t *matrix, const uint8_t *old_perm,
2061                                      const uint8_t *new_perm){
2062     uint16_t temp_matrix[64];
2063     int i;
2064
2065     memcpy(temp_matrix,matrix,64*sizeof(uint16_t));
2066
2067     for(i=0;i<64;i++){
2068         matrix[new_perm[i]] = temp_matrix[old_perm[i]];
2069     }
2070 }
2071
2072 //Call this function when we know all parameters
2073 //it may be called in different places for mpeg1 and mpeg2
2074 static int mpeg_decode_postinit(AVCodecContext *avctx){
2075     Mpeg1Context *s1 = avctx->priv_data;
2076     MpegEncContext *s = &s1->mpeg_enc_ctx;
2077     uint8_t old_permutation[64];
2078
2079     if (
2080         (s1->mpeg_enc_ctx_allocated == 0)||
2081         avctx->coded_width  != s->width ||
2082         avctx->coded_height != s->height||
2083         s1->save_aspect_info != s->aspect_ratio_info||
2084         0)
2085     {
2086
2087         if (s1->mpeg_enc_ctx_allocated) {
2088             ParseContext pc= s->parse_context;
2089             s->parse_context.buffer=0;
2090             MPV_common_end(s);
2091             s->parse_context= pc;
2092         }
2093
2094         if( (s->width == 0 )||(s->height == 0))
2095             return -2;
2096
2097         avcodec_set_dimensions(avctx, s->width, s->height);
2098         avctx->bit_rate = s->bit_rate;
2099         s1->save_aspect_info = s->aspect_ratio_info;
2100
2101      //low_delay may be forced, in this case we will have B frames
2102      //that behave like P frames
2103         avctx->has_b_frames = !(s->low_delay);
2104
2105         if(avctx->sub_id==1){//s->codec_id==avctx->codec_id==CODEC_ID
2106             //mpeg1 fps
2107             avctx->time_base.den     = frame_rate_tab[s->frame_rate_index].num;
2108             avctx->time_base.num= frame_rate_tab[s->frame_rate_index].den;
2109             //mpeg1 aspect
2110             avctx->sample_aspect_ratio= av_d2q(
2111                     1.0/mpeg1_aspect[s->aspect_ratio_info], 255);
2112
2113         }else{//mpeg2
2114         //mpeg2 fps
2115             av_reduce(
2116                 &s->avctx->time_base.den,
2117                 &s->avctx->time_base.num,
2118                 frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num,
2119                 frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den,
2120                 1<<30);
2121         //mpeg2 aspect
2122             if(s->aspect_ratio_info > 1){
2123                 if( (s1->pan_scan.width == 0 )||(s1->pan_scan.height == 0) ){
2124                     s->avctx->sample_aspect_ratio=
2125                         av_div_q(
2126                          mpeg2_aspect[s->aspect_ratio_info],
2127                          (AVRational){s->width, s->height}
2128                          );
2129                 }else{
2130                     s->avctx->sample_aspect_ratio=
2131                         av_div_q(
2132                          mpeg2_aspect[s->aspect_ratio_info],
2133                          (AVRational){s1->pan_scan.width, s1->pan_scan.height}
2134                         );
2135                 }
2136             }else{
2137                 s->avctx->sample_aspect_ratio=
2138                     mpeg2_aspect[s->aspect_ratio_info];
2139             }
2140         }//mpeg2
2141
2142         if(avctx->xvmc_acceleration){
2143             avctx->pix_fmt = avctx->get_format(avctx,pixfmt_xvmc_mpg2_420);
2144         }else{
2145             if(s->chroma_format <  2){
2146                 avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_420);
2147             }else
2148             if(s->chroma_format == 2){
2149                 avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_422);
2150             }else
2151             if(s->chroma_format >  2){
2152                 avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_444);
2153             }
2154         }
2155         //until then pix_fmt may be changed right after codec init
2156         if( avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT )
2157             if( avctx->idct_algo == FF_IDCT_AUTO )
2158                 avctx->idct_algo = FF_IDCT_SIMPLE;
2159
2160         //quantization matrixes may need reordering
2161         //if dct permutation is changed
2162         memcpy(old_permutation,s->dsp.idct_permutation,64*sizeof(uint8_t));
2163
2164         if (MPV_common_init(s) < 0)
2165             return -2;
2166
2167         quant_matrix_rebuild(s->intra_matrix,       old_permutation,s->dsp.idct_permutation);
2168         quant_matrix_rebuild(s->inter_matrix,       old_permutation,s->dsp.idct_permutation);
2169         quant_matrix_rebuild(s->chroma_intra_matrix,old_permutation,s->dsp.idct_permutation);
2170         quant_matrix_rebuild(s->chroma_inter_matrix,old_permutation,s->dsp.idct_permutation);
2171
2172         s1->mpeg_enc_ctx_allocated = 1;
2173     }
2174     return 0;
2175 }
2176
2177 static int mpeg1_decode_picture(AVCodecContext *avctx,
2178                                 const uint8_t *buf, int buf_size)
2179 {
2180     Mpeg1Context *s1 = avctx->priv_data;
2181     MpegEncContext *s = &s1->mpeg_enc_ctx;
2182     int ref, f_code, vbv_delay;
2183
2184     if(mpeg_decode_postinit(s->avctx) < 0)
2185        return -2;
2186
2187     init_get_bits(&s->gb, buf, buf_size*8);
2188
2189     ref = get_bits(&s->gb, 10); /* temporal ref */
2190     s->pict_type = get_bits(&s->gb, 3);
2191     if(s->pict_type == 0 || s->pict_type > 3)
2192         return -1;
2193
2194     vbv_delay= get_bits(&s->gb, 16);
2195     if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
2196         s->full_pel[0] = get_bits1(&s->gb);
2197         f_code = get_bits(&s->gb, 3);
2198         if (f_code == 0 && avctx->error_resilience >= FF_ER_COMPLIANT)
2199             return -1;
2200         s->mpeg_f_code[0][0] = f_code;
2201         s->mpeg_f_code[0][1] = f_code;
2202     }
2203     if (s->pict_type == B_TYPE) {
2204         s->full_pel[1] = get_bits1(&s->gb);
2205         f_code = get_bits(&s->gb, 3);
2206         if (f_code == 0 && avctx->error_resilience >= FF_ER_COMPLIANT)
2207             return -1;
2208         s->mpeg_f_code[1][0] = f_code;
2209         s->mpeg_f_code[1][1] = f_code;
2210     }
2211     s->current_picture.pict_type= s->pict_type;
2212     s->current_picture.key_frame= s->pict_type == I_TYPE;
2213
2214     if(avctx->debug & FF_DEBUG_PICT_INFO)
2215         av_log(avctx, AV_LOG_DEBUG, "vbv_delay %d, ref %d type:%d\n", vbv_delay, ref, s->pict_type);
2216
2217     s->y_dc_scale = 8;
2218     s->c_dc_scale = 8;
2219     s->first_slice = 1;
2220     return 0;
2221 }
2222
2223 static void mpeg_decode_sequence_extension(Mpeg1Context *s1)
2224 {
2225     MpegEncContext *s= &s1->mpeg_enc_ctx;
2226     int horiz_size_ext, vert_size_ext;
2227     int bit_rate_ext;
2228
2229     skip_bits(&s->gb, 1); /* profil and level esc*/
2230     s->avctx->profile= get_bits(&s->gb, 3);
2231     s->avctx->level= get_bits(&s->gb, 4);
2232     s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
2233     s->chroma_format = get_bits(&s->gb, 2); /* chroma_format 1=420, 2=422, 3=444 */
2234     horiz_size_ext = get_bits(&s->gb, 2);
2235     vert_size_ext = get_bits(&s->gb, 2);
2236     s->width |= (horiz_size_ext << 12);
2237     s->height |= (vert_size_ext << 12);
2238     bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
2239     s->bit_rate += (bit_rate_ext << 18) * 400;
2240     skip_bits1(&s->gb); /* marker */
2241     s->avctx->rc_buffer_size += get_bits(&s->gb, 8)*1024*16<<10;
2242
2243     s->low_delay = get_bits1(&s->gb);
2244     if(s->flags & CODEC_FLAG_LOW_DELAY) s->low_delay=1;
2245
2246     s1->frame_rate_ext.num = get_bits(&s->gb, 2)+1;
2247     s1->frame_rate_ext.den = get_bits(&s->gb, 5)+1;
2248
2249     dprintf("sequence extension\n");
2250     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG2VIDEO;
2251     s->avctx->sub_id = 2; /* indicates mpeg2 found */
2252
2253     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2254         av_log(s->avctx, AV_LOG_DEBUG, "profile: %d, level: %d vbv buffer: %d, bitrate:%d\n",
2255                s->avctx->profile, s->avctx->level, s->avctx->rc_buffer_size, s->bit_rate);
2256
2257 }
2258
2259 static void mpeg_decode_sequence_display_extension(Mpeg1Context *s1)
2260 {
2261     MpegEncContext *s= &s1->mpeg_enc_ctx;
2262     int color_description, w, h;
2263
2264     skip_bits(&s->gb, 3); /* video format */
2265     color_description= get_bits1(&s->gb);
2266     if(color_description){
2267         skip_bits(&s->gb, 8); /* color primaries */
2268         skip_bits(&s->gb, 8); /* transfer_characteristics */
2269         skip_bits(&s->gb, 8); /* matrix_coefficients */
2270     }
2271     w= get_bits(&s->gb, 14);
2272     skip_bits(&s->gb, 1); //marker
2273     h= get_bits(&s->gb, 14);
2274     skip_bits(&s->gb, 1); //marker
2275
2276     s1->pan_scan.width= 16*w;
2277     s1->pan_scan.height=16*h;
2278
2279     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2280         av_log(s->avctx, AV_LOG_DEBUG, "sde w:%d, h:%d\n", w, h);
2281 }
2282
2283 static void mpeg_decode_picture_display_extension(Mpeg1Context *s1)
2284 {
2285     MpegEncContext *s= &s1->mpeg_enc_ctx;
2286     int i,nofco;
2287
2288     nofco = 1;
2289     if(s->progressive_sequence){
2290         if(s->repeat_first_field){
2291             nofco++;
2292             if(s->top_field_first)
2293                 nofco++;
2294         }
2295     }else{
2296         if(s->picture_structure == PICT_FRAME){
2297             nofco++;
2298             if(s->repeat_first_field)
2299                 nofco++;
2300         }
2301     }
2302     for(i=0; i<nofco; i++){
2303         s1->pan_scan.position[i][0]= get_sbits(&s->gb, 16);
2304         skip_bits(&s->gb, 1); //marker
2305         s1->pan_scan.position[i][1]= get_sbits(&s->gb, 16);
2306         skip_bits(&s->gb, 1); //marker
2307     }
2308
2309     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2310         av_log(s->avctx, AV_LOG_DEBUG, "pde (%d,%d) (%d,%d) (%d,%d)\n",
2311             s1->pan_scan.position[0][0], s1->pan_scan.position[0][1],
2312             s1->pan_scan.position[1][0], s1->pan_scan.position[1][1],
2313             s1->pan_scan.position[2][0], s1->pan_scan.position[2][1]
2314         );
2315 }
2316
2317 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
2318 {
2319     int i, v, j;
2320
2321     dprintf("matrix extension\n");
2322
2323     if (get_bits1(&s->gb)) {
2324         for(i=0;i<64;i++) {
2325             v = get_bits(&s->gb, 8);
2326             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2327             s->intra_matrix[j] = v;
2328             s->chroma_intra_matrix[j] = v;
2329         }
2330     }
2331     if (get_bits1(&s->gb)) {
2332         for(i=0;i<64;i++) {
2333             v = get_bits(&s->gb, 8);
2334             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2335             s->inter_matrix[j] = v;
2336             s->chroma_inter_matrix[j] = v;
2337         }
2338     }
2339     if (get_bits1(&s->gb)) {
2340         for(i=0;i<64;i++) {
2341             v = get_bits(&s->gb, 8);
2342             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2343             s->chroma_intra_matrix[j] = v;
2344         }
2345     }
2346     if (get_bits1(&s->gb)) {
2347         for(i=0;i<64;i++) {
2348             v = get_bits(&s->gb, 8);
2349             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2350             s->chroma_inter_matrix[j] = v;
2351         }
2352     }
2353 }
2354
2355 static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
2356 {
2357     s->full_pel[0] = s->full_pel[1] = 0;
2358     s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
2359     s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
2360     s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
2361     s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
2362     s->intra_dc_precision = get_bits(&s->gb, 2);
2363     s->picture_structure = get_bits(&s->gb, 2);
2364     s->top_field_first = get_bits1(&s->gb);
2365     s->frame_pred_frame_dct = get_bits1(&s->gb);
2366     s->concealment_motion_vectors = get_bits1(&s->gb);
2367     s->q_scale_type = get_bits1(&s->gb);
2368     s->intra_vlc_format = get_bits1(&s->gb);
2369     s->alternate_scan = get_bits1(&s->gb);
2370     s->repeat_first_field = get_bits1(&s->gb);
2371     s->chroma_420_type = get_bits1(&s->gb);
2372     s->progressive_frame = get_bits1(&s->gb);
2373
2374     if(s->picture_structure == PICT_FRAME)
2375         s->first_field=0;
2376     else{
2377         s->first_field ^= 1;
2378         memset(s->mbskip_table, 0, s->mb_stride*s->mb_height);
2379     }
2380
2381     if(s->alternate_scan){
2382         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
2383         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
2384     }else{
2385         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
2386         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
2387     }
2388
2389     /* composite display not parsed */
2390     dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
2391     dprintf("picture_structure=%d\n", s->picture_structure);
2392     dprintf("top field first=%d\n", s->top_field_first);
2393     dprintf("repeat first field=%d\n", s->repeat_first_field);
2394     dprintf("conceal=%d\n", s->concealment_motion_vectors);
2395     dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
2396     dprintf("alternate_scan=%d\n", s->alternate_scan);
2397     dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
2398     dprintf("progressive_frame=%d\n", s->progressive_frame);
2399 }
2400
2401 static void mpeg_decode_extension(AVCodecContext *avctx,
2402                                   const uint8_t *buf, int buf_size)
2403 {
2404     Mpeg1Context *s1 = avctx->priv_data;
2405     MpegEncContext *s = &s1->mpeg_enc_ctx;
2406     int ext_type;
2407
2408     init_get_bits(&s->gb, buf, buf_size*8);
2409
2410     ext_type = get_bits(&s->gb, 4);
2411     switch(ext_type) {
2412     case 0x1:
2413         mpeg_decode_sequence_extension(s1);
2414         break;
2415     case 0x2:
2416         mpeg_decode_sequence_display_extension(s1);
2417         break;
2418     case 0x3:
2419         mpeg_decode_quant_matrix_extension(s);
2420         break;
2421     case 0x7:
2422         mpeg_decode_picture_display_extension(s1);
2423         break;
2424     case 0x8:
2425         mpeg_decode_picture_coding_extension(s);
2426         break;
2427     }
2428 }
2429
2430 static void exchange_uv(MpegEncContext *s){
2431     short * tmp = s->pblocks[4];
2432     s->pblocks[4] = s->pblocks[5];
2433     s->pblocks[5] = tmp;
2434 }
2435
2436 static int mpeg_field_start(MpegEncContext *s){
2437     AVCodecContext *avctx= s->avctx;
2438     Mpeg1Context *s1 = (Mpeg1Context*)s;
2439
2440     /* start frame decoding */
2441     if(s->first_field || s->picture_structure==PICT_FRAME){
2442         if(MPV_frame_start(s, avctx) < 0)
2443             return -1;
2444
2445         ff_er_frame_start(s);
2446
2447         /* first check if we must repeat the frame */
2448         s->current_picture_ptr->repeat_pict = 0;
2449         if (s->repeat_first_field) {
2450             if (s->progressive_sequence) {
2451                 if (s->top_field_first)
2452                     s->current_picture_ptr->repeat_pict = 4;
2453                 else
2454                     s->current_picture_ptr->repeat_pict = 2;
2455             } else if (s->progressive_frame) {
2456                 s->current_picture_ptr->repeat_pict = 1;
2457             }
2458         }
2459
2460         *s->current_picture_ptr->pan_scan= s1->pan_scan;
2461     }else{ //second field
2462             int i;
2463
2464             if(!s->current_picture_ptr){
2465                 av_log(s->avctx, AV_LOG_ERROR, "first field missing\n");
2466                 return -1;
2467             }
2468
2469             for(i=0; i<4; i++){
2470                 s->current_picture.data[i] = s->current_picture_ptr->data[i];
2471                 if(s->picture_structure == PICT_BOTTOM_FIELD){
2472                     s->current_picture.data[i] += s->current_picture_ptr->linesize[i];
2473                 }
2474             }
2475     }
2476 #ifdef HAVE_XVMC
2477 // MPV_frame_start will call this function too,
2478 // but we need to call it on every field
2479     if(s->avctx->xvmc_acceleration)
2480          XVMC_field_start(s,avctx);
2481 #endif
2482
2483     return 0;
2484 }
2485
2486 #define DECODE_SLICE_ERROR -1
2487 #define DECODE_SLICE_OK 0
2488
2489 /**
2490  * decodes a slice. MpegEncContext.mb_y must be set to the MB row from the startcode
2491  * @return DECODE_SLICE_ERROR if the slice is damaged<br>
2492  *         DECODE_SLICE_OK if this slice is ok<br>
2493  */
2494 static int mpeg_decode_slice(Mpeg1Context *s1, int mb_y,
2495                              const uint8_t **buf, int buf_size)
2496 {
2497     MpegEncContext *s = &s1->mpeg_enc_ctx;
2498     AVCodecContext *avctx= s->avctx;
2499     int ret;
2500     const int field_pic= s->picture_structure != PICT_FRAME;
2501     const int lowres= s->avctx->lowres;
2502
2503     s->resync_mb_x=
2504     s->resync_mb_y= -1;
2505
2506     if (mb_y<<field_pic >= s->mb_height){
2507         av_log(s->avctx, AV_LOG_ERROR, "slice below image (%d >= %d)\n", mb_y, s->mb_height);
2508         return -1;
2509     }
2510
2511     init_get_bits(&s->gb, *buf, buf_size*8);
2512
2513     ff_mpeg1_clean_buffers(s);
2514     s->interlaced_dct = 0;
2515
2516     s->qscale = get_qscale(s);
2517
2518     if(s->qscale == 0){
2519         av_log(s->avctx, AV_LOG_ERROR, "qscale == 0\n");
2520         return -1;
2521     }
2522
2523     /* extra slice info */
2524     while (get_bits1(&s->gb) != 0) {
2525         skip_bits(&s->gb, 8);
2526     }
2527
2528     s->mb_x=0;
2529
2530     for(;;) {
2531         int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
2532         if (code < 0){
2533             av_log(s->avctx, AV_LOG_ERROR, "first mb_incr damaged\n");
2534             return -1;
2535         }
2536         if (code >= 33) {
2537             if (code == 33) {
2538                 s->mb_x += 33;
2539             }
2540             /* otherwise, stuffing, nothing to do */
2541         } else {
2542             s->mb_x += code;
2543             break;
2544         }
2545     }
2546
2547     s->resync_mb_x= s->mb_x;
2548     s->resync_mb_y= s->mb_y= mb_y;
2549     s->mb_skip_run= 0;
2550     ff_init_block_index(s);
2551
2552     if (s->mb_y==0 && s->mb_x==0 && (s->first_field || s->picture_structure==PICT_FRAME)) {
2553         if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2554              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",
2555                  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],
2556                  s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")),
2557                  s->progressive_sequence ? "ps" :"", s->progressive_frame ? "pf" : "", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"",
2558                  s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors,
2559                  s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :"");
2560         }
2561     }
2562
2563     for(;;) {
2564 #ifdef HAVE_XVMC
2565         //one 1 we memcpy blocks in xvmcvideo
2566         if(s->avctx->xvmc_acceleration > 1)
2567             XVMC_init_block(s);//set s->block
2568 #endif
2569
2570         ret = mpeg_decode_mb(s, s->block);
2571         s->chroma_qscale= s->qscale;
2572
2573         dprintf("ret=%d\n", ret);
2574         if (ret < 0)
2575             return -1;
2576
2577         if(s->current_picture.motion_val[0] && !s->encoding){ //note motion_val is normally NULL unless we want to extract the MVs
2578             const int wrap = field_pic ? 2*s->b8_stride : s->b8_stride;
2579             int xy = s->mb_x*2 + s->mb_y*2*wrap;
2580             int motion_x, motion_y, dir, i;
2581             if(field_pic && !s->first_field)
2582                 xy += wrap/2;
2583
2584             for(i=0; i<2; i++){
2585                 for(dir=0; dir<2; dir++){
2586                     if (s->mb_intra || (dir==1 && s->pict_type != B_TYPE)) {
2587                         motion_x = motion_y = 0;
2588                     }else if (s->mv_type == MV_TYPE_16X16 || (s->mv_type == MV_TYPE_FIELD && field_pic)){
2589                         motion_x = s->mv[dir][0][0];
2590                         motion_y = s->mv[dir][0][1];
2591                     } else /*if ((s->mv_type == MV_TYPE_FIELD) || (s->mv_type == MV_TYPE_16X8))*/ {
2592                         motion_x = s->mv[dir][i][0];
2593                         motion_y = s->mv[dir][i][1];
2594                     }
2595
2596                     s->current_picture.motion_val[dir][xy    ][0] = motion_x;
2597                     s->current_picture.motion_val[dir][xy    ][1] = motion_y;
2598                     s->current_picture.motion_val[dir][xy + 1][0] = motion_x;
2599                     s->current_picture.motion_val[dir][xy + 1][1] = motion_y;
2600                     s->current_picture.ref_index [dir][xy    ]=
2601                     s->current_picture.ref_index [dir][xy + 1]= s->field_select[dir][i];
2602                     assert(s->field_select[dir][i]==0 || s->field_select[dir][i]==1);
2603                 }
2604                 xy += wrap;
2605             }
2606         }
2607
2608         s->dest[0] += 16 >> lowres;
2609         s->dest[1] += 16 >> (s->chroma_x_shift + lowres);
2610         s->dest[2] += 16 >> (s->chroma_x_shift + lowres);
2611
2612         MPV_decode_mb(s, s->block);
2613
2614         if (++s->mb_x >= s->mb_width) {
2615             const int mb_size= 16>>s->avctx->lowres;
2616
2617             ff_draw_horiz_band(s, mb_size*s->mb_y, mb_size);
2618
2619             s->mb_x = 0;
2620             s->mb_y++;
2621
2622             if(s->mb_y<<field_pic >= s->mb_height){
2623                 int left= s->gb.size_in_bits - get_bits_count(&s->gb);
2624                 int is_d10= s->chroma_format==2 && s->pict_type==I_TYPE && avctx->profile==0 && avctx->level==5
2625                             && s->intra_dc_precision == 2 && s->q_scale_type == 1 && s->alternate_scan == 0
2626                             && s->progressive_frame == 0 /* vbv_delay == 0xBBB || 0xE10*/;
2627
2628                 if(left < 0 || (left && show_bits(&s->gb, FFMIN(left, 23)) && !is_d10)
2629                    || (avctx->error_resilience >= FF_ER_AGGRESSIVE && left>8)){
2630                     av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d %0X\n", left, show_bits(&s->gb, FFMIN(left, 23)));
2631                     return -1;
2632                 }else
2633                     goto eos;
2634             }
2635
2636             ff_init_block_index(s);
2637         }
2638
2639         /* skip mb handling */
2640         if (s->mb_skip_run == -1) {
2641             /* read again increment */
2642             s->mb_skip_run = 0;
2643             for(;;) {
2644                 int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
2645                 if (code < 0){
2646                     av_log(s->avctx, AV_LOG_ERROR, "mb incr damaged\n");
2647                     return -1;
2648                 }
2649                 if (code >= 33) {
2650                     if (code == 33) {
2651                         s->mb_skip_run += 33;
2652                     }else if(code == 35){
2653                         if(s->mb_skip_run != 0 || show_bits(&s->gb, 15) != 0){
2654                             av_log(s->avctx, AV_LOG_ERROR, "slice mismatch\n");
2655                             return -1;
2656                         }
2657                         goto eos; /* end of slice */
2658                     }
2659                     /* otherwise, stuffing, nothing to do */
2660                 } else {
2661                     s->mb_skip_run += code;
2662                     break;
2663                 }
2664             }
2665         }
2666     }
2667 eos: // end of slice
2668     *buf += get_bits_count(&s->gb)/8 - 1;
2669 //printf("y %d %d %d %d\n", s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y);
2670     return 0;
2671 }
2672
2673 static int slice_decode_thread(AVCodecContext *c, void *arg){
2674     MpegEncContext *s= arg;
2675     const uint8_t *buf= s->gb.buffer;
2676     int mb_y= s->start_mb_y;
2677
2678     s->error_count= 3*(s->end_mb_y - s->start_mb_y)*s->mb_width;
2679
2680     for(;;){
2681         int start_code, ret;
2682
2683         ret= mpeg_decode_slice((Mpeg1Context*)s, mb_y, &buf, s->gb.buffer_end - buf);
2684         emms_c();
2685 //av_log(c, AV_LOG_DEBUG, "ret:%d resync:%d/%d mb:%d/%d ts:%d/%d ec:%d\n",
2686 //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);
2687         if(ret < 0){
2688             if(s->resync_mb_x>=0 && s->resync_mb_y>=0)
2689                 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);
2690         }else{
2691             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);
2692         }
2693
2694         if(s->mb_y == s->end_mb_y)
2695             return 0;
2696
2697         start_code= -1;
2698         buf = ff_find_start_code(buf, s->gb.buffer_end, &start_code);
2699         mb_y= start_code - SLICE_MIN_START_CODE;
2700         if(mb_y < 0 || mb_y >= s->end_mb_y)
2701             return -1;
2702     }
2703
2704     return 0; //not reached
2705 }
2706
2707 /**
2708  * handles slice ends.
2709  * @return 1 if it seems to be the last slice of
2710  */
2711 static int slice_end(AVCodecContext *avctx, AVFrame *pict)
2712 {
2713     Mpeg1Context *s1 = avctx->priv_data;
2714     MpegEncContext *s = &s1->mpeg_enc_ctx;
2715
2716     if (!s1->mpeg_enc_ctx_allocated || !s->current_picture_ptr)
2717         return 0;
2718
2719 #ifdef HAVE_XVMC
2720     if(s->avctx->xvmc_acceleration)
2721         XVMC_field_end(s);
2722 #endif
2723     /* end of slice reached */
2724     if (/*s->mb_y<<field_pic == s->mb_height &&*/ !s->first_field) {
2725         /* end of image */
2726
2727         s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_MPEG2;
2728
2729         ff_er_frame_end(s);
2730
2731         MPV_frame_end(s);
2732
2733         if (s->pict_type == B_TYPE || s->low_delay) {
2734             *pict= *(AVFrame*)s->current_picture_ptr;
2735             ff_print_debug_info(s, pict);
2736         } else {
2737             s->picture_number++;
2738             /* latency of 1 frame for I and P frames */
2739             /* XXX: use another variable than picture_number */
2740             if (s->last_picture_ptr != NULL) {
2741                 *pict= *(AVFrame*)s->last_picture_ptr;
2742                  ff_print_debug_info(s, pict);
2743             }
2744         }
2745
2746         return 1;
2747     } else {
2748         return 0;
2749     }
2750 }
2751
2752 static int mpeg1_decode_sequence(AVCodecContext *avctx,
2753                                  const uint8_t *buf, int buf_size)
2754 {
2755     Mpeg1Context *s1 = avctx->priv_data;
2756     MpegEncContext *s = &s1->mpeg_enc_ctx;
2757     int width,height;
2758     int i, v, j;
2759
2760     init_get_bits(&s->gb, buf, buf_size*8);
2761
2762     width = get_bits(&s->gb, 12);
2763     height = get_bits(&s->gb, 12);
2764     if (width <= 0 || height <= 0 ||
2765         (width % 2) != 0 || (height % 2) != 0)
2766         return -1;
2767     s->aspect_ratio_info= get_bits(&s->gb, 4);
2768     if (s->aspect_ratio_info == 0)
2769         return -1;
2770     s->frame_rate_index = get_bits(&s->gb, 4);
2771     if (s->frame_rate_index == 0 || s->frame_rate_index > 13)
2772         return -1;
2773     s->bit_rate = get_bits(&s->gb, 18) * 400;
2774     if (get_bits1(&s->gb) == 0) /* marker */
2775         return -1;
2776     s->width = width;
2777     s->height = height;
2778
2779     s->avctx->rc_buffer_size= get_bits(&s->gb, 10) * 1024*16;
2780     skip_bits(&s->gb, 1);
2781
2782     /* get matrix */
2783     if (get_bits1(&s->gb)) {
2784         for(i=0;i<64;i++) {
2785             v = get_bits(&s->gb, 8);
2786             if(v==0){
2787                 av_log(s->avctx, AV_LOG_ERROR, "intra matrix damaged\n");
2788                 return -1;
2789             }
2790             j = s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2791             s->intra_matrix[j] = v;
2792             s->chroma_intra_matrix[j] = v;
2793         }
2794 #ifdef DEBUG
2795         dprintf("intra matrix present\n");
2796         for(i=0;i<64;i++)
2797             dprintf(" %d", s->intra_matrix[s->dsp.idct_permutation[i]]);
2798         dprintf("\n");
2799 #endif
2800     } else {
2801         for(i=0;i<64;i++) {
2802             j = s->dsp.idct_permutation[i];
2803             v = ff_mpeg1_default_intra_matrix[i];
2804             s->intra_matrix[j] = v;
2805             s->chroma_intra_matrix[j] = v;
2806         }
2807     }
2808     if (get_bits1(&s->gb)) {
2809         for(i=0;i<64;i++) {
2810             v = get_bits(&s->gb, 8);
2811             if(v==0){
2812                 av_log(s->avctx, AV_LOG_ERROR, "inter matrix damaged\n");
2813                 return -1;
2814             }
2815             j = s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2816             s->inter_matrix[j] = v;
2817             s->chroma_inter_matrix[j] = v;
2818         }
2819 #ifdef DEBUG
2820         dprintf("non intra matrix present\n");
2821         for(i=0;i<64;i++)
2822             dprintf(" %d", s->inter_matrix[s->dsp.idct_permutation[i]]);
2823         dprintf("\n");
2824 #endif
2825     } else {
2826         for(i=0;i<64;i++) {
2827             int j= s->dsp.idct_permutation[i];
2828             v = ff_mpeg1_default_non_intra_matrix[i];
2829             s->inter_matrix[j] = v;
2830             s->chroma_inter_matrix[j] = v;
2831         }
2832     }
2833
2834     if(show_bits(&s->gb, 23) != 0){
2835         av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");
2836         return -1;
2837     }
2838
2839     /* we set mpeg2 parameters so that it emulates mpeg1 */
2840     s->progressive_sequence = 1;
2841     s->progressive_frame = 1;
2842     s->picture_structure = PICT_FRAME;
2843     s->frame_pred_frame_dct = 1;
2844     s->chroma_format = 1;
2845     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG1VIDEO;
2846     avctx->sub_id = 1; /* indicates mpeg1 */
2847     s->out_format = FMT_MPEG1;
2848     s->swap_uv = 0;//AFAIK VCR2 don't have SEQ_HEADER
2849     if(s->flags & CODEC_FLAG_LOW_DELAY) s->low_delay=1;
2850
2851     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2852         av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%d\n",
2853                s->avctx->rc_buffer_size, s->bit_rate);
2854
2855     return 0;
2856 }
2857
2858 static int vcr2_init_sequence(AVCodecContext *avctx)
2859 {
2860     Mpeg1Context *s1 = avctx->priv_data;
2861     MpegEncContext *s = &s1->mpeg_enc_ctx;
2862     int i, v;
2863
2864     /* start new mpeg1 context decoding */
2865     s->out_format = FMT_MPEG1;
2866     if (s1->mpeg_enc_ctx_allocated) {
2867         MPV_common_end(s);
2868     }
2869     s->width  = avctx->coded_width;
2870     s->height = avctx->coded_height;
2871     avctx->has_b_frames= 0; //true?
2872     s->low_delay= 1;
2873
2874     if(avctx->xvmc_acceleration){
2875         avctx->pix_fmt = avctx->get_format(avctx,pixfmt_xvmc_mpg2_420);
2876     }else{
2877         avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_420);
2878     }
2879
2880     if( avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT )
2881         if( avctx->idct_algo == FF_IDCT_AUTO )
2882             avctx->idct_algo = FF_IDCT_SIMPLE;
2883
2884     if (MPV_common_init(s) < 0)
2885         return -1;
2886     exchange_uv(s);//common init reset pblocks, so we swap them here
2887     s->swap_uv = 1;// in case of xvmc we need to swap uv for each MB
2888     s1->mpeg_enc_ctx_allocated = 1;
2889
2890     for(i=0;i<64;i++) {
2891         int j= s->dsp.idct_permutation[i];
2892         v = ff_mpeg1_default_intra_matrix[i];
2893         s->intra_matrix[j] = v;
2894         s->chroma_intra_matrix[j] = v;
2895
2896         v = ff_mpeg1_default_non_intra_matrix[i];
2897         s->inter_matrix[j] = v;
2898         s->chroma_inter_matrix[j] = v;
2899     }
2900
2901     s->progressive_sequence = 1;
2902     s->progressive_frame = 1;
2903     s->picture_structure = PICT_FRAME;
2904     s->frame_pred_frame_dct = 1;
2905     s->chroma_format = 1;
2906     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG2VIDEO;
2907     avctx->sub_id = 2; /* indicates mpeg2 */
2908     return 0;
2909 }
2910
2911
2912 static void mpeg_decode_user_data(AVCodecContext *avctx,
2913                                   const uint8_t *buf, int buf_size)
2914 {
2915     const uint8_t *p;
2916     int len, flags;
2917     p = buf;
2918     len = buf_size;
2919
2920     /* we parse the DTG active format information */
2921     if (len >= 5 &&
2922         p[0] == 'D' && p[1] == 'T' && p[2] == 'G' && p[3] == '1') {
2923         flags = p[4];
2924         p += 5;
2925         len -= 5;
2926         if (flags & 0x80) {
2927             /* skip event id */
2928             if (len < 2)
2929                 return;
2930             p += 2;
2931             len -= 2;
2932         }
2933         if (flags & 0x40) {
2934             if (len < 1)
2935                 return;
2936             avctx->dtg_active_format = p[0] & 0x0f;
2937         }
2938     }
2939 }
2940
2941 static void mpeg_decode_gop(AVCodecContext *avctx,
2942                             const uint8_t *buf, int buf_size){
2943     Mpeg1Context *s1 = avctx->priv_data;
2944     MpegEncContext *s = &s1->mpeg_enc_ctx;
2945
2946     int drop_frame_flag;
2947     int time_code_hours, time_code_minutes;
2948     int time_code_seconds, time_code_pictures;
2949     int broken_link;
2950
2951     init_get_bits(&s->gb, buf, buf_size*8);
2952
2953     drop_frame_flag = get_bits1(&s->gb);
2954
2955     time_code_hours=get_bits(&s->gb,5);
2956     time_code_minutes = get_bits(&s->gb,6);
2957     skip_bits1(&s->gb);//marker bit
2958     time_code_seconds = get_bits(&s->gb,6);
2959     time_code_pictures = get_bits(&s->gb,6);
2960
2961     /*broken_link indicate that after editing the
2962       reference frames of the first B-Frames after GOP I-Frame
2963       are missing (open gop)*/
2964     broken_link = get_bits1(&s->gb);
2965
2966     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2967         av_log(s->avctx, AV_LOG_DEBUG, "GOP (%2d:%02d:%02d.[%02d]) broken_link=%d\n",
2968             time_code_hours, time_code_minutes, time_code_seconds,
2969             time_code_pictures, broken_link);
2970 }
2971 /**
2972  * finds the end of the current frame in the bitstream.
2973  * @return the position of the first byte of the next frame, or -1
2974  */
2975 int ff_mpeg1_find_frame_end(ParseContext *pc, const uint8_t *buf, int buf_size)
2976 {
2977     int i;
2978     uint32_t state= pc->state;
2979
2980     i=0;
2981     if(!pc->frame_start_found){
2982         for(i=0; i<buf_size; i++){
2983             i= ff_find_start_code(buf+i, buf+buf_size, &state) - buf - 1;
2984             if(state >= SLICE_MIN_START_CODE && state <= SLICE_MAX_START_CODE){
2985                 i++;
2986                 pc->frame_start_found=1;
2987                 break;
2988             }
2989         }
2990     }
2991
2992     if(pc->frame_start_found){
2993         /* EOF considered as end of frame */
2994         if (buf_size == 0)
2995             return 0;
2996         for(; i<buf_size; i++){
2997             i= ff_find_start_code(buf+i, buf+buf_size, &state) - buf - 1;
2998             if((state&0xFFFFFF00) == 0x100){
2999                 if(state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE){
3000                     pc->frame_start_found=0;
3001                     pc->state=-1;
3002                     return i-3;
3003                 }
3004             }
3005         }
3006     }
3007     pc->state= state;
3008     return END_NOT_FOUND;
3009 }
3010
3011 /* handle buffering and image synchronisation */
3012 static int mpeg_decode_frame(AVCodecContext *avctx,
3013                              void *data, int *data_size,
3014                              uint8_t *buf, int buf_size)
3015 {
3016     Mpeg1Context *s = avctx->priv_data;
3017     const uint8_t *buf_end;
3018     const uint8_t *buf_ptr;
3019     int ret, start_code, input_size;
3020     AVFrame *picture = data;
3021     MpegEncContext *s2 = &s->mpeg_enc_ctx;
3022     dprintf("fill_buffer\n");
3023
3024     if (buf_size == 0) {
3025         /* special case for last picture */
3026         if (s2->low_delay==0 && s2->next_picture_ptr) {
3027             *picture= *(AVFrame*)s2->next_picture_ptr;
3028             s2->next_picture_ptr= NULL;
3029
3030             *data_size = sizeof(AVFrame);
3031         }
3032         return 0;
3033     }
3034
3035     if(s2->flags&CODEC_FLAG_TRUNCATED){
3036         int next= ff_mpeg1_find_frame_end(&s2->parse_context, buf, buf_size);
3037
3038         if( ff_combine_frame(&s2->parse_context, next, &buf, &buf_size) < 0 )
3039             return buf_size;
3040     }
3041
3042     buf_ptr = buf;
3043     buf_end = buf + buf_size;
3044
3045 #if 0
3046     if (s->repeat_field % 2 == 1) {
3047         s->repeat_field++;
3048         //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
3049         //        s2->picture_number, s->repeat_field);
3050         if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
3051             *data_size = sizeof(AVPicture);
3052             goto the_end;
3053         }
3054     }
3055 #endif
3056
3057     if(s->mpeg_enc_ctx_allocated==0 && avctx->codec_tag == ff_get_fourcc("VCR2"))
3058         vcr2_init_sequence(avctx);
3059
3060     s->slice_count= 0;
3061
3062     for(;;) {
3063         /* find start next code */
3064         start_code = -1;
3065         buf_ptr = ff_find_start_code(buf_ptr,buf_end, &start_code);
3066         if (start_code < 0){
3067             if(s2->pict_type != B_TYPE || avctx->skip_frame <= AVDISCARD_DEFAULT){
3068                 if(avctx->thread_count > 1){
3069                     int i;
3070
3071                     avctx->execute(avctx, slice_decode_thread,  (void**)&(s2->thread_context[0]), NULL, s->slice_count);
3072                     for(i=0; i<s->slice_count; i++)
3073                         s2->error_count += s2->thread_context[i]->error_count;
3074                 }
3075                 if (slice_end(avctx, picture)) {
3076                     if(s2->last_picture_ptr || s2->low_delay) //FIXME merge with the stuff in mpeg_decode_slice
3077                         *data_size = sizeof(AVPicture);
3078                 }
3079             }
3080             return FFMAX(0, buf_ptr - buf - s2->parse_context.last_index);
3081         }
3082
3083         input_size = buf_end - buf_ptr;
3084
3085         if(avctx->debug & FF_DEBUG_STARTCODE){
3086             av_log(avctx, AV_LOG_DEBUG, "%3X at %zd left %d\n", start_code, buf_ptr-buf, input_size);
3087         }
3088
3089                 /* prepare data for next start code */
3090                 switch(start_code) {
3091                 case SEQ_START_CODE:
3092                     mpeg1_decode_sequence(avctx, buf_ptr,
3093                                           input_size);
3094                     break;
3095
3096                 case PICTURE_START_CODE:
3097                     /* we have a complete image : we try to decompress it */
3098                     mpeg1_decode_picture(avctx,
3099                                          buf_ptr, input_size);
3100                     break;
3101                 case EXT_START_CODE:
3102                     mpeg_decode_extension(avctx,
3103                                           buf_ptr, input_size);
3104                     break;
3105                 case USER_START_CODE:
3106                     mpeg_decode_user_data(avctx,
3107                                           buf_ptr, input_size);
3108                     break;
3109                 case GOP_START_CODE:
3110                     s2->first_field=0;
3111                     mpeg_decode_gop(avctx,
3112                                           buf_ptr, input_size);
3113                     break;
3114                 default:
3115                     if (start_code >= SLICE_MIN_START_CODE &&
3116                         start_code <= SLICE_MAX_START_CODE) {
3117                         int mb_y= start_code - SLICE_MIN_START_CODE;
3118
3119                         if(s2->last_picture_ptr==NULL){
3120                         /* skip b frames if we dont have reference frames */
3121                             if(s2->pict_type==B_TYPE) break;
3122                         /* skip P frames if we dont have reference frame no valid header */
3123 //                            if(s2->pict_type==P_TYPE && s2->first_field && !s2->first_slice) break;
3124                         }
3125                         /* skip b frames if we are in a hurry */
3126                         if(avctx->hurry_up && s2->pict_type==B_TYPE) break;
3127                         if(  (avctx->skip_frame >= AVDISCARD_NONREF && s2->pict_type==B_TYPE)
3128                            ||(avctx->skip_frame >= AVDISCARD_NONKEY && s2->pict_type!=I_TYPE)
3129                            || avctx->skip_frame >= AVDISCARD_ALL)
3130                             break;
3131                         /* skip everything if we are in a hurry>=5 */
3132                         if(avctx->hurry_up>=5) break;
3133
3134                         if (!s->mpeg_enc_ctx_allocated) break;
3135
3136                         if(s2->codec_id == CODEC_ID_MPEG2VIDEO){
3137                             if(mb_y < avctx->skip_top || mb_y >= s2->mb_height - avctx->skip_bottom)
3138                                 break;
3139                         }
3140
3141                         if(s2->first_slice){
3142                             s2->first_slice=0;
3143                             if(mpeg_field_start(s2) < 0)
3144                                 return -1;
3145                         }
3146
3147                         if(avctx->thread_count > 1){
3148                             int threshold= (s2->mb_height*s->slice_count + avctx->thread_count/2) / avctx->thread_count;
3149                             if(threshold <= mb_y){
3150                                 MpegEncContext *thread_context= s2->thread_context[s->slice_count];
3151
3152                                 thread_context->start_mb_y= mb_y;
3153                                 thread_context->end_mb_y  = s2->mb_height;
3154                                 if(s->slice_count){
3155                                     s2->thread_context[s->slice_count-1]->end_mb_y= mb_y;
3156                                     ff_update_duplicate_context(thread_context, s2);
3157                                 }
3158                                 init_get_bits(&thread_context->gb, buf_ptr, input_size*8);
3159                                 s->slice_count++;
3160                             }
3161                             buf_ptr += 2; //FIXME add minimum num of bytes per slice
3162                         }else{
3163                             ret = mpeg_decode_slice(s, mb_y, &buf_ptr, input_size);
3164                             emms_c();
3165
3166                             if(ret < 0){
3167                                 if(s2->resync_mb_x>=0 && s2->resync_mb_y>=0)
3168                                     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);
3169                             }else{
3170                                 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);
3171                             }
3172                         }
3173                     }
3174                     break;
3175                 }
3176     }
3177 }
3178
3179 static int mpeg_decode_end(AVCodecContext *avctx)
3180 {
3181     Mpeg1Context *s = avctx->priv_data;
3182
3183     if (s->mpeg_enc_ctx_allocated)
3184         MPV_common_end(&s->mpeg_enc_ctx);
3185     return 0;
3186 }
3187
3188 AVCodec mpeg1video_decoder = {
3189     "mpeg1video",
3190     CODEC_TYPE_VIDEO,
3191     CODEC_ID_MPEG1VIDEO,
3192     sizeof(Mpeg1Context),
3193     mpeg_decode_init,
3194     NULL,
3195     mpeg_decode_end,
3196     mpeg_decode_frame,
3197     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
3198     .flush= ff_mpeg_flush,
3199 };
3200
3201 AVCodec mpeg2video_decoder = {
3202     "mpeg2video",
3203     CODEC_TYPE_VIDEO,
3204     CODEC_ID_MPEG2VIDEO,
3205     sizeof(Mpeg1Context),
3206     mpeg_decode_init,
3207     NULL,
3208     mpeg_decode_end,
3209     mpeg_decode_frame,
3210     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
3211     .flush= ff_mpeg_flush,
3212 };
3213
3214 //legacy decoder
3215 AVCodec mpegvideo_decoder = {
3216     "mpegvideo",
3217     CODEC_TYPE_VIDEO,
3218     CODEC_ID_MPEG2VIDEO,
3219     sizeof(Mpeg1Context),
3220     mpeg_decode_init,
3221     NULL,
3222     mpeg_decode_end,
3223     mpeg_decode_frame,
3224     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
3225     .flush= ff_mpeg_flush,
3226 };
3227
3228 #ifdef CONFIG_ENCODERS
3229
3230 AVCodec mpeg1video_encoder = {
3231     "mpeg1video",
3232     CODEC_TYPE_VIDEO,
3233     CODEC_ID_MPEG1VIDEO,
3234     sizeof(MpegEncContext),
3235     encode_init,
3236     MPV_encode_picture,
3237     MPV_encode_end,
3238     .supported_framerates= frame_rate_tab+1,
3239     .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, -1},
3240     .capabilities= CODEC_CAP_DELAY,
3241 };
3242
3243 AVCodec mpeg2video_encoder = {
3244     "mpeg2video",
3245     CODEC_TYPE_VIDEO,
3246     CODEC_ID_MPEG2VIDEO,
3247     sizeof(MpegEncContext),
3248     encode_init,
3249     MPV_encode_picture,
3250     MPV_encode_end,
3251     .supported_framerates= frame_rate_tab+1,
3252     .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, -1},
3253     .capabilities= CODEC_CAP_DELAY,
3254 };
3255 #endif
3256
3257 #ifdef HAVE_XVMC
3258 static int mpeg_mc_decode_init(AVCodecContext *avctx){
3259     Mpeg1Context *s;
3260
3261     if( avctx->thread_count > 1)
3262         return -1;
3263     if( !(avctx->slice_flags & SLICE_FLAG_CODED_ORDER) )
3264         return -1;
3265     if( !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD) ){
3266         dprintf("mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");
3267     }
3268     mpeg_decode_init(avctx);
3269     s = avctx->priv_data;
3270
3271     avctx->pix_fmt = PIX_FMT_XVMC_MPEG2_IDCT;
3272     avctx->xvmc_acceleration = 2;//2 - the blocks are packed!
3273
3274     return 0;
3275 }
3276
3277 AVCodec mpeg_xvmc_decoder = {
3278     "mpegvideo_xvmc",
3279     CODEC_TYPE_VIDEO,
3280     CODEC_ID_MPEG2VIDEO_XVMC,
3281     sizeof(Mpeg1Context),
3282     mpeg_mc_decode_init,
3283     NULL,
3284     mpeg_decode_end,
3285     mpeg_decode_frame,
3286     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED| CODEC_CAP_HWACCEL | CODEC_CAP_DELAY,
3287     .flush= ff_mpeg_flush,
3288 };
3289
3290 #endif
3291
3292 /* this is ugly i know, but the alternative is too make
3293    hundreds of vars global and prefix them with ff_mpeg1_
3294    which is far uglier. */
3295 #include "mdec.c"