Remove useless line.
[ffmpeg.git] / libavcodec / h263.c
1 /*
2  * H263/MPEG4 backend for ffmpeg encoder and decoder
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  * H263+ support.
5  * Copyright (c) 2001 Juan J. Sierralta P
6  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
7  *
8  * ac prediction encoding, B-frame support, error resilience, optimizations,
9  * qpel decoding, gmc decoding, interlaced decoding
10  * by Michael Niedermayer <michaelni@gmx.at>
11  *
12  * This file is part of FFmpeg.
13  *
14  * FFmpeg is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * FFmpeg is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with FFmpeg; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27  */
28
29 /**
30  * @file libavcodec/h263.c
31  * h263/mpeg4 codec.
32  */
33
34 //#define DEBUG
35 #include <limits.h>
36
37 #include "dsputil.h"
38 #include "avcodec.h"
39 #include "mpegvideo.h"
40 #include "h263.h"
41 #include "h263data.h"
42 #include "mathops.h"
43 #include "unary.h"
44 #include "flv.h"
45 #include "mpeg4video.h"
46
47 //#undef NDEBUG
48 //#include <assert.h>
49
50 // The defines below define the number of bits that are read at once for
51 // reading vlc values. Changing these may improve speed and data cache needs
52 // be aware though that decreasing them may need the number of stages that is
53 // passed to get_vlc* to be increased.
54 #define MV_VLC_BITS 9
55 #define H263_MBTYPE_B_VLC_BITS 6
56 #define CBPC_B_VLC_BITS 3
57
58
59 #if CONFIG_ENCODERS
60 /**
61  * Table of number of bits a motion vector component needs.
62  */
63 static uint8_t mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
64
65 /**
66  * Minimal fcode that a motion vector component would need.
67  */
68 static uint8_t fcode_tab[MAX_MV*2+1];
69
70 /**
71  * Minimal fcode that a motion vector component would need in umv.
72  * All entries in this table are 1.
73  */
74 static uint8_t umv_fcode_tab[MAX_MV*2+1];
75
76 //unified encoding tables for run length encoding of coefficients
77 //unified in the sense that the specification specifies the encoding in several steps.
78 static uint8_t  uni_h263_intra_aic_rl_len [64*64*2*2];
79 static uint8_t  uni_h263_inter_rl_len [64*64*2*2];
80 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
81 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
82 #define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
83
84 #endif
85
86 static uint8_t static_rl_table_store[2][2][2*MAX_RUN + MAX_LEVEL + 3];
87
88
89 int h263_get_picture_format(int width, int height)
90 {
91     if (width == 128 && height == 96)
92         return 1;
93     else if (width == 176 && height == 144)
94         return 2;
95     else if (width == 352 && height == 288)
96         return 3;
97     else if (width == 704 && height == 576)
98         return 4;
99     else if (width == 1408 && height == 1152)
100         return 5;
101     else
102         return 7;
103 }
104
105 void ff_h263_show_pict_info(MpegEncContext *s){
106     if(s->avctx->debug&FF_DEBUG_PICT_INFO){
107     av_log(s->avctx, AV_LOG_DEBUG, "qp:%d %c size:%d rnd:%d%s%s%s%s%s%s%s%s%s %d/%d\n",
108          s->qscale, av_get_pict_type_char(s->pict_type),
109          s->gb.size_in_bits, 1-s->no_rounding,
110          s->obmc ? " AP" : "",
111          s->umvplus ? " UMV" : "",
112          s->h263_long_vectors ? " LONG" : "",
113          s->h263_plus ? " +" : "",
114          s->h263_aic ? " AIC" : "",
115          s->alt_inter_vlc ? " AIV" : "",
116          s->modified_quant ? " MQ" : "",
117          s->loop_filter ? " LOOP" : "",
118          s->h263_slice_structured ? " SS" : "",
119          s->avctx->time_base.den, s->avctx->time_base.num
120     );
121     }
122 }
123
124 #if CONFIG_ENCODERS
125
126 /**
127  * Returns the 4 bit value that specifies the given aspect ratio.
128  * This may be one of the standard aspect ratios or it specifies
129  * that the aspect will be stored explicitly later.
130  */
131 av_const int ff_h263_aspect_to_info(AVRational aspect){
132     int i;
133
134     if(aspect.num==0) aspect= (AVRational){1,1};
135
136     for(i=1; i<6; i++){
137         if(av_cmp_q(ff_h263_pixel_aspect[i], aspect) == 0){
138             return i;
139         }
140     }
141
142     return FF_ASPECT_EXTENDED;
143 }
144
145 void h263_encode_picture_header(MpegEncContext * s, int picture_number)
146 {
147     int format, coded_frame_rate, coded_frame_rate_base, i, temp_ref;
148     int best_clock_code=1;
149     int best_divisor=60;
150     int best_error= INT_MAX;
151
152     if(s->h263_plus){
153         for(i=0; i<2; i++){
154             int div, error;
155             div= (s->avctx->time_base.num*1800000LL + 500LL*s->avctx->time_base.den) / ((1000LL+i)*s->avctx->time_base.den);
156             div= av_clip(div, 1, 127);
157             error= FFABS(s->avctx->time_base.num*1800000LL - (1000LL+i)*s->avctx->time_base.den*div);
158             if(error < best_error){
159                 best_error= error;
160                 best_divisor= div;
161                 best_clock_code= i;
162             }
163         }
164     }
165     s->custom_pcf= best_clock_code!=1 || best_divisor!=60;
166     coded_frame_rate= 1800000;
167     coded_frame_rate_base= (1000+best_clock_code)*best_divisor;
168
169     align_put_bits(&s->pb);
170
171     /* Update the pointer to last GOB */
172     s->ptr_lastgob = put_bits_ptr(&s->pb);
173     put_bits(&s->pb, 22, 0x20); /* PSC */
174     temp_ref= s->picture_number * (int64_t)coded_frame_rate * s->avctx->time_base.num / //FIXME use timestamp
175                          (coded_frame_rate_base * (int64_t)s->avctx->time_base.den);
176     put_sbits(&s->pb, 8, temp_ref); /* TemporalReference */
177
178     put_bits(&s->pb, 1, 1);     /* marker */
179     put_bits(&s->pb, 1, 0);     /* h263 id */
180     put_bits(&s->pb, 1, 0);     /* split screen off */
181     put_bits(&s->pb, 1, 0);     /* camera  off */
182     put_bits(&s->pb, 1, 0);     /* freeze picture release off */
183
184     format = h263_get_picture_format(s->width, s->height);
185     if (!s->h263_plus) {
186         /* H.263v1 */
187         put_bits(&s->pb, 3, format);
188         put_bits(&s->pb, 1, (s->pict_type == FF_P_TYPE));
189         /* By now UMV IS DISABLED ON H.263v1, since the restrictions
190         of H.263v1 UMV implies to check the predicted MV after
191         calculation of the current MB to see if we're on the limits */
192         put_bits(&s->pb, 1, 0);         /* Unrestricted Motion Vector: off */
193         put_bits(&s->pb, 1, 0);         /* SAC: off */
194         put_bits(&s->pb, 1, s->obmc);   /* Advanced Prediction */
195         put_bits(&s->pb, 1, 0);         /* only I/P frames, no PB frame */
196         put_bits(&s->pb, 5, s->qscale);
197         put_bits(&s->pb, 1, 0);         /* Continuous Presence Multipoint mode: off */
198     } else {
199         int ufep=1;
200         /* H.263v2 */
201         /* H.263 Plus PTYPE */
202
203         put_bits(&s->pb, 3, 7);
204         put_bits(&s->pb,3,ufep); /* Update Full Extended PTYPE */
205         if (format == 7)
206             put_bits(&s->pb,3,6); /* Custom Source Format */
207         else
208             put_bits(&s->pb, 3, format);
209
210         put_bits(&s->pb,1, s->custom_pcf);
211         put_bits(&s->pb,1, s->umvplus); /* Unrestricted Motion Vector */
212         put_bits(&s->pb,1,0); /* SAC: off */
213         put_bits(&s->pb,1,s->obmc); /* Advanced Prediction Mode */
214         put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
215         put_bits(&s->pb,1,s->loop_filter); /* Deblocking Filter */
216         put_bits(&s->pb,1,s->h263_slice_structured); /* Slice Structured */
217         put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
218         put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
219         put_bits(&s->pb,1,s->alt_inter_vlc); /* Alternative Inter VLC */
220         put_bits(&s->pb,1,s->modified_quant); /* Modified Quantization: */
221         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
222         put_bits(&s->pb,3,0); /* Reserved */
223
224         put_bits(&s->pb, 3, s->pict_type == FF_P_TYPE);
225
226         put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
227         put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
228         put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
229         put_bits(&s->pb,2,0); /* Reserved */
230         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
231
232         /* This should be here if PLUSPTYPE */
233         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
234
235                 if (format == 7) {
236             /* Custom Picture Format (CPFMT) */
237             s->aspect_ratio_info= ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio);
238
239             put_bits(&s->pb,4,s->aspect_ratio_info);
240             put_bits(&s->pb,9,(s->width >> 2) - 1);
241             put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
242             put_bits(&s->pb,9,(s->height >> 2));
243             if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
244                 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
245                 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
246             }
247         }
248         if(s->custom_pcf){
249             if(ufep){
250                 put_bits(&s->pb, 1, best_clock_code);
251                 put_bits(&s->pb, 7, best_divisor);
252             }
253             put_sbits(&s->pb, 2, temp_ref>>8);
254         }
255
256         /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
257         if (s->umvplus)
258 //            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
259 //FIXME check actual requested range
260             put_bits(&s->pb,2,1); /* unlimited */
261         if(s->h263_slice_structured)
262             put_bits(&s->pb,2,0); /* no weird submodes */
263
264         put_bits(&s->pb, 5, s->qscale);
265     }
266
267     put_bits(&s->pb, 1, 0);     /* no PEI */
268
269     if(s->h263_slice_structured){
270         put_bits(&s->pb, 1, 1);
271
272         assert(s->mb_x == 0 && s->mb_y == 0);
273         ff_h263_encode_mba(s);
274
275         put_bits(&s->pb, 1, 1);
276     }
277
278     if(s->h263_aic){
279          s->y_dc_scale_table=
280          s->c_dc_scale_table= ff_aic_dc_scale_table;
281     }else{
282         s->y_dc_scale_table=
283         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
284     }
285 }
286
287 /**
288  * Encodes a group of blocks header.
289  */
290 void h263_encode_gob_header(MpegEncContext * s, int mb_line)
291 {
292     put_bits(&s->pb, 17, 1); /* GBSC */
293
294     if(s->h263_slice_structured){
295         put_bits(&s->pb, 1, 1);
296
297         ff_h263_encode_mba(s);
298
299         if(s->mb_num > 1583)
300             put_bits(&s->pb, 1, 1);
301         put_bits(&s->pb, 5, s->qscale); /* GQUANT */
302         put_bits(&s->pb, 1, 1);
303         put_bits(&s->pb, 2, s->pict_type == FF_I_TYPE); /* GFID */
304     }else{
305         int gob_number= mb_line / s->gob_index;
306
307         put_bits(&s->pb, 5, gob_number); /* GN */
308         put_bits(&s->pb, 2, s->pict_type == FF_I_TYPE); /* GFID */
309         put_bits(&s->pb, 5, s->qscale); /* GQUANT */
310     }
311 }
312
313 /**
314  * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
315  */
316 void ff_clean_h263_qscales(MpegEncContext *s){
317     int i;
318     int8_t * const qscale_table= s->current_picture.qscale_table;
319
320     ff_init_qscale_tab(s);
321
322     for(i=1; i<s->mb_num; i++){
323         if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i-1] ] >2)
324             qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i-1] ]+2;
325     }
326     for(i=s->mb_num-2; i>=0; i--){
327         if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i+1] ] >2)
328             qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i+1] ]+2;
329     }
330
331     if(s->codec_id != CODEC_ID_H263P){
332         for(i=1; i<s->mb_num; i++){
333             int mb_xy= s->mb_index2xy[i];
334
335             if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTER4V)){
336                 s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_INTER;
337             }
338         }
339     }
340 }
341
342 #endif //CONFIG_ENCODERS
343
344 #define tab_size ((signed)FF_ARRAY_ELEMS(s->direct_scale_mv[0]))
345 #define tab_bias (tab_size/2)
346
347 //used by mpeg4 and rv10 decoder
348 void ff_mpeg4_init_direct_mv(MpegEncContext *s){
349     int i;
350     for(i=0; i<tab_size; i++){
351         s->direct_scale_mv[0][i] = (i-tab_bias)*s->pb_time/s->pp_time;
352         s->direct_scale_mv[1][i] = (i-tab_bias)*(s->pb_time-s->pp_time)/s->pp_time;
353     }
354 }
355
356 static inline void ff_mpeg4_set_one_direct_mv(MpegEncContext *s, int mx, int my, int i){
357     int xy= s->block_index[i];
358     uint16_t time_pp= s->pp_time;
359     uint16_t time_pb= s->pb_time;
360     int p_mx, p_my;
361
362     p_mx= s->next_picture.motion_val[0][xy][0];
363     if((unsigned)(p_mx + tab_bias) < tab_size){
364         s->mv[0][i][0] = s->direct_scale_mv[0][p_mx + tab_bias] + mx;
365         s->mv[1][i][0] = mx ? s->mv[0][i][0] - p_mx
366                             : s->direct_scale_mv[1][p_mx + tab_bias];
367     }else{
368         s->mv[0][i][0] = p_mx*time_pb/time_pp + mx;
369         s->mv[1][i][0] = mx ? s->mv[0][i][0] - p_mx
370                             : p_mx*(time_pb - time_pp)/time_pp;
371     }
372     p_my= s->next_picture.motion_val[0][xy][1];
373     if((unsigned)(p_my + tab_bias) < tab_size){
374         s->mv[0][i][1] = s->direct_scale_mv[0][p_my + tab_bias] + my;
375         s->mv[1][i][1] = my ? s->mv[0][i][1] - p_my
376                             : s->direct_scale_mv[1][p_my + tab_bias];
377     }else{
378         s->mv[0][i][1] = p_my*time_pb/time_pp + my;
379         s->mv[1][i][1] = my ? s->mv[0][i][1] - p_my
380                             : p_my*(time_pb - time_pp)/time_pp;
381     }
382 }
383
384 #undef tab_size
385 #undef tab_bias
386
387 /**
388  *
389  * @return the mb_type
390  */
391 int ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
392     const int mb_index= s->mb_x + s->mb_y*s->mb_stride;
393     const int colocated_mb_type= s->next_picture.mb_type[mb_index];
394     uint16_t time_pp;
395     uint16_t time_pb;
396     int i;
397
398     //FIXME avoid divides
399     // try special case with shifts for 1 and 3 B-frames?
400
401     if(IS_8X8(colocated_mb_type)){
402         s->mv_type = MV_TYPE_8X8;
403         for(i=0; i<4; i++){
404             ff_mpeg4_set_one_direct_mv(s, mx, my, i);
405         }
406         return MB_TYPE_DIRECT2 | MB_TYPE_8x8 | MB_TYPE_L0L1;
407     } else if(IS_INTERLACED(colocated_mb_type)){
408         s->mv_type = MV_TYPE_FIELD;
409         for(i=0; i<2; i++){
410             int field_select= s->next_picture.ref_index[0][s->block_index[2*i]];
411             s->field_select[0][i]= field_select;
412             s->field_select[1][i]= i;
413             if(s->top_field_first){
414                 time_pp= s->pp_field_time - field_select + i;
415                 time_pb= s->pb_field_time - field_select + i;
416             }else{
417                 time_pp= s->pp_field_time + field_select - i;
418                 time_pb= s->pb_field_time + field_select - i;
419             }
420             s->mv[0][i][0] = s->p_field_mv_table[i][0][mb_index][0]*time_pb/time_pp + mx;
421             s->mv[0][i][1] = s->p_field_mv_table[i][0][mb_index][1]*time_pb/time_pp + my;
422             s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->p_field_mv_table[i][0][mb_index][0]
423                                 : s->p_field_mv_table[i][0][mb_index][0]*(time_pb - time_pp)/time_pp;
424             s->mv[1][i][1] = my ? s->mv[0][i][1] - s->p_field_mv_table[i][0][mb_index][1]
425                                 : s->p_field_mv_table[i][0][mb_index][1]*(time_pb - time_pp)/time_pp;
426         }
427         return MB_TYPE_DIRECT2 | MB_TYPE_16x8 | MB_TYPE_L0L1 | MB_TYPE_INTERLACED;
428     }else{
429         ff_mpeg4_set_one_direct_mv(s, mx, my, 0);
430         s->mv[0][1][0] = s->mv[0][2][0] = s->mv[0][3][0] = s->mv[0][0][0];
431         s->mv[0][1][1] = s->mv[0][2][1] = s->mv[0][3][1] = s->mv[0][0][1];
432         s->mv[1][1][0] = s->mv[1][2][0] = s->mv[1][3][0] = s->mv[1][0][0];
433         s->mv[1][1][1] = s->mv[1][2][1] = s->mv[1][3][1] = s->mv[1][0][1];
434         if((s->avctx->workaround_bugs & FF_BUG_DIRECT_BLOCKSIZE) || !s->quarter_sample)
435             s->mv_type= MV_TYPE_16X16;
436         else
437             s->mv_type= MV_TYPE_8X8;
438         return MB_TYPE_DIRECT2 | MB_TYPE_16x16 | MB_TYPE_L0L1; //Note see prev line
439     }
440 }
441
442 void ff_h263_update_motion_val(MpegEncContext * s){
443     const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
444                //FIXME a lot of that is only needed for !low_delay
445     const int wrap = s->b8_stride;
446     const int xy = s->block_index[0];
447
448     s->current_picture.mbskip_table[mb_xy]= s->mb_skipped;
449
450     if(s->mv_type != MV_TYPE_8X8){
451         int motion_x, motion_y;
452         if (s->mb_intra) {
453             motion_x = 0;
454             motion_y = 0;
455         } else if (s->mv_type == MV_TYPE_16X16) {
456             motion_x = s->mv[0][0][0];
457             motion_y = s->mv[0][0][1];
458         } else /*if (s->mv_type == MV_TYPE_FIELD)*/ {
459             int i;
460             motion_x = s->mv[0][0][0] + s->mv[0][1][0];
461             motion_y = s->mv[0][0][1] + s->mv[0][1][1];
462             motion_x = (motion_x>>1) | (motion_x&1);
463             for(i=0; i<2; i++){
464                 s->p_field_mv_table[i][0][mb_xy][0]= s->mv[0][i][0];
465                 s->p_field_mv_table[i][0][mb_xy][1]= s->mv[0][i][1];
466             }
467             s->current_picture.ref_index[0][xy           ]=
468             s->current_picture.ref_index[0][xy        + 1]= s->field_select[0][0];
469             s->current_picture.ref_index[0][xy + wrap    ]=
470             s->current_picture.ref_index[0][xy + wrap + 1]= s->field_select[0][1];
471         }
472
473         /* no update if 8X8 because it has been done during parsing */
474         s->current_picture.motion_val[0][xy][0] = motion_x;
475         s->current_picture.motion_val[0][xy][1] = motion_y;
476         s->current_picture.motion_val[0][xy + 1][0] = motion_x;
477         s->current_picture.motion_val[0][xy + 1][1] = motion_y;
478         s->current_picture.motion_val[0][xy + wrap][0] = motion_x;
479         s->current_picture.motion_val[0][xy + wrap][1] = motion_y;
480         s->current_picture.motion_val[0][xy + 1 + wrap][0] = motion_x;
481         s->current_picture.motion_val[0][xy + 1 + wrap][1] = motion_y;
482     }
483
484     if(s->encoding){ //FIXME encoding MUST be cleaned up
485         if (s->mv_type == MV_TYPE_8X8)
486             s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_8x8;
487         else if(s->mb_intra)
488             s->current_picture.mb_type[mb_xy]= MB_TYPE_INTRA;
489         else
490             s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_16x16;
491     }
492 }
493
494 #if CONFIG_ENCODERS
495
496 static const int dquant_code[5]= {1,0,9,2,3};
497
498 /**
499  * encodes a 8x8 block.
500  * @param block the 8x8 block
501  * @param n block index (0-3 are luma, 4-5 are chroma)
502  */
503 static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
504 {
505     int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
506     RLTable *rl;
507
508     rl = &rl_inter;
509     if (s->mb_intra && !s->h263_aic) {
510         /* DC coef */
511         level = block[0];
512         /* 255 cannot be represented, so we clamp */
513         if (level > 254) {
514             level = 254;
515             block[0] = 254;
516         }
517         /* 0 cannot be represented also */
518         else if (level < 1) {
519             level = 1;
520             block[0] = 1;
521         }
522         if (level == 128) //FIXME check rv10
523             put_bits(&s->pb, 8, 0xff);
524         else
525             put_bits(&s->pb, 8, level);
526         i = 1;
527     } else {
528         i = 0;
529         if (s->h263_aic && s->mb_intra)
530             rl = &rl_intra_aic;
531
532         if(s->alt_inter_vlc && !s->mb_intra){
533             int aic_vlc_bits=0;
534             int inter_vlc_bits=0;
535             int wrong_pos=-1;
536             int aic_code;
537
538             last_index = s->block_last_index[n];
539             last_non_zero = i - 1;
540             for (; i <= last_index; i++) {
541                 j = s->intra_scantable.permutated[i];
542                 level = block[j];
543                 if (level) {
544                     run = i - last_non_zero - 1;
545                     last = (i == last_index);
546
547                     if(level<0) level= -level;
548
549                     code = get_rl_index(rl, last, run, level);
550                     aic_code = get_rl_index(&rl_intra_aic, last, run, level);
551                     inter_vlc_bits += rl->table_vlc[code][1]+1;
552                     aic_vlc_bits   += rl_intra_aic.table_vlc[aic_code][1]+1;
553
554                     if (code == rl->n) {
555                         inter_vlc_bits += 1+6+8-1;
556                     }
557                     if (aic_code == rl_intra_aic.n) {
558                         aic_vlc_bits += 1+6+8-1;
559                         wrong_pos += run + 1;
560                     }else
561                         wrong_pos += wrong_run[aic_code];
562                     last_non_zero = i;
563                 }
564             }
565             i = 0;
566             if(aic_vlc_bits < inter_vlc_bits && wrong_pos > 63)
567                 rl = &rl_intra_aic;
568         }
569     }
570
571     /* AC coefs */
572     last_index = s->block_last_index[n];
573     last_non_zero = i - 1;
574     for (; i <= last_index; i++) {
575         j = s->intra_scantable.permutated[i];
576         level = block[j];
577         if (level) {
578             run = i - last_non_zero - 1;
579             last = (i == last_index);
580             sign = 0;
581             slevel = level;
582             if (level < 0) {
583                 sign = 1;
584                 level = -level;
585             }
586             code = get_rl_index(rl, last, run, level);
587             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
588             if (code == rl->n) {
589               if(!CONFIG_FLV_ENCODER || s->h263_flv <= 1){
590                 put_bits(&s->pb, 1, last);
591                 put_bits(&s->pb, 6, run);
592
593                 assert(slevel != 0);
594
595                 if(level < 128)
596                     put_sbits(&s->pb, 8, slevel);
597                 else{
598                     put_bits(&s->pb, 8, 128);
599                     put_sbits(&s->pb, 5, slevel);
600                     put_sbits(&s->pb, 6, slevel>>5);
601                 }
602               }else{
603                     ff_flv2_encode_ac_esc(&s->pb, slevel, level, run, last);
604               }
605             } else {
606                 put_bits(&s->pb, 1, sign);
607             }
608             last_non_zero = i;
609         }
610     }
611 }
612
613 /* Encode MV differences on H.263+ with Unrestricted MV mode */
614 static void h263p_encode_umotion(MpegEncContext * s, int val)
615 {
616     short sval = 0;
617     short i = 0;
618     short n_bits = 0;
619     short temp_val;
620     int code = 0;
621     int tcode;
622
623     if ( val == 0)
624         put_bits(&s->pb, 1, 1);
625     else if (val == 1)
626         put_bits(&s->pb, 3, 0);
627     else if (val == -1)
628         put_bits(&s->pb, 3, 2);
629     else {
630
631         sval = ((val < 0) ? (short)(-val):(short)val);
632         temp_val = sval;
633
634         while (temp_val != 0) {
635             temp_val = temp_val >> 1;
636             n_bits++;
637         }
638
639         i = n_bits - 1;
640         while (i > 0) {
641             tcode = (sval & (1 << (i-1))) >> (i-1);
642             tcode = (tcode << 1) | 1;
643             code = (code << 2) | tcode;
644             i--;
645         }
646         code = ((code << 1) | (val < 0)) << 1;
647         put_bits(&s->pb, (2*n_bits)+1, code);
648     }
649 }
650
651 static int h263_pred_dc(MpegEncContext * s, int n, int16_t **dc_val_ptr)
652 {
653     int x, y, wrap, a, c, pred_dc;
654     int16_t *dc_val;
655
656     /* find prediction */
657     if (n < 4) {
658         x = 2 * s->mb_x + (n & 1);
659         y = 2 * s->mb_y + ((n & 2) >> 1);
660         wrap = s->b8_stride;
661         dc_val = s->dc_val[0];
662     } else {
663         x = s->mb_x;
664         y = s->mb_y;
665         wrap = s->mb_stride;
666         dc_val = s->dc_val[n - 4 + 1];
667     }
668     /* B C
669      * A X
670      */
671     a = dc_val[(x - 1) + (y) * wrap];
672     c = dc_val[(x) + (y - 1) * wrap];
673
674     /* No prediction outside GOB boundary */
675     if(s->first_slice_line && n!=3){
676         if(n!=2) c= 1024;
677         if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
678     }
679     /* just DC prediction */
680     if (a != 1024 && c != 1024)
681         pred_dc = (a + c) >> 1;
682     else if (a != 1024)
683         pred_dc = a;
684     else
685         pred_dc = c;
686
687     /* we assume pred is positive */
688     *dc_val_ptr = &dc_val[x + y * wrap];
689     return pred_dc;
690 }
691
692 void h263_encode_mb(MpegEncContext * s,
693                     DCTELEM block[6][64],
694                     int motion_x, int motion_y)
695 {
696     int cbpc, cbpy, i, cbp, pred_x, pred_y;
697     int16_t pred_dc;
698     int16_t rec_intradc[6];
699     int16_t *dc_ptr[6];
700     const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1);
701
702     if (!s->mb_intra) {
703         /* compute cbp */
704         cbp= get_p_cbp(s, block, motion_x, motion_y);
705
706         if ((cbp | motion_x | motion_y | s->dquant | (s->mv_type - MV_TYPE_16X16)) == 0) {
707             /* skip macroblock */
708             put_bits(&s->pb, 1, 1);
709             if(interleaved_stats){
710                 s->misc_bits++;
711                 s->last_bits++;
712             }
713             s->skip_count++;
714
715             return;
716         }
717         put_bits(&s->pb, 1, 0);         /* mb coded */
718
719         cbpc = cbp & 3;
720         cbpy = cbp >> 2;
721         if(s->alt_inter_vlc==0 || cbpc!=3)
722             cbpy ^= 0xF;
723         if(s->dquant) cbpc+= 8;
724         if(s->mv_type==MV_TYPE_16X16){
725             put_bits(&s->pb,
726                     inter_MCBPC_bits[cbpc],
727                     inter_MCBPC_code[cbpc]);
728
729             put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
730             if(s->dquant)
731                 put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
732
733             if(interleaved_stats){
734                 s->misc_bits+= get_bits_diff(s);
735             }
736
737             /* motion vectors: 16x16 mode */
738             h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
739
740             if (!s->umvplus) {
741                 ff_h263_encode_motion_vector(s, motion_x - pred_x,
742                                                 motion_y - pred_y, 1);
743             }
744             else {
745                 h263p_encode_umotion(s, motion_x - pred_x);
746                 h263p_encode_umotion(s, motion_y - pred_y);
747                 if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
748                     /* To prevent Start Code emulation */
749                     put_bits(&s->pb,1,1);
750             }
751         }else{
752             put_bits(&s->pb,
753                     inter_MCBPC_bits[cbpc+16],
754                     inter_MCBPC_code[cbpc+16]);
755             put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
756             if(s->dquant)
757                 put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
758
759             if(interleaved_stats){
760                 s->misc_bits+= get_bits_diff(s);
761             }
762
763             for(i=0; i<4; i++){
764                 /* motion vectors: 8x8 mode*/
765                 h263_pred_motion(s, i, 0, &pred_x, &pred_y);
766
767                 motion_x= s->current_picture.motion_val[0][ s->block_index[i] ][0];
768                 motion_y= s->current_picture.motion_val[0][ s->block_index[i] ][1];
769                 if (!s->umvplus) {
770                     ff_h263_encode_motion_vector(s, motion_x - pred_x,
771                                                     motion_y - pred_y, 1);
772                 }
773                 else {
774                     h263p_encode_umotion(s, motion_x - pred_x);
775                     h263p_encode_umotion(s, motion_y - pred_y);
776                     if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
777                         /* To prevent Start Code emulation */
778                         put_bits(&s->pb,1,1);
779                 }
780             }
781         }
782
783         if(interleaved_stats){
784             s->mv_bits+= get_bits_diff(s);
785         }
786     } else {
787         assert(s->mb_intra);
788
789         cbp = 0;
790         if (s->h263_aic) {
791             /* Predict DC */
792             for(i=0; i<6; i++) {
793                 int16_t level = block[i][0];
794                 int scale;
795
796                 if(i<4) scale= s->y_dc_scale;
797                 else    scale= s->c_dc_scale;
798
799                 pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
800                 level -= pred_dc;
801                 /* Quant */
802                 if (level >= 0)
803                     level = (level + (scale>>1))/scale;
804                 else
805                     level = (level - (scale>>1))/scale;
806
807                 /* AIC can change CBP */
808                 if (level == 0 && s->block_last_index[i] == 0)
809                     s->block_last_index[i] = -1;
810
811                 if(!s->modified_quant){
812                     if (level < -127)
813                         level = -127;
814                     else if (level > 127)
815                         level = 127;
816                 }
817
818                 block[i][0] = level;
819                 /* Reconstruction */
820                 rec_intradc[i] = scale*level + pred_dc;
821                 /* Oddify */
822                 rec_intradc[i] |= 1;
823                 //if ((rec_intradc[i] % 2) == 0)
824                 //    rec_intradc[i]++;
825                 /* Clipping */
826                 if (rec_intradc[i] < 0)
827                     rec_intradc[i] = 0;
828                 else if (rec_intradc[i] > 2047)
829                     rec_intradc[i] = 2047;
830
831                 /* Update AC/DC tables */
832                 *dc_ptr[i] = rec_intradc[i];
833                 if (s->block_last_index[i] >= 0)
834                     cbp |= 1 << (5 - i);
835             }
836         }else{
837             for(i=0; i<6; i++) {
838                 /* compute cbp */
839                 if (s->block_last_index[i] >= 1)
840                     cbp |= 1 << (5 - i);
841             }
842         }
843
844         cbpc = cbp & 3;
845         if (s->pict_type == FF_I_TYPE) {
846             if(s->dquant) cbpc+=4;
847             put_bits(&s->pb,
848                 intra_MCBPC_bits[cbpc],
849                 intra_MCBPC_code[cbpc]);
850         } else {
851             if(s->dquant) cbpc+=8;
852             put_bits(&s->pb, 1, 0);     /* mb coded */
853             put_bits(&s->pb,
854                 inter_MCBPC_bits[cbpc + 4],
855                 inter_MCBPC_code[cbpc + 4]);
856         }
857         if (s->h263_aic) {
858             /* XXX: currently, we do not try to use ac prediction */
859             put_bits(&s->pb, 1, 0);     /* no AC prediction */
860         }
861         cbpy = cbp >> 2;
862         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
863         if(s->dquant)
864             put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
865
866         if(interleaved_stats){
867             s->misc_bits+= get_bits_diff(s);
868         }
869     }
870
871     for(i=0; i<6; i++) {
872         /* encode each block */
873         h263_encode_block(s, block[i], i);
874
875         /* Update INTRADC for decoding */
876         if (s->h263_aic && s->mb_intra) {
877             block[i][0] = rec_intradc[i];
878
879         }
880     }
881
882     if(interleaved_stats){
883         if (!s->mb_intra) {
884             s->p_tex_bits+= get_bits_diff(s);
885             s->f_count++;
886         }else{
887             s->i_tex_bits+= get_bits_diff(s);
888             s->i_count++;
889         }
890     }
891 }
892 #endif
893
894 void ff_h263_loop_filter(MpegEncContext * s){
895     int qp_c;
896     const int linesize  = s->linesize;
897     const int uvlinesize= s->uvlinesize;
898     const int xy = s->mb_y * s->mb_stride + s->mb_x;
899     uint8_t *dest_y = s->dest[0];
900     uint8_t *dest_cb= s->dest[1];
901     uint8_t *dest_cr= s->dest[2];
902
903 //    if(s->pict_type==FF_B_TYPE && !s->readable) return;
904
905     /*
906        Diag Top
907        Left Center
908     */
909     if(!IS_SKIP(s->current_picture.mb_type[xy])){
910         qp_c= s->qscale;
911         s->dsp.h263_v_loop_filter(dest_y+8*linesize  , linesize, qp_c);
912         s->dsp.h263_v_loop_filter(dest_y+8*linesize+8, linesize, qp_c);
913     }else
914         qp_c= 0;
915
916     if(s->mb_y){
917         int qp_dt, qp_tt, qp_tc;
918
919         if(IS_SKIP(s->current_picture.mb_type[xy-s->mb_stride]))
920             qp_tt=0;
921         else
922             qp_tt= s->current_picture.qscale_table[xy-s->mb_stride];
923
924         if(qp_c)
925             qp_tc= qp_c;
926         else
927             qp_tc= qp_tt;
928
929         if(qp_tc){
930             const int chroma_qp= s->chroma_qscale_table[qp_tc];
931             s->dsp.h263_v_loop_filter(dest_y  ,   linesize, qp_tc);
932             s->dsp.h263_v_loop_filter(dest_y+8,   linesize, qp_tc);
933
934             s->dsp.h263_v_loop_filter(dest_cb , uvlinesize, chroma_qp);
935             s->dsp.h263_v_loop_filter(dest_cr , uvlinesize, chroma_qp);
936         }
937
938         if(qp_tt)
939             s->dsp.h263_h_loop_filter(dest_y-8*linesize+8  ,   linesize, qp_tt);
940
941         if(s->mb_x){
942             if(qp_tt || IS_SKIP(s->current_picture.mb_type[xy-1-s->mb_stride]))
943                 qp_dt= qp_tt;
944             else
945                 qp_dt= s->current_picture.qscale_table[xy-1-s->mb_stride];
946
947             if(qp_dt){
948                 const int chroma_qp= s->chroma_qscale_table[qp_dt];
949                 s->dsp.h263_h_loop_filter(dest_y -8*linesize  ,   linesize, qp_dt);
950                 s->dsp.h263_h_loop_filter(dest_cb-8*uvlinesize, uvlinesize, chroma_qp);
951                 s->dsp.h263_h_loop_filter(dest_cr-8*uvlinesize, uvlinesize, chroma_qp);
952             }
953         }
954     }
955
956     if(qp_c){
957         s->dsp.h263_h_loop_filter(dest_y +8,   linesize, qp_c);
958         if(s->mb_y + 1 == s->mb_height)
959             s->dsp.h263_h_loop_filter(dest_y+8*linesize+8,   linesize, qp_c);
960     }
961
962     if(s->mb_x){
963         int qp_lc;
964         if(qp_c || IS_SKIP(s->current_picture.mb_type[xy-1]))
965             qp_lc= qp_c;
966         else
967             qp_lc= s->current_picture.qscale_table[xy-1];
968
969         if(qp_lc){
970             s->dsp.h263_h_loop_filter(dest_y,   linesize, qp_lc);
971             if(s->mb_y + 1 == s->mb_height){
972                 const int chroma_qp= s->chroma_qscale_table[qp_lc];
973                 s->dsp.h263_h_loop_filter(dest_y +8*  linesize,   linesize, qp_lc);
974                 s->dsp.h263_h_loop_filter(dest_cb             , uvlinesize, chroma_qp);
975                 s->dsp.h263_h_loop_filter(dest_cr             , uvlinesize, chroma_qp);
976             }
977         }
978     }
979 }
980
981 static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
982 {
983     int x, y, wrap, a, c, pred_dc, scale, i;
984     int16_t *dc_val, *ac_val, *ac_val1;
985
986     /* find prediction */
987     if (n < 4) {
988         x = 2 * s->mb_x + (n & 1);
989         y = 2 * s->mb_y + (n>> 1);
990         wrap = s->b8_stride;
991         dc_val = s->dc_val[0];
992         ac_val = s->ac_val[0][0];
993         scale = s->y_dc_scale;
994     } else {
995         x = s->mb_x;
996         y = s->mb_y;
997         wrap = s->mb_stride;
998         dc_val = s->dc_val[n - 4 + 1];
999         ac_val = s->ac_val[n - 4 + 1][0];
1000         scale = s->c_dc_scale;
1001     }
1002
1003     ac_val += ((y) * wrap + (x)) * 16;
1004     ac_val1 = ac_val;
1005
1006     /* B C
1007      * A X
1008      */
1009     a = dc_val[(x - 1) + (y) * wrap];
1010     c = dc_val[(x) + (y - 1) * wrap];
1011
1012     /* No prediction outside GOB boundary */
1013     if(s->first_slice_line && n!=3){
1014         if(n!=2) c= 1024;
1015         if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
1016     }
1017
1018     if (s->ac_pred) {
1019         pred_dc = 1024;
1020         if (s->h263_aic_dir) {
1021             /* left prediction */
1022             if (a != 1024) {
1023                 ac_val -= 16;
1024                 for(i=1;i<8;i++) {
1025                     block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1026                 }
1027                 pred_dc = a;
1028             }
1029         } else {
1030             /* top prediction */
1031             if (c != 1024) {
1032                 ac_val -= 16 * wrap;
1033                 for(i=1;i<8;i++) {
1034                     block[s->dsp.idct_permutation[i   ]] += ac_val[i + 8];
1035                 }
1036                 pred_dc = c;
1037             }
1038         }
1039     } else {
1040         /* just DC prediction */
1041         if (a != 1024 && c != 1024)
1042             pred_dc = (a + c) >> 1;
1043         else if (a != 1024)
1044             pred_dc = a;
1045         else
1046             pred_dc = c;
1047     }
1048
1049     /* we assume pred is positive */
1050     block[0]=block[0]*scale + pred_dc;
1051
1052     if (block[0] < 0)
1053         block[0] = 0;
1054     else
1055         block[0] |= 1;
1056
1057     /* Update AC/DC tables */
1058     dc_val[(x) + (y) * wrap] = block[0];
1059
1060     /* left copy */
1061     for(i=1;i<8;i++)
1062         ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1063     /* top copy */
1064     for(i=1;i<8;i++)
1065         ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1066 }
1067
1068 int16_t *h263_pred_motion(MpegEncContext * s, int block, int dir,
1069                         int *px, int *py)
1070 {
1071     int wrap;
1072     int16_t *A, *B, *C, (*mot_val)[2];
1073     static const int off[4]= {2, 1, 1, -1};
1074
1075     wrap = s->b8_stride;
1076     mot_val = s->current_picture.motion_val[dir] + s->block_index[block];
1077
1078     A = mot_val[ - 1];
1079     /* special case for first (slice) line */
1080     if (s->first_slice_line && block<3) {
1081         // we can't just change some MVs to simulate that as we need them for the B frames (and ME)
1082         // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1083         if(block==0){ //most common case
1084             if(s->mb_x  == s->resync_mb_x){ //rare
1085                 *px= *py = 0;
1086             }else if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1087                 C = mot_val[off[block] - wrap];
1088                 if(s->mb_x==0){
1089                     *px = C[0];
1090                     *py = C[1];
1091                 }else{
1092                     *px = mid_pred(A[0], 0, C[0]);
1093                     *py = mid_pred(A[1], 0, C[1]);
1094                 }
1095             }else{
1096                 *px = A[0];
1097                 *py = A[1];
1098             }
1099         }else if(block==1){
1100             if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1101                 C = mot_val[off[block] - wrap];
1102                 *px = mid_pred(A[0], 0, C[0]);
1103                 *py = mid_pred(A[1], 0, C[1]);
1104             }else{
1105                 *px = A[0];
1106                 *py = A[1];
1107             }
1108         }else{ /* block==2*/
1109             B = mot_val[ - wrap];
1110             C = mot_val[off[block] - wrap];
1111             if(s->mb_x == s->resync_mb_x) //rare
1112                 A[0]=A[1]=0;
1113
1114             *px = mid_pred(A[0], B[0], C[0]);
1115             *py = mid_pred(A[1], B[1], C[1]);
1116         }
1117     } else {
1118         B = mot_val[ - wrap];
1119         C = mot_val[off[block] - wrap];
1120         *px = mid_pred(A[0], B[0], C[0]);
1121         *py = mid_pred(A[1], B[1], C[1]);
1122     }
1123     return *mot_val;
1124 }
1125
1126 #if CONFIG_ENCODERS
1127
1128 /***************************************************/
1129 void ff_h263_encode_motion(MpegEncContext * s, int val, int f_code)
1130 {
1131     int range, l, bit_size, sign, code, bits;
1132
1133     if (val == 0) {
1134         /* zero vector */
1135         code = 0;
1136         put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1137     } else {
1138         bit_size = f_code - 1;
1139         range = 1 << bit_size;
1140         /* modulo encoding */
1141         l= INT_BIT - 6 - bit_size;
1142         val = (val<<l)>>l;
1143         sign = val>>31;
1144         val= (val^sign)-sign;
1145         sign&=1;
1146
1147         val--;
1148         code = (val >> bit_size) + 1;
1149         bits = val & (range - 1);
1150
1151         put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign);
1152         if (bit_size > 0) {
1153             put_bits(&s->pb, bit_size, bits);
1154         }
1155     }
1156 }
1157
1158 static void init_mv_penalty_and_fcode(MpegEncContext *s)
1159 {
1160     int f_code;
1161     int mv;
1162
1163     for(f_code=1; f_code<=MAX_FCODE; f_code++){
1164         for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1165             int len;
1166
1167             if(mv==0) len= mvtab[0][1];
1168             else{
1169                 int val, bit_size, code;
1170
1171                 bit_size = f_code - 1;
1172
1173                 val=mv;
1174                 if (val < 0)
1175                     val = -val;
1176                 val--;
1177                 code = (val >> bit_size) + 1;
1178                 if(code<33){
1179                     len= mvtab[code][1] + 1 + bit_size;
1180                 }else{
1181                     len= mvtab[32][1] + av_log2(code>>5) + 2 + bit_size;
1182                 }
1183             }
1184
1185             mv_penalty[f_code][mv+MAX_MV]= len;
1186         }
1187     }
1188
1189     for(f_code=MAX_FCODE; f_code>0; f_code--){
1190         for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1191             fcode_tab[mv+MAX_MV]= f_code;
1192         }
1193     }
1194
1195     for(mv=0; mv<MAX_MV*2+1; mv++){
1196         umv_fcode_tab[mv]= 1;
1197     }
1198 }
1199
1200 static void init_uni_h263_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1201     int slevel, run, last;
1202
1203     assert(MAX_LEVEL >= 64);
1204     assert(MAX_RUN   >= 63);
1205
1206     for(slevel=-64; slevel<64; slevel++){
1207         if(slevel==0) continue;
1208         for(run=0; run<64; run++){
1209             for(last=0; last<=1; last++){
1210                 const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1211                 int level= slevel < 0 ? -slevel : slevel;
1212                 int sign= slevel < 0 ? 1 : 0;
1213                 int bits, len, code;
1214
1215                 len_tab[index]= 100;
1216
1217                 /* ESC0 */
1218                 code= get_rl_index(rl, last, run, level);
1219                 bits= rl->table_vlc[code][0];
1220                 len=  rl->table_vlc[code][1];
1221                 bits=bits*2+sign; len++;
1222
1223                 if(code!=rl->n && len < len_tab[index]){
1224                     if(bits_tab) bits_tab[index]= bits;
1225                     len_tab [index]= len;
1226                 }
1227                 /* ESC */
1228                 bits= rl->table_vlc[rl->n][0];
1229                 len = rl->table_vlc[rl->n][1];
1230                 bits=bits*2+last; len++;
1231                 bits=bits*64+run; len+=6;
1232                 bits=bits*256+(level&0xff); len+=8;
1233
1234                 if(len < len_tab[index]){
1235                     if(bits_tab) bits_tab[index]= bits;
1236                     len_tab [index]= len;
1237                 }
1238             }
1239         }
1240     }
1241 }
1242
1243 void h263_encode_init(MpegEncContext *s)
1244 {
1245     static int done = 0;
1246
1247     if (!done) {
1248         done = 1;
1249
1250         init_rl(&rl_inter, static_rl_table_store[0]);
1251         init_rl(&rl_intra_aic, static_rl_table_store[1]);
1252
1253         init_uni_h263_rl_tab(&rl_intra_aic, NULL, uni_h263_intra_aic_rl_len);
1254         init_uni_h263_rl_tab(&rl_inter    , NULL, uni_h263_inter_rl_len);
1255
1256         init_mv_penalty_and_fcode(s);
1257     }
1258     s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
1259
1260     s->intra_ac_vlc_length     =s->inter_ac_vlc_length     = uni_h263_inter_rl_len;
1261     s->intra_ac_vlc_last_length=s->inter_ac_vlc_last_length= uni_h263_inter_rl_len + 128*64;
1262     if(s->h263_aic){
1263         s->intra_ac_vlc_length     = uni_h263_intra_aic_rl_len;
1264         s->intra_ac_vlc_last_length= uni_h263_intra_aic_rl_len + 128*64;
1265     }
1266     s->ac_esc_length= 7+1+6+8;
1267
1268     // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
1269     switch(s->codec_id){
1270     case CODEC_ID_MPEG4:
1271         s->fcode_tab= fcode_tab;
1272         break;
1273     case CODEC_ID_H263P:
1274         if(s->umvplus)
1275             s->fcode_tab= umv_fcode_tab;
1276         if(s->modified_quant){
1277             s->min_qcoeff= -2047;
1278             s->max_qcoeff=  2047;
1279         }else{
1280             s->min_qcoeff= -127;
1281             s->max_qcoeff=  127;
1282         }
1283         break;
1284         //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later
1285     case CODEC_ID_FLV1:
1286         if (s->h263_flv > 1) {
1287             s->min_qcoeff= -1023;
1288             s->max_qcoeff=  1023;
1289         } else {
1290             s->min_qcoeff= -127;
1291             s->max_qcoeff=  127;
1292         }
1293         s->y_dc_scale_table=
1294         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1295         break;
1296     default: //nothing needed - default table already set in mpegvideo.c
1297         s->min_qcoeff= -127;
1298         s->max_qcoeff=  127;
1299         s->y_dc_scale_table=
1300         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1301     }
1302 }
1303 #endif //CONFIG_ENCODERS
1304
1305 /***********************************************/
1306 /* decoding */
1307
1308 VLC intra_MCBPC_vlc;
1309 VLC inter_MCBPC_vlc;
1310 VLC cbpy_vlc;
1311 static VLC mv_vlc;
1312 static VLC h263_mbtype_b_vlc;
1313 static VLC cbpc_b_vlc;
1314
1315 /* init vlcs */
1316
1317 /* XXX: find a better solution to handle static init */
1318 void h263_decode_init_vlc(MpegEncContext *s)
1319 {
1320     static int done = 0;
1321
1322     if (!done) {
1323         done = 1;
1324
1325         INIT_VLC_STATIC(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 9,
1326                  intra_MCBPC_bits, 1, 1,
1327                  intra_MCBPC_code, 1, 1, 72);
1328         INIT_VLC_STATIC(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 28,
1329                  inter_MCBPC_bits, 1, 1,
1330                  inter_MCBPC_code, 1, 1, 198);
1331         INIT_VLC_STATIC(&cbpy_vlc, CBPY_VLC_BITS, 16,
1332                  &cbpy_tab[0][1], 2, 1,
1333                  &cbpy_tab[0][0], 2, 1, 64);
1334         INIT_VLC_STATIC(&mv_vlc, MV_VLC_BITS, 33,
1335                  &mvtab[0][1], 2, 1,
1336                  &mvtab[0][0], 2, 1, 538);
1337         init_rl(&rl_inter, static_rl_table_store[0]);
1338         init_rl(&rl_intra_aic, static_rl_table_store[1]);
1339         INIT_VLC_RL(rl_inter, 554);
1340         INIT_VLC_RL(rl_intra_aic, 554);
1341         INIT_VLC_STATIC(&h263_mbtype_b_vlc, H263_MBTYPE_B_VLC_BITS, 15,
1342                  &h263_mbtype_b_tab[0][1], 2, 1,
1343                  &h263_mbtype_b_tab[0][0], 2, 1, 80);
1344         INIT_VLC_STATIC(&cbpc_b_vlc, CBPC_B_VLC_BITS, 4,
1345                  &cbpc_b_tab[0][1], 2, 1,
1346                  &cbpc_b_tab[0][0], 2, 1, 8);
1347     }
1348 }
1349
1350 /**
1351  * Get the GOB height based on picture height.
1352  */
1353 int ff_h263_get_gob_height(MpegEncContext *s){
1354     if (s->height <= 400)
1355         return 1;
1356     else if (s->height <= 800)
1357         return  2;
1358     else
1359         return 4;
1360 }
1361
1362 int ff_h263_decode_mba(MpegEncContext *s)
1363 {
1364     int i, mb_pos;
1365
1366     for(i=0; i<6; i++){
1367         if(s->mb_num-1 <= ff_mba_max[i]) break;
1368     }
1369     mb_pos= get_bits(&s->gb, ff_mba_length[i]);
1370     s->mb_x= mb_pos % s->mb_width;
1371     s->mb_y= mb_pos / s->mb_width;
1372
1373     return mb_pos;
1374 }
1375
1376 void ff_h263_encode_mba(MpegEncContext *s)
1377 {
1378     int i, mb_pos;
1379
1380     for(i=0; i<6; i++){
1381         if(s->mb_num-1 <= ff_mba_max[i]) break;
1382     }
1383     mb_pos= s->mb_x + s->mb_width*s->mb_y;
1384     put_bits(&s->pb, ff_mba_length[i], mb_pos);
1385 }
1386
1387 /**
1388  * decodes the group of blocks header or slice header.
1389  * @return <0 if an error occurred
1390  */
1391 static int h263_decode_gob_header(MpegEncContext *s)
1392 {
1393     unsigned int val, gfid, gob_number;
1394     int left;
1395
1396     /* Check for GOB Start Code */
1397     val = show_bits(&s->gb, 16);
1398     if(val)
1399         return -1;
1400
1401         /* We have a GBSC probably with GSTUFF */
1402     skip_bits(&s->gb, 16); /* Drop the zeros */
1403     left= get_bits_left(&s->gb);
1404     //MN: we must check the bits left or we might end in a infinite loop (or segfault)
1405     for(;left>13; left--){
1406         if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
1407     }
1408     if(left<=13)
1409         return -1;
1410
1411     if(s->h263_slice_structured){
1412         if(get_bits1(&s->gb)==0)
1413             return -1;
1414
1415         ff_h263_decode_mba(s);
1416
1417         if(s->mb_num > 1583)
1418             if(get_bits1(&s->gb)==0)
1419                 return -1;
1420
1421         s->qscale = get_bits(&s->gb, 5); /* SQUANT */
1422         if(get_bits1(&s->gb)==0)
1423             return -1;
1424         gfid = get_bits(&s->gb, 2); /* GFID */
1425     }else{
1426         gob_number = get_bits(&s->gb, 5); /* GN */
1427         s->mb_x= 0;
1428         s->mb_y= s->gob_index* gob_number;
1429         gfid = get_bits(&s->gb, 2); /* GFID */
1430         s->qscale = get_bits(&s->gb, 5); /* GQUANT */
1431     }
1432
1433     if(s->mb_y >= s->mb_height)
1434         return -1;
1435
1436     if(s->qscale==0)
1437         return -1;
1438
1439     return 0;
1440 }
1441
1442 static inline void memsetw(short *tab, int val, int n)
1443 {
1444     int i;
1445     for(i=0;i<n;i++)
1446         tab[i] = val;
1447 }
1448
1449 /**
1450  * finds the next resync_marker
1451  * @param p pointer to buffer to scan
1452  * @param end pointer to the end of the buffer
1453  * @return pointer to the next resync_marker, or end if none was found
1454  */
1455 const uint8_t *ff_h263_find_resync_marker(const uint8_t *restrict p, const uint8_t * restrict end)
1456 {
1457     assert(p < end);
1458
1459     end-=2;
1460     p++;
1461     for(;p<end; p+=2){
1462         if(!*p){
1463             if     (!p[-1] && p[1]) return p - 1;
1464             else if(!p[ 1] && p[2]) return p;
1465         }
1466     }
1467     return end+2;
1468 }
1469
1470 /**
1471  * decodes the group of blocks / video packet header.
1472  * @return bit position of the resync_marker, or <0 if none was found
1473  */
1474 int ff_h263_resync(MpegEncContext *s){
1475     int left, pos, ret;
1476
1477     if(s->codec_id==CODEC_ID_MPEG4){
1478         skip_bits1(&s->gb);
1479         align_get_bits(&s->gb);
1480     }
1481
1482     if(show_bits(&s->gb, 16)==0){
1483         pos= get_bits_count(&s->gb);
1484         if(CONFIG_MPEG4_DECODER && s->codec_id==CODEC_ID_MPEG4)
1485             ret= mpeg4_decode_video_packet_header(s);
1486         else
1487             ret= h263_decode_gob_header(s);
1488         if(ret>=0)
1489             return pos;
1490     }
1491     //OK, it's not where it is supposed to be ...
1492     s->gb= s->last_resync_gb;
1493     align_get_bits(&s->gb);
1494     left= get_bits_left(&s->gb);
1495
1496     for(;left>16+1+5+5; left-=8){
1497         if(show_bits(&s->gb, 16)==0){
1498             GetBitContext bak= s->gb;
1499
1500             pos= get_bits_count(&s->gb);
1501             if(CONFIG_MPEG4_DECODER && s->codec_id==CODEC_ID_MPEG4)
1502                 ret= mpeg4_decode_video_packet_header(s);
1503             else
1504                 ret= h263_decode_gob_header(s);
1505             if(ret>=0)
1506                 return pos;
1507
1508             s->gb= bak;
1509         }
1510         skip_bits(&s->gb, 8);
1511     }
1512
1513     return -1;
1514 }
1515
1516 int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
1517 {
1518     int code, val, sign, shift, l;
1519     code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
1520
1521     if (code == 0)
1522         return pred;
1523     if (code < 0)
1524         return 0xffff;
1525
1526     sign = get_bits1(&s->gb);
1527     shift = f_code - 1;
1528     val = code;
1529     if (shift) {
1530         val = (val - 1) << shift;
1531         val |= get_bits(&s->gb, shift);
1532         val++;
1533     }
1534     if (sign)
1535         val = -val;
1536     val += pred;
1537
1538     /* modulo decoding */
1539     if (!s->h263_long_vectors) {
1540         l = INT_BIT - 5 - f_code;
1541         val = (val<<l)>>l;
1542     } else {
1543         /* horrible h263 long vector mode */
1544         if (pred < -31 && val < -63)
1545             val += 64;
1546         if (pred > 32 && val > 63)
1547             val -= 64;
1548
1549     }
1550     return val;
1551 }
1552
1553
1554 /* Decodes RVLC of H.263+ UMV */
1555 static int h263p_decode_umotion(MpegEncContext * s, int pred)
1556 {
1557    int code = 0, sign;
1558
1559    if (get_bits1(&s->gb)) /* Motion difference = 0 */
1560       return pred;
1561
1562    code = 2 + get_bits1(&s->gb);
1563
1564    while (get_bits1(&s->gb))
1565    {
1566       code <<= 1;
1567       code += get_bits1(&s->gb);
1568    }
1569    sign = code & 1;
1570    code >>= 1;
1571
1572    code = (sign) ? (pred - code) : (pred + code);
1573    dprintf(s->avctx,"H.263+ UMV Motion = %d\n", code);
1574    return code;
1575
1576 }
1577
1578 /**
1579  * read the next MVs for OBMC. yes this is a ugly hack, feel free to send a patch :)
1580  */
1581 static void preview_obmc(MpegEncContext *s){
1582     GetBitContext gb= s->gb;
1583
1584     int cbpc, i, pred_x, pred_y, mx, my;
1585     int16_t *mot_val;
1586     const int xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
1587     const int stride= s->b8_stride*2;
1588
1589     for(i=0; i<4; i++)
1590         s->block_index[i]+= 2;
1591     for(i=4; i<6; i++)
1592         s->block_index[i]+= 1;
1593     s->mb_x++;
1594
1595     assert(s->pict_type == FF_P_TYPE);
1596
1597     do{
1598         if (get_bits1(&s->gb)) {
1599             /* skip mb */
1600             mot_val = s->current_picture.motion_val[0][ s->block_index[0] ];
1601             mot_val[0       ]= mot_val[2       ]=
1602             mot_val[0+stride]= mot_val[2+stride]= 0;
1603             mot_val[1       ]= mot_val[3       ]=
1604             mot_val[1+stride]= mot_val[3+stride]= 0;
1605
1606             s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
1607             goto end;
1608         }
1609         cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
1610     }while(cbpc == 20);
1611
1612     if(cbpc & 4){
1613         s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
1614     }else{
1615         get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
1616         if (cbpc & 8) {
1617             if(s->modified_quant){
1618                 if(get_bits1(&s->gb)) skip_bits(&s->gb, 1);
1619                 else                  skip_bits(&s->gb, 5);
1620             }else
1621                 skip_bits(&s->gb, 2);
1622         }
1623
1624         if ((cbpc & 16) == 0) {
1625                 s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
1626                 /* 16x16 motion prediction */
1627                 mot_val= h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1628                 if (s->umvplus)
1629                    mx = h263p_decode_umotion(s, pred_x);
1630                 else
1631                    mx = h263_decode_motion(s, pred_x, 1);
1632
1633                 if (s->umvplus)
1634                    my = h263p_decode_umotion(s, pred_y);
1635                 else
1636                    my = h263_decode_motion(s, pred_y, 1);
1637
1638                 mot_val[0       ]= mot_val[2       ]=
1639                 mot_val[0+stride]= mot_val[2+stride]= mx;
1640                 mot_val[1       ]= mot_val[3       ]=
1641                 mot_val[1+stride]= mot_val[3+stride]= my;
1642         } else {
1643             s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
1644             for(i=0;i<4;i++) {
1645                 mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1646                 if (s->umvplus)
1647                   mx = h263p_decode_umotion(s, pred_x);
1648                 else
1649                   mx = h263_decode_motion(s, pred_x, 1);
1650
1651                 if (s->umvplus)
1652                   my = h263p_decode_umotion(s, pred_y);
1653                 else
1654                   my = h263_decode_motion(s, pred_y, 1);
1655                 if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
1656                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1657                 mot_val[0] = mx;
1658                 mot_val[1] = my;
1659             }
1660         }
1661     }
1662 end:
1663
1664     for(i=0; i<4; i++)
1665         s->block_index[i]-= 2;
1666     for(i=4; i<6; i++)
1667         s->block_index[i]-= 1;
1668     s->mb_x--;
1669
1670     s->gb= gb;
1671 }
1672
1673 static void h263_decode_dquant(MpegEncContext *s){
1674     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
1675
1676     if(s->modified_quant){
1677         if(get_bits1(&s->gb))
1678             s->qscale= modified_quant_tab[get_bits1(&s->gb)][ s->qscale ];
1679         else
1680             s->qscale= get_bits(&s->gb, 5);
1681     }else
1682         s->qscale += quant_tab[get_bits(&s->gb, 2)];
1683     ff_set_qscale(s, s->qscale);
1684 }
1685
1686 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
1687                              int n, int coded)
1688 {
1689     int code, level, i, j, last, run;
1690     RLTable *rl = &rl_inter;
1691     const uint8_t *scan_table;
1692     GetBitContext gb= s->gb;
1693
1694     scan_table = s->intra_scantable.permutated;
1695     if (s->h263_aic && s->mb_intra) {
1696         rl = &rl_intra_aic;
1697         i = 0;
1698         if (s->ac_pred) {
1699             if (s->h263_aic_dir)
1700                 scan_table = s->intra_v_scantable.permutated; /* left */
1701             else
1702                 scan_table = s->intra_h_scantable.permutated; /* top */
1703         }
1704     } else if (s->mb_intra) {
1705         /* DC coef */
1706         if(s->codec_id == CODEC_ID_RV10){
1707 #if CONFIG_RV10_DECODER
1708           if (s->rv10_version == 3 && s->pict_type == FF_I_TYPE) {
1709             int component, diff;
1710             component = (n <= 3 ? 0 : n - 4 + 1);
1711             level = s->last_dc[component];
1712             if (s->rv10_first_dc_coded[component]) {
1713                 diff = rv_decode_dc(s, n);
1714                 if (diff == 0xffff)
1715                     return -1;
1716                 level += diff;
1717                 level = level & 0xff; /* handle wrap round */
1718                 s->last_dc[component] = level;
1719             } else {
1720                 s->rv10_first_dc_coded[component] = 1;
1721             }
1722           } else {
1723                 level = get_bits(&s->gb, 8);
1724                 if (level == 255)
1725                     level = 128;
1726           }
1727 #endif
1728         }else{
1729             level = get_bits(&s->gb, 8);
1730             if((level&0x7F) == 0){
1731                 av_log(s->avctx, AV_LOG_ERROR, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);
1732                 if(s->error_recognition >= FF_ER_COMPLIANT)
1733                     return -1;
1734             }
1735             if (level == 255)
1736                 level = 128;
1737         }
1738         block[0] = level;
1739         i = 1;
1740     } else {
1741         i = 0;
1742     }
1743     if (!coded) {
1744         if (s->mb_intra && s->h263_aic)
1745             goto not_coded;
1746         s->block_last_index[n] = i - 1;
1747         return 0;
1748     }
1749 retry:
1750     for(;;) {
1751         code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1752         if (code < 0){
1753             av_log(s->avctx, AV_LOG_ERROR, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
1754             return -1;
1755         }
1756         if (code == rl->n) {
1757             /* escape */
1758             if (CONFIG_FLV_DECODER && s->h263_flv > 1) {
1759                 ff_flv2_decode_ac_esc(&s->gb, &level, &run, &last);
1760             } else {
1761                 last = get_bits1(&s->gb);
1762                 run = get_bits(&s->gb, 6);
1763                 level = (int8_t)get_bits(&s->gb, 8);
1764                 if(level == -128){
1765                     if (s->codec_id == CODEC_ID_RV10) {
1766                         /* XXX: should patch encoder too */
1767                         level = get_sbits(&s->gb, 12);
1768                     }else{
1769                         level = get_bits(&s->gb, 5);
1770                         level |= get_sbits(&s->gb, 6)<<5;
1771                     }
1772                 }
1773             }
1774         } else {
1775             run = rl->table_run[code];
1776             level = rl->table_level[code];
1777             last = code >= rl->last;
1778             if (get_bits1(&s->gb))
1779                 level = -level;
1780         }
1781         i += run;
1782         if (i >= 64){
1783             if(s->alt_inter_vlc && rl == &rl_inter && !s->mb_intra){
1784                 //Looks like a hack but no, it's the way it is supposed to work ...
1785                 rl = &rl_intra_aic;
1786                 i = 0;
1787                 s->gb= gb;
1788                 s->dsp.clear_block(block);
1789                 goto retry;
1790             }
1791             av_log(s->avctx, AV_LOG_ERROR, "run overflow at %dx%d i:%d\n", s->mb_x, s->mb_y, s->mb_intra);
1792             return -1;
1793         }
1794         j = scan_table[i];
1795         block[j] = level;
1796         if (last)
1797             break;
1798         i++;
1799     }
1800 not_coded:
1801     if (s->mb_intra && s->h263_aic) {
1802         h263_pred_acdc(s, block, n);
1803         i = 63;
1804     }
1805     s->block_last_index[n] = i;
1806     return 0;
1807 }
1808
1809 static int h263_skip_b_part(MpegEncContext *s, int cbp)
1810 {
1811     DECLARE_ALIGNED(16, DCTELEM, dblock[64]);
1812     int i, mbi;
1813
1814     /* we have to set s->mb_intra to zero to decode B-part of PB-frame correctly
1815      * but real value should be restored in order to be used later (in OBMC condition)
1816      */
1817     mbi = s->mb_intra;
1818     s->mb_intra = 0;
1819     for (i = 0; i < 6; i++) {
1820         if (h263_decode_block(s, dblock, i, cbp&32) < 0)
1821             return -1;
1822         cbp+=cbp;
1823     }
1824     s->mb_intra = mbi;
1825     return 0;
1826 }
1827
1828 static int h263_get_modb(GetBitContext *gb, int pb_frame, int *cbpb)
1829 {
1830     int c, mv = 1;
1831
1832     if (pb_frame < 3) { // h.263 Annex G and i263 PB-frame
1833         c = get_bits1(gb);
1834         if (pb_frame == 2 && c)
1835             mv = !get_bits1(gb);
1836     } else { // h.263 Annex M improved PB-frame
1837         mv = get_unary(gb, 0, 4) + 1;
1838         c = mv & 1;
1839         mv = !!(mv & 2);
1840     }
1841     if(c)
1842         *cbpb = get_bits(gb, 6);
1843     return mv;
1844 }
1845
1846 int ff_h263_decode_mb(MpegEncContext *s,
1847                       DCTELEM block[6][64])
1848 {
1849     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
1850     int16_t *mot_val;
1851     const int xy= s->mb_x + s->mb_y * s->mb_stride;
1852     int cbpb = 0, pb_mv_count = 0;
1853
1854     assert(!s->h263_pred);
1855
1856     if (s->pict_type == FF_P_TYPE) {
1857         do{
1858             if (get_bits1(&s->gb)) {
1859                 /* skip mb */
1860                 s->mb_intra = 0;
1861                 for(i=0;i<6;i++)
1862                     s->block_last_index[i] = -1;
1863                 s->mv_dir = MV_DIR_FORWARD;
1864                 s->mv_type = MV_TYPE_16X16;
1865                 s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
1866                 s->mv[0][0][0] = 0;
1867                 s->mv[0][0][1] = 0;
1868                 s->mb_skipped = !(s->obmc | s->loop_filter);
1869                 goto end;
1870             }
1871             cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
1872             if (cbpc < 0){
1873                 av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1874                 return -1;
1875             }
1876         }while(cbpc == 20);
1877
1878         s->dsp.clear_blocks(s->block[0]);
1879
1880         dquant = cbpc & 8;
1881         s->mb_intra = ((cbpc & 4) != 0);
1882         if (s->mb_intra) goto intra;
1883
1884         if(s->pb_frame && get_bits1(&s->gb))
1885             pb_mv_count = h263_get_modb(&s->gb, s->pb_frame, &cbpb);
1886         cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
1887
1888         if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
1889             cbpy ^= 0xF;
1890
1891         cbp = (cbpc & 3) | (cbpy << 2);
1892         if (dquant) {
1893             h263_decode_dquant(s);
1894         }
1895
1896         s->mv_dir = MV_DIR_FORWARD;
1897         if ((cbpc & 16) == 0) {
1898             s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
1899             /* 16x16 motion prediction */
1900             s->mv_type = MV_TYPE_16X16;
1901             h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1902             if (s->umvplus)
1903                mx = h263p_decode_umotion(s, pred_x);
1904             else
1905                mx = h263_decode_motion(s, pred_x, 1);
1906
1907             if (mx >= 0xffff)
1908                 return -1;
1909
1910             if (s->umvplus)
1911                my = h263p_decode_umotion(s, pred_y);
1912             else
1913                my = h263_decode_motion(s, pred_y, 1);
1914
1915             if (my >= 0xffff)
1916                 return -1;
1917             s->mv[0][0][0] = mx;
1918             s->mv[0][0][1] = my;
1919
1920             if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
1921                skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1922         } else {
1923             s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
1924             s->mv_type = MV_TYPE_8X8;
1925             for(i=0;i<4;i++) {
1926                 mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1927                 if (s->umvplus)
1928                   mx = h263p_decode_umotion(s, pred_x);
1929                 else
1930                   mx = h263_decode_motion(s, pred_x, 1);
1931                 if (mx >= 0xffff)
1932                     return -1;
1933
1934                 if (s->umvplus)
1935                   my = h263p_decode_umotion(s, pred_y);
1936                 else
1937                   my = h263_decode_motion(s, pred_y, 1);
1938                 if (my >= 0xffff)
1939                     return -1;
1940                 s->mv[0][i][0] = mx;
1941                 s->mv[0][i][1] = my;
1942                 if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
1943                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1944                 mot_val[0] = mx;
1945                 mot_val[1] = my;
1946             }
1947         }
1948     } else if(s->pict_type==FF_B_TYPE) {
1949         int mb_type;
1950         const int stride= s->b8_stride;
1951         int16_t *mot_val0 = s->current_picture.motion_val[0][ 2*(s->mb_x + s->mb_y*stride) ];
1952         int16_t *mot_val1 = s->current_picture.motion_val[1][ 2*(s->mb_x + s->mb_y*stride) ];
1953 //        const int mv_xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
1954
1955         //FIXME ugly
1956         mot_val0[0       ]= mot_val0[2       ]= mot_val0[0+2*stride]= mot_val0[2+2*stride]=
1957         mot_val0[1       ]= mot_val0[3       ]= mot_val0[1+2*stride]= mot_val0[3+2*stride]=
1958         mot_val1[0       ]= mot_val1[2       ]= mot_val1[0+2*stride]= mot_val1[2+2*stride]=
1959         mot_val1[1       ]= mot_val1[3       ]= mot_val1[1+2*stride]= mot_val1[3+2*stride]= 0;
1960
1961         do{
1962             mb_type= get_vlc2(&s->gb, h263_mbtype_b_vlc.table, H263_MBTYPE_B_VLC_BITS, 2);
1963             if (mb_type < 0){
1964                 av_log(s->avctx, AV_LOG_ERROR, "b mb_type damaged at %d %d\n", s->mb_x, s->mb_y);
1965                 return -1;
1966             }
1967
1968             mb_type= h263_mb_type_b_map[ mb_type ];
1969         }while(!mb_type);
1970
1971         s->mb_intra = IS_INTRA(mb_type);
1972         if(HAS_CBP(mb_type)){
1973             s->dsp.clear_blocks(s->block[0]);
1974             cbpc = get_vlc2(&s->gb, cbpc_b_vlc.table, CBPC_B_VLC_BITS, 1);
1975             if(s->mb_intra){
1976                 dquant = IS_QUANT(mb_type);
1977                 goto intra;
1978             }
1979
1980             cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
1981
1982             if (cbpy < 0){
1983                 av_log(s->avctx, AV_LOG_ERROR, "b cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
1984                 return -1;
1985             }
1986
1987             if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
1988                 cbpy ^= 0xF;
1989
1990             cbp = (cbpc & 3) | (cbpy << 2);
1991         }else
1992             cbp=0;
1993
1994         assert(!s->mb_intra);
1995
1996         if(IS_QUANT(mb_type)){
1997             h263_decode_dquant(s);
1998         }
1999
2000         if(IS_DIRECT(mb_type)){
2001             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2002             mb_type |= ff_mpeg4_set_direct_mv(s, 0, 0);
2003         }else{
2004             s->mv_dir = 0;
2005             s->mv_type= MV_TYPE_16X16;
2006 //FIXME UMV
2007
2008             if(USES_LIST(mb_type, 0)){
2009                 int16_t *mot_val= h263_pred_motion(s, 0, 0, &mx, &my);
2010                 s->mv_dir = MV_DIR_FORWARD;
2011
2012                 mx = h263_decode_motion(s, mx, 1);
2013                 my = h263_decode_motion(s, my, 1);
2014
2015                 s->mv[0][0][0] = mx;
2016                 s->mv[0][0][1] = my;
2017                 mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
2018                 mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
2019             }
2020
2021             if(USES_LIST(mb_type, 1)){
2022                 int16_t *mot_val= h263_pred_motion(s, 0, 1, &mx, &my);
2023                 s->mv_dir |= MV_DIR_BACKWARD;
2024
2025                 mx = h263_decode_motion(s, mx, 1);
2026                 my = h263_decode_motion(s, my, 1);
2027
2028                 s->mv[1][0][0] = mx;
2029                 s->mv[1][0][1] = my;
2030                 mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
2031                 mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
2032             }
2033         }
2034
2035         s->current_picture.mb_type[xy]= mb_type;
2036     } else { /* I-Frame */
2037         do{
2038             cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
2039             if (cbpc < 0){
2040                 av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
2041                 return -1;
2042             }
2043         }while(cbpc == 8);
2044
2045         s->dsp.clear_blocks(s->block[0]);
2046
2047         dquant = cbpc & 4;
2048         s->mb_intra = 1;
2049 intra:
2050         s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
2051         if (s->h263_aic) {
2052             s->ac_pred = get_bits1(&s->gb);
2053             if(s->ac_pred){
2054                 s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
2055
2056                 s->h263_aic_dir = get_bits1(&s->gb);
2057             }
2058         }else
2059             s->ac_pred = 0;
2060
2061         if(s->pb_frame && get_bits1(&s->gb))
2062             pb_mv_count = h263_get_modb(&s->gb, s->pb_frame, &cbpb);
2063         cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2064         if(cbpy<0){
2065             av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
2066             return -1;
2067         }
2068         cbp = (cbpc & 3) | (cbpy << 2);
2069         if (dquant) {
2070             h263_decode_dquant(s);
2071         }
2072
2073         pb_mv_count += !!s->pb_frame;
2074     }
2075
2076     while(pb_mv_count--){
2077         h263_decode_motion(s, 0, 1);
2078         h263_decode_motion(s, 0, 1);
2079     }
2080
2081     /* decode each block */
2082     for (i = 0; i < 6; i++) {
2083         if (h263_decode_block(s, block[i], i, cbp&32) < 0)
2084             return -1;
2085         cbp+=cbp;
2086     }
2087
2088     if(s->pb_frame && h263_skip_b_part(s, cbpb) < 0)
2089         return -1;
2090     if(s->obmc && !s->mb_intra){
2091         if(s->pict_type == FF_P_TYPE && s->mb_x+1<s->mb_width && s->mb_num_left != 1)
2092             preview_obmc(s);
2093     }
2094 end:
2095
2096         /* per-MB end of slice check */
2097     {
2098         int v= show_bits(&s->gb, 16);
2099
2100         if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
2101             v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
2102         }
2103
2104         if(v==0)
2105             return SLICE_END;
2106     }
2107
2108     return SLICE_OK;
2109 }
2110
2111 /* most is hardcoded. should extend to handle all h263 streams */
2112 int h263_decode_picture_header(MpegEncContext *s)
2113 {
2114     int format, width, height, i;
2115     uint32_t startcode;
2116
2117     align_get_bits(&s->gb);
2118
2119     startcode= get_bits(&s->gb, 22-8);
2120
2121     for(i= get_bits_left(&s->gb); i>24; i-=8) {
2122         startcode = ((startcode << 8) | get_bits(&s->gb, 8)) & 0x003FFFFF;
2123
2124         if(startcode == 0x20)
2125             break;
2126     }
2127
2128     if (startcode != 0x20) {
2129         av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");
2130         return -1;
2131     }
2132     /* temporal reference */
2133     i = get_bits(&s->gb, 8); /* picture timestamp */
2134     if( (s->picture_number&~0xFF)+i < s->picture_number)
2135         i+= 256;
2136     s->current_picture_ptr->pts=
2137     s->picture_number= (s->picture_number&~0xFF) + i;
2138
2139     /* PTYPE starts here */
2140     if (get_bits1(&s->gb) != 1) {
2141         /* marker */
2142         av_log(s->avctx, AV_LOG_ERROR, "Bad marker\n");
2143         return -1;
2144     }
2145     if (get_bits1(&s->gb) != 0) {
2146         av_log(s->avctx, AV_LOG_ERROR, "Bad H263 id\n");
2147         return -1;      /* h263 id */
2148     }
2149     skip_bits1(&s->gb);         /* split screen off */
2150     skip_bits1(&s->gb);         /* camera  off */
2151     skip_bits1(&s->gb);         /* freeze picture release off */
2152
2153     format = get_bits(&s->gb, 3);
2154     /*
2155         0    forbidden
2156         1    sub-QCIF
2157         10   QCIF
2158         7       extended PTYPE (PLUSPTYPE)
2159     */
2160
2161     if (format != 7 && format != 6) {
2162         s->h263_plus = 0;
2163         /* H.263v1 */
2164         width = h263_format[format][0];
2165         height = h263_format[format][1];
2166         if (!width)
2167             return -1;
2168
2169         s->pict_type = FF_I_TYPE + get_bits1(&s->gb);
2170
2171         s->h263_long_vectors = get_bits1(&s->gb);
2172
2173         if (get_bits1(&s->gb) != 0) {
2174             av_log(s->avctx, AV_LOG_ERROR, "H263 SAC not supported\n");
2175             return -1; /* SAC: off */
2176         }
2177         s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */
2178         s->unrestricted_mv = s->h263_long_vectors || s->obmc;
2179
2180         s->pb_frame = get_bits1(&s->gb);
2181         s->chroma_qscale= s->qscale = get_bits(&s->gb, 5);
2182         skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */
2183
2184         s->width = width;
2185         s->height = height;
2186         s->avctx->sample_aspect_ratio= (AVRational){12,11};
2187         s->avctx->time_base= (AVRational){1001, 30000};
2188     } else {
2189         int ufep;
2190
2191         /* H.263v2 */
2192         s->h263_plus = 1;
2193         ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
2194
2195         /* ufep other than 0 and 1 are reserved */
2196         if (ufep == 1) {
2197             /* OPPTYPE */
2198             format = get_bits(&s->gb, 3);
2199             dprintf(s->avctx, "ufep=1, format: %d\n", format);
2200             s->custom_pcf= get_bits1(&s->gb);
2201             s->umvplus = get_bits1(&s->gb); /* Unrestricted Motion Vector */
2202             if (get_bits1(&s->gb) != 0) {
2203                 av_log(s->avctx, AV_LOG_ERROR, "Syntax-based Arithmetic Coding (SAC) not supported\n");
2204             }
2205             s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */
2206             s->h263_aic = get_bits1(&s->gb); /* Advanced Intra Coding (AIC) */
2207             s->loop_filter= get_bits1(&s->gb);
2208             s->unrestricted_mv = s->umvplus || s->obmc || s->loop_filter;
2209
2210             s->h263_slice_structured= get_bits1(&s->gb);
2211             if (get_bits1(&s->gb) != 0) {
2212                 av_log(s->avctx, AV_LOG_ERROR, "Reference Picture Selection not supported\n");
2213             }
2214             if (get_bits1(&s->gb) != 0) {
2215                 av_log(s->avctx, AV_LOG_ERROR, "Independent Segment Decoding not supported\n");
2216             }
2217             s->alt_inter_vlc= get_bits1(&s->gb);
2218             s->modified_quant= get_bits1(&s->gb);
2219             if(s->modified_quant)
2220                 s->chroma_qscale_table= ff_h263_chroma_qscale_table;
2221
2222             skip_bits(&s->gb, 1); /* Prevent start code emulation */
2223
2224             skip_bits(&s->gb, 3); /* Reserved */
2225         } else if (ufep != 0) {
2226             av_log(s->avctx, AV_LOG_ERROR, "Bad UFEP type (%d)\n", ufep);
2227             return -1;
2228         }
2229
2230         /* MPPTYPE */
2231         s->pict_type = get_bits(&s->gb, 3);
2232         switch(s->pict_type){
2233         case 0: s->pict_type= FF_I_TYPE;break;
2234         case 1: s->pict_type= FF_P_TYPE;break;
2235         case 2: s->pict_type= FF_P_TYPE;s->pb_frame = 3;break;
2236         case 3: s->pict_type= FF_B_TYPE;break;
2237         case 7: s->pict_type= FF_I_TYPE;break; //ZYGO
2238         default:
2239             return -1;
2240         }
2241         skip_bits(&s->gb, 2);
2242         s->no_rounding = get_bits1(&s->gb);
2243         skip_bits(&s->gb, 4);
2244
2245         /* Get the picture dimensions */
2246         if (ufep) {
2247             if (format == 6) {
2248                 /* Custom Picture Format (CPFMT) */
2249                 s->aspect_ratio_info = get_bits(&s->gb, 4);
2250                 dprintf(s->avctx, "aspect: %d\n", s->aspect_ratio_info);
2251                 /* aspect ratios:
2252                 0 - forbidden
2253                 1 - 1:1
2254                 2 - 12:11 (CIF 4:3)
2255                 3 - 10:11 (525-type 4:3)
2256                 4 - 16:11 (CIF 16:9)
2257                 5 - 40:33 (525-type 16:9)
2258                 6-14 - reserved
2259                 */
2260                 width = (get_bits(&s->gb, 9) + 1) * 4;
2261                 skip_bits1(&s->gb);
2262                 height = get_bits(&s->gb, 9) * 4;
2263                 dprintf(s->avctx, "\nH.263+ Custom picture: %dx%d\n",width,height);
2264                 if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
2265                     /* aspected dimensions */
2266                     s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 8);
2267                     s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 8);
2268                 }else{
2269                     s->avctx->sample_aspect_ratio= ff_h263_pixel_aspect[s->aspect_ratio_info];
2270                 }
2271             } else {
2272                 width = h263_format[format][0];
2273                 height = h263_format[format][1];
2274                 s->avctx->sample_aspect_ratio= (AVRational){12,11};
2275             }
2276             if ((width == 0) || (height == 0))
2277                 return -1;
2278             s->width = width;
2279             s->height = height;
2280
2281             if(s->custom_pcf){
2282                 int gcd;
2283                 s->avctx->time_base.den= 1800000;
2284                 s->avctx->time_base.num= 1000 + get_bits1(&s->gb);
2285                 s->avctx->time_base.num*= get_bits(&s->gb, 7);
2286                 if(s->avctx->time_base.num == 0){
2287                     av_log(s, AV_LOG_ERROR, "zero framerate\n");
2288                     return -1;
2289                 }
2290                 gcd= av_gcd(s->avctx->time_base.den, s->avctx->time_base.num);
2291                 s->avctx->time_base.den /= gcd;
2292                 s->avctx->time_base.num /= gcd;
2293             }else{
2294                 s->avctx->time_base= (AVRational){1001, 30000};
2295             }
2296         }
2297
2298         if(s->custom_pcf){
2299             skip_bits(&s->gb, 2); //extended Temporal reference
2300         }
2301
2302         if (ufep) {
2303             if (s->umvplus) {
2304                 if(get_bits1(&s->gb)==0) /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
2305                     skip_bits1(&s->gb);
2306             }
2307             if(s->h263_slice_structured){
2308                 if (get_bits1(&s->gb) != 0) {
2309                     av_log(s->avctx, AV_LOG_ERROR, "rectangular slices not supported\n");
2310                 }
2311                 if (get_bits1(&s->gb) != 0) {
2312                     av_log(s->avctx, AV_LOG_ERROR, "unordered slices not supported\n");
2313                 }
2314             }
2315         }
2316
2317         s->qscale = get_bits(&s->gb, 5);
2318     }
2319
2320     s->mb_width = (s->width  + 15) / 16;
2321     s->mb_height = (s->height  + 15) / 16;
2322     s->mb_num = s->mb_width * s->mb_height;
2323
2324     if (s->pb_frame) {
2325         skip_bits(&s->gb, 3); /* Temporal reference for B-pictures */
2326         if (s->custom_pcf)
2327             skip_bits(&s->gb, 2); //extended Temporal reference
2328         skip_bits(&s->gb, 2); /* Quantization information for B-pictures */
2329     }
2330
2331     /* PEI */
2332     while (get_bits1(&s->gb) != 0) {
2333         skip_bits(&s->gb, 8);
2334     }
2335
2336     if(s->h263_slice_structured){
2337         if (get_bits1(&s->gb) != 1) {
2338             av_log(s->avctx, AV_LOG_ERROR, "SEPB1 marker missing\n");
2339             return -1;
2340         }
2341
2342         ff_h263_decode_mba(s);
2343
2344         if (get_bits1(&s->gb) != 1) {
2345             av_log(s->avctx, AV_LOG_ERROR, "SEPB2 marker missing\n");
2346             return -1;
2347         }
2348     }
2349     s->f_code = 1;
2350
2351     if(s->h263_aic){
2352          s->y_dc_scale_table=
2353          s->c_dc_scale_table= ff_aic_dc_scale_table;
2354     }else{
2355         s->y_dc_scale_table=
2356         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
2357     }
2358
2359         ff_h263_show_pict_info(s);
2360     if (s->pict_type == FF_I_TYPE && s->codec_tag == AV_RL32("ZYGO")){
2361         int i,j;
2362         for(i=0; i<85; i++) av_log(s->avctx, AV_LOG_DEBUG, "%d", get_bits1(&s->gb));
2363         av_log(s->avctx, AV_LOG_DEBUG, "\n");
2364         for(i=0; i<13; i++){
2365             for(j=0; j<3; j++){
2366                 int v= get_bits(&s->gb, 8);
2367                 v |= get_sbits(&s->gb, 8)<<8;
2368                 av_log(s->avctx, AV_LOG_DEBUG, " %5d", v);
2369             }
2370             av_log(s->avctx, AV_LOG_DEBUG, "\n");
2371         }
2372         for(i=0; i<50; i++) av_log(s->avctx, AV_LOG_DEBUG, "%d", get_bits1(&s->gb));
2373     }
2374
2375     return 0;
2376 }
2377
2378