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