1/*
2 * ITU H263 bitstream encoder
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 * This file is part of FFmpeg.
9 *
10 * FFmpeg is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * FFmpeg is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with FFmpeg; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 */
24
25/**
26 * @file
27 * h263 bitstream encoder.
28 */
29
30#include <limits.h>
31
32#include "libavutil/attributes.h"
33#include "avcodec.h"
34#include "mpegvideo.h"
35#include "h263.h"
36#include "mathops.h"
37#include "mpegutils.h"
38#include "unary.h"
39#include "flv.h"
40#include "mpeg4video.h"
41#include "internal.h"
42
43/**
44 * Table of number of bits a motion vector component needs.
45 */
46static uint8_t mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
47
48/**
49 * Minimal fcode that a motion vector component would need.
50 */
51static uint8_t fcode_tab[MAX_MV*2+1];
52
53/**
54 * Minimal fcode that a motion vector component would need in umv.
55 * All entries in this table are 1.
56 */
57static uint8_t umv_fcode_tab[MAX_MV*2+1];
58
59//unified encoding tables for run length encoding of coefficients
60//unified in the sense that the specification specifies the encoding in several steps.
61static uint8_t  uni_h263_intra_aic_rl_len [64*64*2*2];
62static uint8_t  uni_h263_inter_rl_len [64*64*2*2];
63//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
64//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
65#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
66
67static const uint8_t wrong_run[102] = {
68 1,  2,  3,  5,  4, 10,  9,  8,
6911, 15, 17, 16, 23, 22, 21, 20,
7019, 18, 25, 24, 27, 26, 11,  7,
71 6,  1,  2, 13,  2,  2,  2,  2,
72 6, 12,  3,  9,  1,  3,  4,  3,
73 7,  4,  1,  1,  5,  5, 14,  6,
74 1,  7,  1,  8,  1,  1,  1,  1,
7510,  1,  1,  5,  9, 17, 25, 24,
7629, 33, 32, 41,  2, 23, 28, 31,
77 3, 22, 30,  4, 27, 40,  8, 26,
78 6, 39,  7, 38, 16, 37, 15, 10,
7911, 12, 13, 14,  1, 21, 20, 18,
8019,  2,  1, 34, 35, 36
81};
82
83/**
84 * Return the 4 bit value that specifies the given aspect ratio.
85 * This may be one of the standard aspect ratios or it specifies
86 * that the aspect will be stored explicitly later.
87 */
88av_const int ff_h263_aspect_to_info(AVRational aspect){
89    int i;
90
91    if(aspect.num==0) aspect= (AVRational){1,1};
92
93    for(i=1; i<6; i++){
94        if(av_cmp_q(ff_h263_pixel_aspect[i], aspect) == 0){
95            return i;
96        }
97    }
98
99    return FF_ASPECT_EXTENDED;
100}
101
102void ff_h263_encode_picture_header(MpegEncContext * s, int picture_number)
103{
104    int format, coded_frame_rate, coded_frame_rate_base, i, temp_ref;
105    int best_clock_code=1;
106    int best_divisor=60;
107    int best_error= INT_MAX;
108
109    if(s->h263_plus){
110        for(i=0; i<2; i++){
111            int div, error;
112            div= (s->avctx->time_base.num*1800000LL + 500LL*s->avctx->time_base.den) / ((1000LL+i)*s->avctx->time_base.den);
113            div= av_clip(div, 1, 127);
114            error= FFABS(s->avctx->time_base.num*1800000LL - (1000LL+i)*s->avctx->time_base.den*div);
115            if(error < best_error){
116                best_error= error;
117                best_divisor= div;
118                best_clock_code= i;
119            }
120        }
121    }
122    s->custom_pcf= best_clock_code!=1 || best_divisor!=60;
123    coded_frame_rate= 1800000;
124    coded_frame_rate_base= (1000+best_clock_code)*best_divisor;
125
126    avpriv_align_put_bits(&s->pb);
127
128    /* Update the pointer to last GOB */
129    s->ptr_lastgob = put_bits_ptr(&s->pb);
130    put_bits(&s->pb, 22, 0x20); /* PSC */
131    temp_ref= s->picture_number * (int64_t)coded_frame_rate * s->avctx->time_base.num / //FIXME use timestamp
132                         (coded_frame_rate_base * (int64_t)s->avctx->time_base.den);
133    put_sbits(&s->pb, 8, temp_ref); /* TemporalReference */
134
135    put_bits(&s->pb, 1, 1);     /* marker */
136    put_bits(&s->pb, 1, 0);     /* h263 id */
137    put_bits(&s->pb, 1, 0);     /* split screen off */
138    put_bits(&s->pb, 1, 0);     /* camera  off */
139    put_bits(&s->pb, 1, 0);     /* freeze picture release off */
140
141    format = ff_match_2uint16(ff_h263_format, FF_ARRAY_ELEMS(ff_h263_format), s->width, s->height);
142    if (!s->h263_plus) {
143        /* H.263v1 */
144        put_bits(&s->pb, 3, format);
145        put_bits(&s->pb, 1, (s->pict_type == AV_PICTURE_TYPE_P));
146        /* By now UMV IS DISABLED ON H.263v1, since the restrictions
147        of H.263v1 UMV implies to check the predicted MV after
148        calculation of the current MB to see if we're on the limits */
149        put_bits(&s->pb, 1, 0);         /* Unrestricted Motion Vector: off */
150        put_bits(&s->pb, 1, 0);         /* SAC: off */
151        put_bits(&s->pb, 1, s->obmc);   /* Advanced Prediction */
152        put_bits(&s->pb, 1, 0);         /* only I/P frames, no PB frame */
153        put_bits(&s->pb, 5, s->qscale);
154        put_bits(&s->pb, 1, 0);         /* Continuous Presence Multipoint mode: off */
155    } else {
156        int ufep=1;
157        /* H.263v2 */
158        /* H.263 Plus PTYPE */
159
160        put_bits(&s->pb, 3, 7);
161        put_bits(&s->pb,3,ufep); /* Update Full Extended PTYPE */
162        if (format == 8)
163            put_bits(&s->pb,3,6); /* Custom Source Format */
164        else
165            put_bits(&s->pb, 3, format);
166
167        put_bits(&s->pb,1, s->custom_pcf);
168        put_bits(&s->pb,1, s->umvplus); /* Unrestricted Motion Vector */
169        put_bits(&s->pb,1,0); /* SAC: off */
170        put_bits(&s->pb,1,s->obmc); /* Advanced Prediction Mode */
171        put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
172        put_bits(&s->pb,1,s->loop_filter); /* Deblocking Filter */
173        put_bits(&s->pb,1,s->h263_slice_structured); /* Slice Structured */
174        put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
175        put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
176        put_bits(&s->pb,1,s->alt_inter_vlc); /* Alternative Inter VLC */
177        put_bits(&s->pb,1,s->modified_quant); /* Modified Quantization: */
178        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
179        put_bits(&s->pb,3,0); /* Reserved */
180
181        put_bits(&s->pb, 3, s->pict_type == AV_PICTURE_TYPE_P);
182
183        put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
184        put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
185        put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
186        put_bits(&s->pb,2,0); /* Reserved */
187        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
188
189        /* This should be here if PLUSPTYPE */
190        put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
191
192        if (format == 8) {
193            /* Custom Picture Format (CPFMT) */
194            s->aspect_ratio_info= ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio);
195
196            put_bits(&s->pb,4,s->aspect_ratio_info);
197            put_bits(&s->pb,9,(s->width >> 2) - 1);
198            put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
199            put_bits(&s->pb,9,(s->height >> 2));
200            if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
201                put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
202                put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
203            }
204        }
205        if(s->custom_pcf){
206            if(ufep){
207                put_bits(&s->pb, 1, best_clock_code);
208                put_bits(&s->pb, 7, best_divisor);
209            }
210            put_sbits(&s->pb, 2, temp_ref>>8);
211        }
212
213        /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
214        if (s->umvplus)
215//            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
216//FIXME check actual requested range
217            put_bits(&s->pb,2,1); /* unlimited */
218        if(s->h263_slice_structured)
219            put_bits(&s->pb,2,0); /* no weird submodes */
220
221        put_bits(&s->pb, 5, s->qscale);
222    }
223
224    put_bits(&s->pb, 1, 0);     /* no PEI */
225
226    if(s->h263_slice_structured){
227        put_bits(&s->pb, 1, 1);
228
229        av_assert1(s->mb_x == 0 && s->mb_y == 0);
230        ff_h263_encode_mba(s);
231
232        put_bits(&s->pb, 1, 1);
233    }
234}
235
236/**
237 * Encode a group of blocks header.
238 */
239void ff_h263_encode_gob_header(MpegEncContext * s, int mb_line)
240{
241    put_bits(&s->pb, 17, 1); /* GBSC */
242
243    if(s->h263_slice_structured){
244        put_bits(&s->pb, 1, 1);
245
246        ff_h263_encode_mba(s);
247
248        if(s->mb_num > 1583)
249            put_bits(&s->pb, 1, 1);
250        put_bits(&s->pb, 5, s->qscale); /* GQUANT */
251        put_bits(&s->pb, 1, 1);
252        put_bits(&s->pb, 2, s->pict_type == AV_PICTURE_TYPE_I); /* GFID */
253    }else{
254        int gob_number= mb_line / s->gob_index;
255
256        put_bits(&s->pb, 5, gob_number); /* GN */
257        put_bits(&s->pb, 2, s->pict_type == AV_PICTURE_TYPE_I); /* GFID */
258        put_bits(&s->pb, 5, s->qscale); /* GQUANT */
259    }
260}
261
262/**
263 * modify qscale so that encoding is actually possible in h263 (limit difference to -2..2)
264 */
265void ff_clean_h263_qscales(MpegEncContext *s){
266    int i;
267    int8_t * const qscale_table = s->current_picture.qscale_table;
268
269    ff_init_qscale_tab(s);
270
271    for(i=1; i<s->mb_num; i++){
272        if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i-1] ] >2)
273            qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i-1] ]+2;
274    }
275    for(i=s->mb_num-2; i>=0; i--){
276        if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i+1] ] >2)
277            qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i+1] ]+2;
278    }
279
280    if(s->codec_id != AV_CODEC_ID_H263P){
281        for(i=1; i<s->mb_num; i++){
282            int mb_xy= s->mb_index2xy[i];
283
284            if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTER4V)){
285                s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_INTER;
286            }
287        }
288    }
289}
290
291static const int dquant_code[5]= {1,0,9,2,3};
292
293/**
294 * Encode an 8x8 block.
295 * @param block the 8x8 block
296 * @param n block index (0-3 are luma, 4-5 are chroma)
297 */
298static void h263_encode_block(MpegEncContext * s, int16_t * block, int n)
299{
300    int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
301    RLTable *rl;
302
303    rl = &ff_h263_rl_inter;
304    if (s->mb_intra && !s->h263_aic) {
305        /* DC coef */
306        level = block[0];
307        /* 255 cannot be represented, so we clamp */
308        if (level > 254) {
309            level = 254;
310            block[0] = 254;
311        }
312        /* 0 cannot be represented also */
313        else if (level < 1) {
314            level = 1;
315            block[0] = 1;
316        }
317        if (level == 128) //FIXME check rv10
318            put_bits(&s->pb, 8, 0xff);
319        else
320            put_bits(&s->pb, 8, level);
321        i = 1;
322    } else {
323        i = 0;
324        if (s->h263_aic && s->mb_intra)
325            rl = &ff_rl_intra_aic;
326
327        if(s->alt_inter_vlc && !s->mb_intra){
328            int aic_vlc_bits=0;
329            int inter_vlc_bits=0;
330            int wrong_pos=-1;
331            int aic_code;
332
333            last_index = s->block_last_index[n];
334            last_non_zero = i - 1;
335            for (; i <= last_index; i++) {
336                j = s->intra_scantable.permutated[i];
337                level = block[j];
338                if (level) {
339                    run = i - last_non_zero - 1;
340                    last = (i == last_index);
341
342                    if(level<0) level= -level;
343
344                    code = get_rl_index(rl, last, run, level);
345                    aic_code = get_rl_index(&ff_rl_intra_aic, last, run, level);
346                    inter_vlc_bits += rl->table_vlc[code][1]+1;
347                    aic_vlc_bits   += ff_rl_intra_aic.table_vlc[aic_code][1]+1;
348
349                    if (code == rl->n) {
350                        inter_vlc_bits += 1+6+8-1;
351                    }
352                    if (aic_code == ff_rl_intra_aic.n) {
353                        aic_vlc_bits += 1+6+8-1;
354                        wrong_pos += run + 1;
355                    }else
356                        wrong_pos += wrong_run[aic_code];
357                    last_non_zero = i;
358                }
359            }
360            i = 0;
361            if(aic_vlc_bits < inter_vlc_bits && wrong_pos > 63)
362                rl = &ff_rl_intra_aic;
363        }
364    }
365
366    /* AC coefs */
367    last_index = s->block_last_index[n];
368    last_non_zero = i - 1;
369    for (; i <= last_index; i++) {
370        j = s->intra_scantable.permutated[i];
371        level = block[j];
372        if (level) {
373            run = i - last_non_zero - 1;
374            last = (i == last_index);
375            sign = 0;
376            slevel = level;
377            if (level < 0) {
378                sign = 1;
379                level = -level;
380            }
381            code = get_rl_index(rl, last, run, level);
382            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
383            if (code == rl->n) {
384              if(!CONFIG_FLV_ENCODER || s->h263_flv <= 1){
385                put_bits(&s->pb, 1, last);
386                put_bits(&s->pb, 6, run);
387
388                av_assert2(slevel != 0);
389
390                if(level < 128)
391                    put_sbits(&s->pb, 8, slevel);
392                else{
393                    put_bits(&s->pb, 8, 128);
394                    put_sbits(&s->pb, 5, slevel);
395                    put_sbits(&s->pb, 6, slevel>>5);
396                }
397              }else{
398                    ff_flv2_encode_ac_esc(&s->pb, slevel, level, run, last);
399              }
400            } else {
401                put_bits(&s->pb, 1, sign);
402            }
403            last_non_zero = i;
404        }
405    }
406}
407
408/* Encode MV differences on H.263+ with Unrestricted MV mode */
409static void h263p_encode_umotion(MpegEncContext * s, int val)
410{
411    short sval = 0;
412    short i = 0;
413    short n_bits = 0;
414    short temp_val;
415    int code = 0;
416    int tcode;
417
418    if ( val == 0)
419        put_bits(&s->pb, 1, 1);
420    else if (val == 1)
421        put_bits(&s->pb, 3, 0);
422    else if (val == -1)
423        put_bits(&s->pb, 3, 2);
424    else {
425
426        sval = ((val < 0) ? (short)(-val):(short)val);
427        temp_val = sval;
428
429        while (temp_val != 0) {
430            temp_val = temp_val >> 1;
431            n_bits++;
432        }
433
434        i = n_bits - 1;
435        while (i > 0) {
436            tcode = (sval & (1 << (i-1))) >> (i-1);
437            tcode = (tcode << 1) | 1;
438            code = (code << 2) | tcode;
439            i--;
440        }
441        code = ((code << 1) | (val < 0)) << 1;
442        put_bits(&s->pb, (2*n_bits)+1, code);
443    }
444}
445
446void ff_h263_encode_mb(MpegEncContext * s,
447                       int16_t block[6][64],
448                       int motion_x, int motion_y)
449{
450    int cbpc, cbpy, i, cbp, pred_x, pred_y;
451    int16_t pred_dc;
452    int16_t rec_intradc[6];
453    int16_t *dc_ptr[6];
454    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1);
455
456    if (!s->mb_intra) {
457        /* compute cbp */
458        cbp= get_p_cbp(s, block, motion_x, motion_y);
459
460        if ((cbp | motion_x | motion_y | s->dquant | (s->mv_type - MV_TYPE_16X16)) == 0) {
461            /* skip macroblock */
462            put_bits(&s->pb, 1, 1);
463            if(interleaved_stats){
464                s->misc_bits++;
465                s->last_bits++;
466            }
467            s->skip_count++;
468
469            return;
470        }
471        put_bits(&s->pb, 1, 0);         /* mb coded */
472
473        cbpc = cbp & 3;
474        cbpy = cbp >> 2;
475        if(s->alt_inter_vlc==0 || cbpc!=3)
476            cbpy ^= 0xF;
477        if(s->dquant) cbpc+= 8;
478        if(s->mv_type==MV_TYPE_16X16){
479            put_bits(&s->pb,
480                    ff_h263_inter_MCBPC_bits[cbpc],
481                    ff_h263_inter_MCBPC_code[cbpc]);
482
483            put_bits(&s->pb, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
484            if(s->dquant)
485                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
486
487            if(interleaved_stats){
488                s->misc_bits+= get_bits_diff(s);
489            }
490
491            /* motion vectors: 16x16 mode */
492            ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
493
494            if (!s->umvplus) {
495                ff_h263_encode_motion_vector(s, motion_x - pred_x,
496                                                motion_y - pred_y, 1);
497            }
498            else {
499                h263p_encode_umotion(s, motion_x - pred_x);
500                h263p_encode_umotion(s, motion_y - pred_y);
501                if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
502                    /* To prevent Start Code emulation */
503                    put_bits(&s->pb,1,1);
504            }
505        }else{
506            put_bits(&s->pb,
507                    ff_h263_inter_MCBPC_bits[cbpc+16],
508                    ff_h263_inter_MCBPC_code[cbpc+16]);
509            put_bits(&s->pb, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
510            if(s->dquant)
511                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
512
513            if(interleaved_stats){
514                s->misc_bits+= get_bits_diff(s);
515            }
516
517            for(i=0; i<4; i++){
518                /* motion vectors: 8x8 mode*/
519                ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
520
521                motion_x = s->current_picture.motion_val[0][s->block_index[i]][0];
522                motion_y = s->current_picture.motion_val[0][s->block_index[i]][1];
523                if (!s->umvplus) {
524                    ff_h263_encode_motion_vector(s, motion_x - pred_x,
525                                                    motion_y - pred_y, 1);
526                }
527                else {
528                    h263p_encode_umotion(s, motion_x - pred_x);
529                    h263p_encode_umotion(s, motion_y - pred_y);
530                    if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
531                        /* To prevent Start Code emulation */
532                        put_bits(&s->pb,1,1);
533                }
534            }
535        }
536
537        if(interleaved_stats){
538            s->mv_bits+= get_bits_diff(s);
539        }
540    } else {
541        av_assert2(s->mb_intra);
542
543        cbp = 0;
544        if (s->h263_aic) {
545            /* Predict DC */
546            for(i=0; i<6; i++) {
547                int16_t level = block[i][0];
548                int scale;
549
550                if(i<4) scale= s->y_dc_scale;
551                else    scale= s->c_dc_scale;
552
553                pred_dc = ff_h263_pred_dc(s, i, &dc_ptr[i]);
554                level -= pred_dc;
555                /* Quant */
556                if (level >= 0)
557                    level = (level + (scale>>1))/scale;
558                else
559                    level = (level - (scale>>1))/scale;
560
561                if(!s->modified_quant){
562                    if (level < -127)
563                        level = -127;
564                    else if (level > 127)
565                        level = 127;
566                }
567
568                block[i][0] = level;
569                /* Reconstruction */
570                rec_intradc[i] = scale*level + pred_dc;
571                /* Oddify */
572                rec_intradc[i] |= 1;
573                //if ((rec_intradc[i] % 2) == 0)
574                //    rec_intradc[i]++;
575                /* Clipping */
576                if (rec_intradc[i] < 0)
577                    rec_intradc[i] = 0;
578                else if (rec_intradc[i] > 2047)
579                    rec_intradc[i] = 2047;
580
581                /* Update AC/DC tables */
582                *dc_ptr[i] = rec_intradc[i];
583                /* AIC can change CBP */
584                if (s->block_last_index[i] > 0 ||
585                    (s->block_last_index[i] == 0 && level !=0))
586                    cbp |= 1 << (5 - i);
587            }
588        }else{
589            for(i=0; i<6; i++) {
590                /* compute cbp */
591                if (s->block_last_index[i] >= 1)
592                    cbp |= 1 << (5 - i);
593            }
594        }
595
596        cbpc = cbp & 3;
597        if (s->pict_type == AV_PICTURE_TYPE_I) {
598            if(s->dquant) cbpc+=4;
599            put_bits(&s->pb,
600                ff_h263_intra_MCBPC_bits[cbpc],
601                ff_h263_intra_MCBPC_code[cbpc]);
602        } else {
603            if(s->dquant) cbpc+=8;
604            put_bits(&s->pb, 1, 0);     /* mb coded */
605            put_bits(&s->pb,
606                ff_h263_inter_MCBPC_bits[cbpc + 4],
607                ff_h263_inter_MCBPC_code[cbpc + 4]);
608        }
609        if (s->h263_aic) {
610            /* XXX: currently, we do not try to use ac prediction */
611            put_bits(&s->pb, 1, 0);     /* no AC prediction */
612        }
613        cbpy = cbp >> 2;
614        put_bits(&s->pb, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
615        if(s->dquant)
616            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
617
618        if(interleaved_stats){
619            s->misc_bits+= get_bits_diff(s);
620        }
621    }
622
623    for(i=0; i<6; i++) {
624        /* encode each block */
625        h263_encode_block(s, block[i], i);
626
627        /* Update INTRADC for decoding */
628        if (s->h263_aic && s->mb_intra) {
629            block[i][0] = rec_intradc[i];
630
631        }
632    }
633
634    if(interleaved_stats){
635        if (!s->mb_intra) {
636            s->p_tex_bits+= get_bits_diff(s);
637            s->f_count++;
638        }else{
639            s->i_tex_bits+= get_bits_diff(s);
640            s->i_count++;
641        }
642    }
643}
644
645void ff_h263_encode_motion(MpegEncContext * s, int val, int f_code)
646{
647    int range, bit_size, sign, code, bits;
648
649    if (val == 0) {
650        /* zero vector */
651        code = 0;
652        put_bits(&s->pb, ff_mvtab[code][1], ff_mvtab[code][0]);
653    } else {
654        bit_size = f_code - 1;
655        range = 1 << bit_size;
656        /* modulo encoding */
657        val = sign_extend(val, 6 + bit_size);
658        sign = val>>31;
659        val= (val^sign)-sign;
660        sign&=1;
661
662        val--;
663        code = (val >> bit_size) + 1;
664        bits = val & (range - 1);
665
666        put_bits(&s->pb, ff_mvtab[code][1] + 1, (ff_mvtab[code][0] << 1) | sign);
667        if (bit_size > 0) {
668            put_bits(&s->pb, bit_size, bits);
669        }
670    }
671}
672
673static av_cold void init_mv_penalty_and_fcode(MpegEncContext *s)
674{
675    int f_code;
676    int mv;
677
678    for(f_code=1; f_code<=MAX_FCODE; f_code++){
679        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
680            int len;
681
682            if(mv==0) len= ff_mvtab[0][1];
683            else{
684                int val, bit_size, code;
685
686                bit_size = f_code - 1;
687
688                val=mv;
689                if (val < 0)
690                    val = -val;
691                val--;
692                code = (val >> bit_size) + 1;
693                if(code<33){
694                    len= ff_mvtab[code][1] + 1 + bit_size;
695                }else{
696                    len= ff_mvtab[32][1] + av_log2(code>>5) + 2 + bit_size;
697                }
698            }
699
700            mv_penalty[f_code][mv+MAX_MV]= len;
701        }
702    }
703
704    for(f_code=MAX_FCODE; f_code>0; f_code--){
705        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
706            fcode_tab[mv+MAX_MV]= f_code;
707        }
708    }
709
710    for(mv=0; mv<MAX_MV*2+1; mv++){
711        umv_fcode_tab[mv]= 1;
712    }
713}
714
715static av_cold void init_uni_h263_rl_tab(RLTable *rl, uint32_t *bits_tab,
716                                         uint8_t *len_tab)
717{
718    int slevel, run, last;
719
720    av_assert0(MAX_LEVEL >= 64);
721    av_assert0(MAX_RUN   >= 63);
722
723    for(slevel=-64; slevel<64; slevel++){
724        if(slevel==0) continue;
725        for(run=0; run<64; run++){
726            for(last=0; last<=1; last++){
727                const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
728                int level= slevel < 0 ? -slevel : slevel;
729                int sign= slevel < 0 ? 1 : 0;
730                int bits, len, code;
731
732                len_tab[index]= 100;
733
734                /* ESC0 */
735                code= get_rl_index(rl, last, run, level);
736                bits= rl->table_vlc[code][0];
737                len=  rl->table_vlc[code][1];
738                bits=bits*2+sign; len++;
739
740                if(code!=rl->n && len < len_tab[index]){
741                    if(bits_tab) bits_tab[index]= bits;
742                    len_tab [index]= len;
743                }
744                /* ESC */
745                bits= rl->table_vlc[rl->n][0];
746                len = rl->table_vlc[rl->n][1];
747                bits=bits*2+last; len++;
748                bits=bits*64+run; len+=6;
749                bits=bits*256+(level&0xff); len+=8;
750
751                if(len < len_tab[index]){
752                    if(bits_tab) bits_tab[index]= bits;
753                    len_tab [index]= len;
754                }
755            }
756        }
757    }
758}
759
760av_cold void ff_h263_encode_init(MpegEncContext *s)
761{
762    static int done = 0;
763
764    if (!done) {
765        done = 1;
766
767        ff_init_rl(&ff_h263_rl_inter, ff_h263_static_rl_table_store[0]);
768        ff_init_rl(&ff_rl_intra_aic, ff_h263_static_rl_table_store[1]);
769
770        init_uni_h263_rl_tab(&ff_rl_intra_aic, NULL, uni_h263_intra_aic_rl_len);
771        init_uni_h263_rl_tab(&ff_h263_rl_inter    , NULL, uni_h263_inter_rl_len);
772
773        init_mv_penalty_and_fcode(s);
774    }
775    s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
776
777    s->intra_ac_vlc_length     =s->inter_ac_vlc_length     = uni_h263_inter_rl_len;
778    s->intra_ac_vlc_last_length=s->inter_ac_vlc_last_length= uni_h263_inter_rl_len + 128*64;
779    if(s->h263_aic){
780        s->intra_ac_vlc_length     = uni_h263_intra_aic_rl_len;
781        s->intra_ac_vlc_last_length= uni_h263_intra_aic_rl_len + 128*64;
782    }
783    s->ac_esc_length= 7+1+6+8;
784
785    // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
786    switch(s->codec_id){
787    case AV_CODEC_ID_MPEG4:
788        s->fcode_tab= fcode_tab;
789        break;
790    case AV_CODEC_ID_H263P:
791        if(s->umvplus)
792            s->fcode_tab= umv_fcode_tab;
793        if(s->modified_quant){
794            s->min_qcoeff= -2047;
795            s->max_qcoeff=  2047;
796        }else{
797            s->min_qcoeff= -127;
798            s->max_qcoeff=  127;
799        }
800        break;
801        //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later
802    case AV_CODEC_ID_FLV1:
803        if (s->h263_flv > 1) {
804            s->min_qcoeff= -1023;
805            s->max_qcoeff=  1023;
806        } else {
807            s->min_qcoeff= -127;
808            s->max_qcoeff=  127;
809        }
810        break;
811    default: //nothing needed - default table already set in mpegvideo.c
812        s->min_qcoeff= -127;
813        s->max_qcoeff=  127;
814    }
815    if(s->h263_aic){
816         s->y_dc_scale_table=
817         s->c_dc_scale_table= ff_aic_dc_scale_table;
818    }else{
819        s->y_dc_scale_table=
820        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
821    }
822}
823
824void ff_h263_encode_mba(MpegEncContext *s)
825{
826    int i, mb_pos;
827
828    for(i=0; i<6; i++){
829        if(s->mb_num-1 <= ff_mba_max[i]) break;
830    }
831    mb_pos= s->mb_x + s->mb_width*s->mb_y;
832    put_bits(&s->pb, ff_mba_length[i], mb_pos);
833}
834