64cbecba9a75b6319107654aad06953ac7e9e812
[ffmpeg.git] / libavcodec / mpeg4videoenc.c
1 /*
2  * MPEG4 encoder.
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "mpegvideo.h"
24 #include "h263.h"
25 #include "mpeg4video.h"
26
27 //The uni_DCtab_* tables below contain unified bits+length tables to encode DC
28 //differences in mpeg4. Unified in the sense that the specification specifies
29 //this encoding in several steps.
30 static uint8_t uni_DCtab_lum_len[512];
31 static uint8_t uni_DCtab_chrom_len[512];
32 static uint16_t uni_DCtab_lum_bits[512];
33 static uint16_t uni_DCtab_chrom_bits[512];
34
35 //unified encoding tables for run length encoding of coefficients
36 //unified in the sense that the specification specifies the encoding in several steps.
37 static uint32_t uni_mpeg4_intra_rl_bits[64*64*2*2];
38 static uint8_t  uni_mpeg4_intra_rl_len [64*64*2*2];
39 static uint32_t uni_mpeg4_inter_rl_bits[64*64*2*2];
40 static uint8_t  uni_mpeg4_inter_rl_len [64*64*2*2];
41 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
42 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
43 #define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
44
45 /* mpeg4
46 inter
47 max level: 24/6
48 max run: 53/63
49
50 intra
51 max level: 53/16
52 max run: 29/41
53 */
54
55
56 /**
57  * Returns the number of bits that encoding the 8x8 block in block would need.
58  * @param[in]  block_last_index last index in scantable order that refers to a non zero element in block.
59  */
60 static inline int get_block_rate(MpegEncContext * s, DCTELEM block[64], int block_last_index, uint8_t scantable[64]){
61     int last=0;
62     int j;
63     int rate=0;
64
65     for(j=1; j<=block_last_index; j++){
66         const int index= scantable[j];
67         int level= block[index];
68         if(level){
69             level+= 64;
70             if((level&(~127)) == 0){
71                 if(j<block_last_index) rate+= s->intra_ac_vlc_length     [UNI_AC_ENC_INDEX(j-last-1, level)];
72                 else                   rate+= s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j-last-1, level)];
73             }else
74                 rate += s->ac_esc_length;
75
76             last= j;
77         }
78     }
79
80     return rate;
81 }
82
83
84 /**
85  * Restores the ac coefficients in block that have been changed by decide_ac_pred().
86  * This function also restores s->block_last_index.
87  * @param[in,out] block MB coefficients, these will be restored
88  * @param[in] dir ac prediction direction for each 8x8 block
89  * @param[out] st scantable for each 8x8 block
90  * @param[in] zigzag_last_index index refering to the last non zero coefficient in zigzag order
91  */
92 static inline void restore_ac_coeffs(MpegEncContext * s, DCTELEM block[6][64], const int dir[6], uint8_t *st[6], const int zigzag_last_index[6])
93 {
94     int i, n;
95     memcpy(s->block_last_index, zigzag_last_index, sizeof(int)*6);
96
97     for(n=0; n<6; n++){
98         int16_t *ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
99
100         st[n]= s->intra_scantable.permutated;
101         if(dir[n]){
102             /* top prediction */
103             for(i=1; i<8; i++){
104                 block[n][s->dsp.idct_permutation[i   ]] = ac_val[i+8];
105             }
106         }else{
107             /* left prediction */
108             for(i=1; i<8; i++){
109                 block[n][s->dsp.idct_permutation[i<<3]]= ac_val[i  ];
110             }
111         }
112     }
113 }
114
115 /**
116  * Returns the optimal value (0 or 1) for the ac_pred element for the given MB in mpeg4.
117  * This function will also update s->block_last_index and s->ac_val.
118  * @param[in,out] block MB coefficients, these will be updated if 1 is returned
119  * @param[in] dir ac prediction direction for each 8x8 block
120  * @param[out] st scantable for each 8x8 block
121  * @param[out] zigzag_last_index index refering to the last non zero coefficient in zigzag order
122  */
123 static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], const int dir[6], uint8_t *st[6], int zigzag_last_index[6])
124 {
125     int score= 0;
126     int i, n;
127     int8_t * const qscale_table= s->current_picture.qscale_table;
128
129     memcpy(zigzag_last_index, s->block_last_index, sizeof(int)*6);
130
131     for(n=0; n<6; n++){
132         int16_t *ac_val, *ac_val1;
133
134         score -= get_block_rate(s, block[n], s->block_last_index[n], s->intra_scantable.permutated);
135
136         ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
137         ac_val1= ac_val;
138         if(dir[n]){
139             const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
140             /* top prediction */
141             ac_val-= s->block_wrap[n]*16;
142             if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
143                 /* same qscale */
144                 for(i=1; i<8; i++){
145                     const int level= block[n][s->dsp.idct_permutation[i   ]];
146                     block[n][s->dsp.idct_permutation[i   ]] = level - ac_val[i+8];
147                     ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
148                     ac_val1[i+8]= level;
149                 }
150             }else{
151                 /* different qscale, we must rescale */
152                 for(i=1; i<8; i++){
153                     const int level= block[n][s->dsp.idct_permutation[i   ]];
154                     block[n][s->dsp.idct_permutation[i   ]] = level - ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
155                     ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
156                     ac_val1[i+8]= level;
157                 }
158             }
159             st[n]= s->intra_h_scantable.permutated;
160         }else{
161             const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
162             /* left prediction */
163             ac_val-= 16;
164             if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
165                 /* same qscale */
166                 for(i=1; i<8; i++){
167                     const int level= block[n][s->dsp.idct_permutation[i<<3]];
168                     block[n][s->dsp.idct_permutation[i<<3]]= level - ac_val[i];
169                     ac_val1[i  ]= level;
170                     ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
171                 }
172             }else{
173                 /* different qscale, we must rescale */
174                 for(i=1; i<8; i++){
175                     const int level= block[n][s->dsp.idct_permutation[i<<3]];
176                     block[n][s->dsp.idct_permutation[i<<3]]= level - ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
177                     ac_val1[i  ]= level;
178                     ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
179                 }
180             }
181             st[n]= s->intra_v_scantable.permutated;
182         }
183
184         for(i=63; i>0; i--) //FIXME optimize
185             if(block[n][ st[n][i] ]) break;
186         s->block_last_index[n]= i;
187
188         score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
189     }
190
191     if(score < 0){
192         return 1;
193     }else{
194         restore_ac_coeffs(s, block, dir, st, zigzag_last_index);
195         return 0;
196     }
197 }
198
199 /**
200  * modify mb_type & qscale so that encoding is acually possible in mpeg4
201  */
202 void ff_clean_mpeg4_qscales(MpegEncContext *s){
203     int i;
204     int8_t * const qscale_table= s->current_picture.qscale_table;
205
206     ff_clean_h263_qscales(s);
207
208     if(s->pict_type== FF_B_TYPE){
209         int odd=0;
210         /* ok, come on, this isn't funny anymore, there's more code for handling this mpeg4 mess than for the actual adaptive quantization */
211
212         for(i=0; i<s->mb_num; i++){
213             int mb_xy= s->mb_index2xy[i];
214             odd += qscale_table[mb_xy]&1;
215         }
216
217         if(2*odd > s->mb_num) odd=1;
218         else                  odd=0;
219
220         for(i=0; i<s->mb_num; i++){
221             int mb_xy= s->mb_index2xy[i];
222             if((qscale_table[mb_xy]&1) != odd)
223                 qscale_table[mb_xy]++;
224             if(qscale_table[mb_xy] > 31)
225                 qscale_table[mb_xy]= 31;
226         }
227
228         for(i=1; i<s->mb_num; i++){
229             int mb_xy= s->mb_index2xy[i];
230             if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_DIRECT)){
231                 s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_BIDIR;
232             }
233         }
234     }
235 }
236
237
238 /**
239  * encodes the dc value.
240  * @param n block index (0-3 are luma, 4-5 are chroma)
241  */
242 static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
243 {
244 #if 1
245     level+=256;
246     if (n < 4) {
247         /* luminance */
248         put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
249     } else {
250         /* chrominance */
251         put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
252     }
253 #else
254     int size, v;
255     /* find number of bits */
256     size = 0;
257     v = abs(level);
258     while (v) {
259         v >>= 1;
260         size++;
261     }
262
263     if (n < 4) {
264         /* luminance */
265         put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
266     } else {
267         /* chrominance */
268         put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
269     }
270
271     /* encode remaining bits */
272     if (size > 0) {
273         if (level < 0)
274             level = (-level) ^ ((1 << size) - 1);
275         put_bits(&s->pb, size, level);
276         if (size > 8)
277             put_bits(&s->pb, 1, 1);
278     }
279 #endif
280 }
281
282 static inline int mpeg4_get_dc_length(int level, int n){
283     if (n < 4) {
284         return uni_DCtab_lum_len[level + 256];
285     } else {
286         return uni_DCtab_chrom_len[level + 256];
287     }
288 }
289
290 /**
291  * encodes a 8x8 block
292  * @param n block index (0-3 are luma, 4-5 are chroma)
293  */
294 static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc,
295                                uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
296 {
297     int i, last_non_zero;
298 #if 0 //variables for the outcommented version
299     int code, sign, last;
300 #endif
301     const RLTable *rl;
302     uint32_t *bits_tab;
303     uint8_t *len_tab;
304     const int last_index = s->block_last_index[n];
305
306     if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
307         /* mpeg4 based DC predictor */
308         mpeg4_encode_dc(dc_pb, intra_dc, n);
309         if(last_index<1) return;
310         i = 1;
311         rl = &rl_intra;
312         bits_tab= uni_mpeg4_intra_rl_bits;
313         len_tab = uni_mpeg4_intra_rl_len;
314     } else {
315         if(last_index<0) return;
316         i = 0;
317         rl = &rl_inter;
318         bits_tab= uni_mpeg4_inter_rl_bits;
319         len_tab = uni_mpeg4_inter_rl_len;
320     }
321
322     /* AC coefs */
323     last_non_zero = i - 1;
324 #if 1
325     for (; i < last_index; i++) {
326         int level = block[ scan_table[i] ];
327         if (level) {
328             int run = i - last_non_zero - 1;
329             level+=64;
330             if((level&(~127)) == 0){
331                 const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
332                 put_bits(ac_pb, len_tab[index], bits_tab[index]);
333             }else{ //ESC3
334                 put_bits(ac_pb, 7+2+1+6+1+12+1, (3<<23)+(3<<21)+(0<<20)+(run<<14)+(1<<13)+(((level-64)&0xfff)<<1)+1);
335             }
336             last_non_zero = i;
337         }
338     }
339     /*if(i<=last_index)*/{
340         int level = block[ scan_table[i] ];
341         int run = i - last_non_zero - 1;
342         level+=64;
343         if((level&(~127)) == 0){
344             const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
345             put_bits(ac_pb, len_tab[index], bits_tab[index]);
346         }else{ //ESC3
347             put_bits(ac_pb, 7+2+1+6+1+12+1, (3<<23)+(3<<21)+(1<<20)+(run<<14)+(1<<13)+(((level-64)&0xfff)<<1)+1);
348         }
349     }
350 #else
351     for (; i <= last_index; i++) {
352         const int slevel = block[ scan_table[i] ];
353         if (slevel) {
354             int level;
355             int run = i - last_non_zero - 1;
356             last = (i == last_index);
357             sign = 0;
358             level = slevel;
359             if (level < 0) {
360                 sign = 1;
361                 level = -level;
362             }
363             code = get_rl_index(rl, last, run, level);
364             put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
365             if (code == rl->n) {
366                 int level1, run1;
367                 level1 = level - rl->max_level[last][run];
368                 if (level1 < 1)
369                     goto esc2;
370                 code = get_rl_index(rl, last, run, level1);
371                 if (code == rl->n) {
372                 esc2:
373                     put_bits(ac_pb, 1, 1);
374                     if (level > MAX_LEVEL)
375                         goto esc3;
376                     run1 = run - rl->max_run[last][level] - 1;
377                     if (run1 < 0)
378                         goto esc3;
379                     code = get_rl_index(rl, last, run1, level);
380                     if (code == rl->n) {
381                     esc3:
382                         /* third escape */
383                         put_bits(ac_pb, 1, 1);
384                         put_bits(ac_pb, 1, last);
385                         put_bits(ac_pb, 6, run);
386                         put_bits(ac_pb, 1, 1);
387                         put_sbits(ac_pb, 12, slevel);
388                         put_bits(ac_pb, 1, 1);
389                     } else {
390                         /* second escape */
391                         put_bits(ac_pb, 1, 0);
392                         put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
393                         put_bits(ac_pb, 1, sign);
394                     }
395                 } else {
396                     /* first escape */
397                     put_bits(ac_pb, 1, 0);
398                     put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
399                     put_bits(ac_pb, 1, sign);
400                 }
401             } else {
402                 put_bits(ac_pb, 1, sign);
403             }
404             last_non_zero = i;
405         }
406     }
407 #endif
408 }
409
410 static int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc,
411                                uint8_t *scan_table)
412 {
413     int i, last_non_zero;
414     uint8_t *len_tab;
415     const int last_index = s->block_last_index[n];
416     int len=0;
417
418     if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
419         /* mpeg4 based DC predictor */
420         len += mpeg4_get_dc_length(intra_dc, n);
421         if(last_index<1) return len;
422         i = 1;
423         len_tab = uni_mpeg4_intra_rl_len;
424     } else {
425         if(last_index<0) return 0;
426         i = 0;
427         len_tab = uni_mpeg4_inter_rl_len;
428     }
429
430     /* AC coefs */
431     last_non_zero = i - 1;
432     for (; i < last_index; i++) {
433         int level = block[ scan_table[i] ];
434         if (level) {
435             int run = i - last_non_zero - 1;
436             level+=64;
437             if((level&(~127)) == 0){
438                 const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
439                 len += len_tab[index];
440             }else{ //ESC3
441                 len += 7+2+1+6+1+12+1;
442             }
443             last_non_zero = i;
444         }
445     }
446     /*if(i<=last_index)*/{
447         int level = block[ scan_table[i] ];
448         int run = i - last_non_zero - 1;
449         level+=64;
450         if((level&(~127)) == 0){
451             const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
452             len += len_tab[index];
453         }else{ //ESC3
454             len += 7+2+1+6+1+12+1;
455         }
456     }
457
458     return len;
459 }
460
461 static inline void mpeg4_encode_blocks(MpegEncContext * s, DCTELEM block[6][64], int intra_dc[6],
462                                uint8_t **scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb){
463     int i;
464
465     if(scan_table){
466         if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
467             for (i = 0; i < 6; i++) {
468                 skip_put_bits(&s->pb, mpeg4_get_block_length(s, block[i], i, intra_dc[i], scan_table[i]));
469             }
470         }else{
471             /* encode each block */
472             for (i = 0; i < 6; i++) {
473                 mpeg4_encode_block(s, block[i], i, intra_dc[i], scan_table[i], dc_pb, ac_pb);
474             }
475         }
476     }else{
477         if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
478             for (i = 0; i < 6; i++) {
479                 skip_put_bits(&s->pb, mpeg4_get_block_length(s, block[i], i, 0, s->intra_scantable.permutated));
480             }
481         }else{
482             /* encode each block */
483             for (i = 0; i < 6; i++) {
484                 mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, dc_pb, ac_pb);
485             }
486         }
487     }
488 }
489
490 //FIXME this is duplicated to h263.c
491 static const int dquant_code[5]= {1,0,9,2,3};
492
493 void mpeg4_encode_mb(MpegEncContext * s,
494                     DCTELEM block[6][64],
495                     int motion_x, int motion_y)
496 {
497     int cbpc, cbpy, pred_x, pred_y;
498     PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
499     PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=FF_B_TYPE ? &s->tex_pb : &s->pb;
500     PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=FF_I_TYPE ? &s->pb2    : &s->pb;
501     const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
502
503     if (!s->mb_intra) {
504         int i, cbp;
505
506         if(s->pict_type==FF_B_TYPE){
507             static const int mb_type_table[8]= {-1, 3, 2, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
508             int mb_type=  mb_type_table[s->mv_dir];
509
510             if(s->mb_x==0){
511                 for(i=0; i<2; i++){
512                     s->last_mv[i][0][0]=
513                     s->last_mv[i][0][1]=
514                     s->last_mv[i][1][0]=
515                     s->last_mv[i][1][1]= 0;
516                 }
517             }
518
519             assert(s->dquant>=-2 && s->dquant<=2);
520             assert((s->dquant&1)==0);
521             assert(mb_type>=0);
522
523             /* nothing to do if this MB was skipped in the next P Frame */
524             if(s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]){ //FIXME avoid DCT & ...
525                 s->skip_count++;
526                 s->mv[0][0][0]=
527                 s->mv[0][0][1]=
528                 s->mv[1][0][0]=
529                 s->mv[1][0][1]= 0;
530                 s->mv_dir= MV_DIR_FORWARD; //doesn't matter
531                 s->qscale -= s->dquant;
532 //                s->mb_skipped=1;
533
534                 return;
535             }
536
537             cbp= get_b_cbp(s, block, motion_x, motion_y, mb_type);
538
539             if ((cbp | motion_x | motion_y | mb_type) ==0) {
540                 /* direct MB with MV={0,0} */
541                 assert(s->dquant==0);
542
543                 put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
544
545                 if(interleaved_stats){
546                     s->misc_bits++;
547                     s->last_bits++;
548                 }
549                 s->skip_count++;
550                 return;
551             }
552
553             put_bits(&s->pb, 1, 0);     /* mb coded modb1=0 */
554             put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
555             put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we don't need it :)
556             if(cbp) put_bits(&s->pb, 6, cbp);
557
558             if(cbp && mb_type){
559                 if(s->dquant)
560                     put_bits(&s->pb, 2, (s->dquant>>2)+3);
561                 else
562                     put_bits(&s->pb, 1, 0);
563             }else
564                 s->qscale -= s->dquant;
565
566             if(!s->progressive_sequence){
567                 if(cbp)
568                     put_bits(&s->pb, 1, s->interlaced_dct);
569                 if(mb_type) // not direct mode
570                     put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
571             }
572
573             if(interleaved_stats){
574                 s->misc_bits+= get_bits_diff(s);
575             }
576
577             if(mb_type == 0){
578                 assert(s->mv_dir & MV_DIRECT);
579                 ff_h263_encode_motion_vector(s, motion_x, motion_y, 1);
580                 s->b_count++;
581                 s->f_count++;
582             }else{
583                 assert(mb_type > 0 && mb_type < 4);
584                 if(s->mv_type != MV_TYPE_FIELD){
585                     if(s->mv_dir & MV_DIR_FORWARD){
586                         ff_h263_encode_motion_vector(s, s->mv[0][0][0] - s->last_mv[0][0][0],
587                                                         s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
588                         s->last_mv[0][0][0]= s->last_mv[0][1][0]= s->mv[0][0][0];
589                         s->last_mv[0][0][1]= s->last_mv[0][1][1]= s->mv[0][0][1];
590                         s->f_count++;
591                     }
592                     if(s->mv_dir & MV_DIR_BACKWARD){
593                         ff_h263_encode_motion_vector(s, s->mv[1][0][0] - s->last_mv[1][0][0],
594                                                         s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
595                         s->last_mv[1][0][0]= s->last_mv[1][1][0]= s->mv[1][0][0];
596                         s->last_mv[1][0][1]= s->last_mv[1][1][1]= s->mv[1][0][1];
597                         s->b_count++;
598                     }
599                 }else{
600                     if(s->mv_dir & MV_DIR_FORWARD){
601                         put_bits(&s->pb, 1, s->field_select[0][0]);
602                         put_bits(&s->pb, 1, s->field_select[0][1]);
603                     }
604                     if(s->mv_dir & MV_DIR_BACKWARD){
605                         put_bits(&s->pb, 1, s->field_select[1][0]);
606                         put_bits(&s->pb, 1, s->field_select[1][1]);
607                     }
608                     if(s->mv_dir & MV_DIR_FORWARD){
609                         for(i=0; i<2; i++){
610                             ff_h263_encode_motion_vector(s, s->mv[0][i][0] - s->last_mv[0][i][0]  ,
611                                                             s->mv[0][i][1] - s->last_mv[0][i][1]/2, s->f_code);
612                             s->last_mv[0][i][0]= s->mv[0][i][0];
613                             s->last_mv[0][i][1]= s->mv[0][i][1]*2;
614                         }
615                         s->f_count++;
616                     }
617                     if(s->mv_dir & MV_DIR_BACKWARD){
618                         for(i=0; i<2; i++){
619                             ff_h263_encode_motion_vector(s, s->mv[1][i][0] - s->last_mv[1][i][0]  ,
620                                                             s->mv[1][i][1] - s->last_mv[1][i][1]/2, s->b_code);
621                             s->last_mv[1][i][0]= s->mv[1][i][0];
622                             s->last_mv[1][i][1]= s->mv[1][i][1]*2;
623                         }
624                         s->b_count++;
625                     }
626                 }
627             }
628
629             if(interleaved_stats){
630                 s->mv_bits+= get_bits_diff(s);
631             }
632
633             mpeg4_encode_blocks(s, block, NULL, NULL, NULL, &s->pb);
634
635             if(interleaved_stats){
636                 s->p_tex_bits+= get_bits_diff(s);
637             }
638
639         }else{ /* s->pict_type==FF_B_TYPE */
640             cbp= get_p_cbp(s, block, motion_x, motion_y);
641
642             if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
643                 /* check if the B frames can skip it too, as we must skip it if we skip here
644                    why didn't they just compress the skip-mb bits instead of reusing them ?! */
645                 if(s->max_b_frames>0){
646                     int i;
647                     int x,y, offset;
648                     uint8_t *p_pic;
649
650                     x= s->mb_x*16;
651                     y= s->mb_y*16;
652                     if(x+16 > s->width)  x= s->width-16;
653                     if(y+16 > s->height) y= s->height-16;
654
655                     offset= x + y*s->linesize;
656                     p_pic= s->new_picture.data[0] + offset;
657
658                     s->mb_skipped=1;
659                     for(i=0; i<s->max_b_frames; i++){
660                         uint8_t *b_pic;
661                         int diff;
662                         Picture *pic= s->reordered_input_picture[i+1];
663
664                         if(pic==NULL || pic->pict_type!=FF_B_TYPE) break;
665
666                         b_pic= pic->data[0] + offset;
667                         if(pic->type != FF_BUFFER_TYPE_SHARED)
668                             b_pic+= INPLACE_OFFSET;
669                         diff= s->dsp.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
670                         if(diff>s->qscale*70){ //FIXME check that 70 is optimal
671                             s->mb_skipped=0;
672                             break;
673                         }
674                     }
675                 }else
676                     s->mb_skipped=1;
677
678                 if(s->mb_skipped==1){
679                     /* skip macroblock */
680                     put_bits(&s->pb, 1, 1);
681
682                     if(interleaved_stats){
683                         s->misc_bits++;
684                         s->last_bits++;
685                     }
686                     s->skip_count++;
687
688                     return;
689                 }
690             }
691
692             put_bits(&s->pb, 1, 0);     /* mb coded */
693             cbpc = cbp & 3;
694             cbpy = cbp >> 2;
695             cbpy ^= 0xf;
696             if(s->mv_type==MV_TYPE_16X16){
697                 if(s->dquant) cbpc+= 8;
698                 put_bits(&s->pb,
699                         inter_MCBPC_bits[cbpc],
700                         inter_MCBPC_code[cbpc]);
701
702                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
703                 if(s->dquant)
704                     put_bits(pb2, 2, dquant_code[s->dquant+2]);
705
706                 if(!s->progressive_sequence){
707                     if(cbp)
708                         put_bits(pb2, 1, s->interlaced_dct);
709                     put_bits(pb2, 1, 0);
710                 }
711
712                 if(interleaved_stats){
713                     s->misc_bits+= get_bits_diff(s);
714                 }
715
716                 /* motion vectors: 16x16 mode */
717                 h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
718
719                 ff_h263_encode_motion_vector(s, motion_x - pred_x,
720                                                 motion_y - pred_y, s->f_code);
721             }else if(s->mv_type==MV_TYPE_FIELD){
722                 if(s->dquant) cbpc+= 8;
723                 put_bits(&s->pb,
724                         inter_MCBPC_bits[cbpc],
725                         inter_MCBPC_code[cbpc]);
726
727                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
728                 if(s->dquant)
729                     put_bits(pb2, 2, dquant_code[s->dquant+2]);
730
731                 assert(!s->progressive_sequence);
732                 if(cbp)
733                     put_bits(pb2, 1, s->interlaced_dct);
734                 put_bits(pb2, 1, 1);
735
736                 if(interleaved_stats){
737                     s->misc_bits+= get_bits_diff(s);
738                 }
739
740                 /* motion vectors: 16x8 interlaced mode */
741                 h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
742                 pred_y /=2;
743
744                 put_bits(&s->pb, 1, s->field_select[0][0]);
745                 put_bits(&s->pb, 1, s->field_select[0][1]);
746
747                 ff_h263_encode_motion_vector(s, s->mv[0][0][0] - pred_x,
748                                                 s->mv[0][0][1] - pred_y, s->f_code);
749                 ff_h263_encode_motion_vector(s, s->mv[0][1][0] - pred_x,
750                                                 s->mv[0][1][1] - pred_y, s->f_code);
751             }else{
752                 assert(s->mv_type==MV_TYPE_8X8);
753                 put_bits(&s->pb,
754                         inter_MCBPC_bits[cbpc+16],
755                         inter_MCBPC_code[cbpc+16]);
756                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
757
758                 if(!s->progressive_sequence){
759                     if(cbp)
760                         put_bits(pb2, 1, s->interlaced_dct);
761                 }
762
763                 if(interleaved_stats){
764                     s->misc_bits+= get_bits_diff(s);
765                 }
766
767                 for(i=0; i<4; i++){
768                     /* motion vectors: 8x8 mode*/
769                     h263_pred_motion(s, i, 0, &pred_x, &pred_y);
770
771                     ff_h263_encode_motion_vector(s, s->current_picture.motion_val[0][ s->block_index[i] ][0] - pred_x,
772                                                     s->current_picture.motion_val[0][ s->block_index[i] ][1] - pred_y, s->f_code);
773                 }
774             }
775
776             if(interleaved_stats){
777                 s->mv_bits+= get_bits_diff(s);
778             }
779
780             mpeg4_encode_blocks(s, block, NULL, NULL, NULL, tex_pb);
781
782             if(interleaved_stats){
783                 s->p_tex_bits+= get_bits_diff(s);
784             }
785             s->f_count++;
786         }
787     } else {
788         int cbp;
789         int dc_diff[6];   //dc values with the dc prediction subtracted
790         int dir[6];  //prediction direction
791         int zigzag_last_index[6];
792         uint8_t *scan_table[6];
793         int i;
794
795         for(i=0; i<6; i++){
796             dc_diff[i]= ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
797         }
798
799         if(s->flags & CODEC_FLAG_AC_PRED){
800             s->ac_pred= decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
801         }else{
802             for(i=0; i<6; i++)
803                 scan_table[i]= s->intra_scantable.permutated;
804         }
805
806         /* compute cbp */
807         cbp = 0;
808         for (i = 0; i < 6; i++) {
809             if (s->block_last_index[i] >= 1)
810                 cbp |= 1 << (5 - i);
811         }
812
813         cbpc = cbp & 3;
814         if (s->pict_type == FF_I_TYPE) {
815             if(s->dquant) cbpc+=4;
816             put_bits(&s->pb,
817                 intra_MCBPC_bits[cbpc],
818                 intra_MCBPC_code[cbpc]);
819         } else {
820             if(s->dquant) cbpc+=8;
821             put_bits(&s->pb, 1, 0);     /* mb coded */
822             put_bits(&s->pb,
823                 inter_MCBPC_bits[cbpc + 4],
824                 inter_MCBPC_code[cbpc + 4]);
825         }
826         put_bits(pb2, 1, s->ac_pred);
827         cbpy = cbp >> 2;
828         put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
829         if(s->dquant)
830             put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
831
832         if(!s->progressive_sequence){
833             put_bits(dc_pb, 1, s->interlaced_dct);
834         }
835
836         if(interleaved_stats){
837             s->misc_bits+= get_bits_diff(s);
838         }
839
840         mpeg4_encode_blocks(s, block, dc_diff, scan_table, dc_pb, tex_pb);
841
842         if(interleaved_stats){
843             s->i_tex_bits+= get_bits_diff(s);
844         }
845         s->i_count++;
846
847         /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
848         if(s->ac_pred)
849             restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
850     }
851 }
852
853 /**
854  * add mpeg4 stuffing bits (01...1)
855  */
856 void ff_mpeg4_stuffing(PutBitContext * pbc)
857 {
858     int length;
859     put_bits(pbc, 1, 0);
860     length= (-put_bits_count(pbc))&7;
861     if(length) put_bits(pbc, length, (1<<length)-1);
862 }
863
864 /* must be called before writing the header */
865 void ff_set_mpeg4_time(MpegEncContext * s){
866     if(s->pict_type==FF_B_TYPE){
867         ff_mpeg4_init_direct_mv(s);
868     }else{
869         s->last_time_base= s->time_base;
870         s->time_base= s->time/s->avctx->time_base.den;
871     }
872 }
873
874 static void mpeg4_encode_gop_header(MpegEncContext * s){
875     int hours, minutes, seconds;
876     int64_t time;
877
878     put_bits(&s->pb, 16, 0);
879     put_bits(&s->pb, 16, GOP_STARTCODE);
880
881     time= s->current_picture_ptr->pts;
882     if(s->reordered_input_picture[1])
883         time= FFMIN(time, s->reordered_input_picture[1]->pts);
884     time= time*s->avctx->time_base.num;
885
886     seconds= time/s->avctx->time_base.den;
887     minutes= seconds/60; seconds %= 60;
888     hours= minutes/60; minutes %= 60;
889     hours%=24;
890
891     put_bits(&s->pb, 5, hours);
892     put_bits(&s->pb, 6, minutes);
893     put_bits(&s->pb, 1, 1);
894     put_bits(&s->pb, 6, seconds);
895
896     put_bits(&s->pb, 1, !!(s->flags&CODEC_FLAG_CLOSED_GOP));
897     put_bits(&s->pb, 1, 0); //broken link == NO
898
899     s->last_time_base= time / s->avctx->time_base.den;
900
901     ff_mpeg4_stuffing(&s->pb);
902 }
903
904 static void mpeg4_encode_visual_object_header(MpegEncContext * s){
905     int profile_and_level_indication;
906     int vo_ver_id;
907
908     if(s->avctx->profile != FF_PROFILE_UNKNOWN){
909         profile_and_level_indication = s->avctx->profile << 4;
910     }else if(s->max_b_frames || s->quarter_sample){
911         profile_and_level_indication= 0xF0; // adv simple
912     }else{
913         profile_and_level_indication= 0x00; // simple
914     }
915
916     if(s->avctx->level != FF_LEVEL_UNKNOWN){
917         profile_and_level_indication |= s->avctx->level;
918     }else{
919         profile_and_level_indication |= 1; //level 1
920     }
921
922     if(profile_and_level_indication>>4 == 0xF){
923         vo_ver_id= 5;
924     }else{
925         vo_ver_id= 1;
926     }
927
928     //FIXME levels
929
930     put_bits(&s->pb, 16, 0);
931     put_bits(&s->pb, 16, VOS_STARTCODE);
932
933     put_bits(&s->pb, 8, profile_and_level_indication);
934
935     put_bits(&s->pb, 16, 0);
936     put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
937
938     put_bits(&s->pb, 1, 1);
939         put_bits(&s->pb, 4, vo_ver_id);
940         put_bits(&s->pb, 3, 1); //priority
941
942     put_bits(&s->pb, 4, 1); //visual obj type== video obj
943
944     put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
945
946     ff_mpeg4_stuffing(&s->pb);
947 }
948
949 static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
950 {
951     int vo_ver_id;
952
953     if (!CONFIG_MPEG4_ENCODER)  return;
954
955     if(s->max_b_frames || s->quarter_sample){
956         vo_ver_id= 5;
957         s->vo_type= ADV_SIMPLE_VO_TYPE;
958     }else{
959         vo_ver_id= 1;
960         s->vo_type= SIMPLE_VO_TYPE;
961     }
962
963     put_bits(&s->pb, 16, 0);
964     put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
965     put_bits(&s->pb, 16, 0);
966     put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
967
968     put_bits(&s->pb, 1, 0);             /* random access vol */
969     put_bits(&s->pb, 8, s->vo_type);    /* video obj type indication */
970     if(s->workaround_bugs & FF_BUG_MS) {
971         put_bits(&s->pb, 1, 0);         /* is obj layer id= no */
972     } else {
973         put_bits(&s->pb, 1, 1);         /* is obj layer id= yes */
974         put_bits(&s->pb, 4, vo_ver_id); /* is obj layer ver id */
975         put_bits(&s->pb, 3, 1);         /* is obj layer priority */
976     }
977
978     s->aspect_ratio_info= ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio);
979
980     put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
981     if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
982         put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
983         put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
984     }
985
986     if(s->workaround_bugs & FF_BUG_MS) { //
987         put_bits(&s->pb, 1, 0);         /* vol control parameters= no @@@ */
988     } else {
989         put_bits(&s->pb, 1, 1);         /* vol control parameters= yes */
990         put_bits(&s->pb, 2, 1);         /* chroma format YUV 420/YV12 */
991         put_bits(&s->pb, 1, s->low_delay);
992         put_bits(&s->pb, 1, 0);         /* vbv parameters= no */
993     }
994
995     put_bits(&s->pb, 2, RECT_SHAPE);    /* vol shape= rectangle */
996     put_bits(&s->pb, 1, 1);             /* marker bit */
997
998     put_bits(&s->pb, 16, s->avctx->time_base.den);
999     if (s->time_increment_bits < 1)
1000         s->time_increment_bits = 1;
1001     put_bits(&s->pb, 1, 1);             /* marker bit */
1002     put_bits(&s->pb, 1, 0);             /* fixed vop rate=no */
1003     put_bits(&s->pb, 1, 1);             /* marker bit */
1004     put_bits(&s->pb, 13, s->width);     /* vol width */
1005     put_bits(&s->pb, 1, 1);             /* marker bit */
1006     put_bits(&s->pb, 13, s->height);    /* vol height */
1007     put_bits(&s->pb, 1, 1);             /* marker bit */
1008     put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1009     put_bits(&s->pb, 1, 1);             /* obmc disable */
1010     if (vo_ver_id == 1) {
1011         put_bits(&s->pb, 1, s->vol_sprite_usage);       /* sprite enable */
1012     }else{
1013         put_bits(&s->pb, 2, s->vol_sprite_usage);       /* sprite enable */
1014     }
1015
1016     put_bits(&s->pb, 1, 0);             /* not 8 bit == false */
1017     put_bits(&s->pb, 1, s->mpeg_quant); /* quant type= (0=h263 style)*/
1018
1019     if(s->mpeg_quant){
1020         ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
1021         ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
1022     }
1023
1024     if (vo_ver_id != 1)
1025         put_bits(&s->pb, 1, s->quarter_sample);
1026     put_bits(&s->pb, 1, 1);             /* complexity estimation disable */
1027     s->resync_marker= s->rtp_mode;
1028     put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
1029     put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1030     if(s->data_partitioning){
1031         put_bits(&s->pb, 1, 0);         /* no rvlc */
1032     }
1033
1034     if (vo_ver_id != 1){
1035         put_bits(&s->pb, 1, 0);         /* newpred */
1036         put_bits(&s->pb, 1, 0);         /* reduced res vop */
1037     }
1038     put_bits(&s->pb, 1, 0);             /* scalability */
1039
1040     ff_mpeg4_stuffing(&s->pb);
1041
1042     /* user data */
1043     if(!(s->flags & CODEC_FLAG_BITEXACT)){
1044         put_bits(&s->pb, 16, 0);
1045         put_bits(&s->pb, 16, 0x1B2);    /* user_data */
1046         ff_put_string(&s->pb, LIBAVCODEC_IDENT, 0);
1047     }
1048 }
1049
1050 /* write mpeg4 VOP header */
1051 void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
1052 {
1053     int time_incr;
1054     int time_div, time_mod;
1055
1056     if(s->pict_type==FF_I_TYPE){
1057         if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
1058             if(s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT) //HACK, the reference sw is buggy
1059                 mpeg4_encode_visual_object_header(s);
1060             if(s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number==0) //HACK, the reference sw is buggy
1061                 mpeg4_encode_vol_header(s, 0, 0);
1062         }
1063         if(!(s->workaround_bugs & FF_BUG_MS))
1064             mpeg4_encode_gop_header(s);
1065     }
1066
1067     s->partitioned_frame= s->data_partitioning && s->pict_type!=FF_B_TYPE;
1068
1069     put_bits(&s->pb, 16, 0);                /* vop header */
1070     put_bits(&s->pb, 16, VOP_STARTCODE);    /* vop header */
1071     put_bits(&s->pb, 2, s->pict_type - 1);  /* pict type: I = 0 , P = 1 */
1072
1073     assert(s->time>=0);
1074     time_div= s->time/s->avctx->time_base.den;
1075     time_mod= s->time%s->avctx->time_base.den;
1076     time_incr= time_div - s->last_time_base;
1077     assert(time_incr >= 0);
1078     while(time_incr--)
1079         put_bits(&s->pb, 1, 1);
1080
1081     put_bits(&s->pb, 1, 0);
1082
1083     put_bits(&s->pb, 1, 1);                             /* marker */
1084     put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
1085     put_bits(&s->pb, 1, 1);                             /* marker */
1086     put_bits(&s->pb, 1, 1);                             /* vop coded */
1087     if (    s->pict_type == FF_P_TYPE
1088         || (s->pict_type == FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
1089         put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */
1090     }
1091     put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */
1092     if(!s->progressive_sequence){
1093          put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
1094          put_bits(&s->pb, 1, s->alternate_scan);
1095     }
1096     //FIXME sprite stuff
1097
1098     put_bits(&s->pb, 5, s->qscale);
1099
1100     if (s->pict_type != FF_I_TYPE)
1101         put_bits(&s->pb, 3, s->f_code); /* fcode_for */
1102     if (s->pict_type == FF_B_TYPE)
1103         put_bits(&s->pb, 3, s->b_code); /* fcode_back */
1104 }
1105
1106
1107 static void init_uni_dc_tab(void)
1108 {
1109     int level, uni_code, uni_len;
1110
1111     for(level=-256; level<256; level++){
1112         int size, v, l;
1113         /* find number of bits */
1114         size = 0;
1115         v = abs(level);
1116         while (v) {
1117             v >>= 1;
1118             size++;
1119         }
1120
1121         if (level < 0)
1122             l= (-level) ^ ((1 << size) - 1);
1123         else
1124             l= level;
1125
1126         /* luminance */
1127         uni_code= DCtab_lum[size][0];
1128         uni_len = DCtab_lum[size][1];
1129
1130         if (size > 0) {
1131             uni_code<<=size; uni_code|=l;
1132             uni_len+=size;
1133             if (size > 8){
1134                 uni_code<<=1; uni_code|=1;
1135                 uni_len++;
1136             }
1137         }
1138         uni_DCtab_lum_bits[level+256]= uni_code;
1139         uni_DCtab_lum_len [level+256]= uni_len;
1140
1141         /* chrominance */
1142         uni_code= DCtab_chrom[size][0];
1143         uni_len = DCtab_chrom[size][1];
1144
1145         if (size > 0) {
1146             uni_code<<=size; uni_code|=l;
1147             uni_len+=size;
1148             if (size > 8){
1149                 uni_code<<=1; uni_code|=1;
1150                 uni_len++;
1151             }
1152         }
1153         uni_DCtab_chrom_bits[level+256]= uni_code;
1154         uni_DCtab_chrom_len [level+256]= uni_len;
1155
1156     }
1157 }
1158
1159 static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1160     int slevel, run, last;
1161
1162     assert(MAX_LEVEL >= 64);
1163     assert(MAX_RUN   >= 63);
1164
1165     for(slevel=-64; slevel<64; slevel++){
1166         if(slevel==0) continue;
1167         for(run=0; run<64; run++){
1168             for(last=0; last<=1; last++){
1169                 const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1170                 int level= slevel < 0 ? -slevel : slevel;
1171                 int sign= slevel < 0 ? 1 : 0;
1172                 int bits, len, code;
1173                 int level1, run1;
1174
1175                 len_tab[index]= 100;
1176
1177                 /* ESC0 */
1178                 code= get_rl_index(rl, last, run, level);
1179                 bits= rl->table_vlc[code][0];
1180                 len=  rl->table_vlc[code][1];
1181                 bits=bits*2+sign; len++;
1182
1183                 if(code!=rl->n && len < len_tab[index]){
1184                     bits_tab[index]= bits;
1185                     len_tab [index]= len;
1186                 }
1187                 /* ESC1 */
1188                 bits= rl->table_vlc[rl->n][0];
1189                 len=  rl->table_vlc[rl->n][1];
1190                 bits=bits*2;    len++; //esc1
1191                 level1= level - rl->max_level[last][run];
1192                 if(level1>0){
1193                     code= get_rl_index(rl, last, run, level1);
1194                     bits<<= rl->table_vlc[code][1];
1195                     len  += rl->table_vlc[code][1];
1196                     bits += rl->table_vlc[code][0];
1197                     bits=bits*2+sign; len++;
1198
1199                     if(code!=rl->n && len < len_tab[index]){
1200                         bits_tab[index]= bits;
1201                         len_tab [index]= len;
1202                     }
1203                 }
1204                 /* ESC2 */
1205                 bits= rl->table_vlc[rl->n][0];
1206                 len=  rl->table_vlc[rl->n][1];
1207                 bits=bits*4+2;    len+=2; //esc2
1208                 run1 = run - rl->max_run[last][level] - 1;
1209                 if(run1>=0){
1210                     code= get_rl_index(rl, last, run1, level);
1211                     bits<<= rl->table_vlc[code][1];
1212                     len  += rl->table_vlc[code][1];
1213                     bits += rl->table_vlc[code][0];
1214                     bits=bits*2+sign; len++;
1215
1216                     if(code!=rl->n && len < len_tab[index]){
1217                         bits_tab[index]= bits;
1218                         len_tab [index]= len;
1219                     }
1220                 }
1221                 /* ESC3 */
1222                 bits= rl->table_vlc[rl->n][0];
1223                 len = rl->table_vlc[rl->n][1];
1224                 bits=bits*4+3;    len+=2; //esc3
1225                 bits=bits*2+last; len++;
1226                 bits=bits*64+run; len+=6;
1227                 bits=bits*2+1;    len++;  //marker
1228                 bits=bits*4096+(slevel&0xfff); len+=12;
1229                 bits=bits*2+1;    len++;  //marker
1230
1231                 if(len < len_tab[index]){
1232                     bits_tab[index]= bits;
1233                     len_tab [index]= len;
1234                 }
1235             }
1236         }
1237     }
1238 }
1239
1240 static av_cold int encode_init(AVCodecContext *avctx)
1241 {
1242     MpegEncContext *s = avctx->priv_data;
1243     int ret;
1244     static int done = 0;
1245
1246     if((ret=MPV_encode_init(avctx)) < 0)
1247         return ret;
1248
1249     if (!done) {
1250         done = 1;
1251
1252         init_uni_dc_tab();
1253
1254         init_rl(&rl_intra, ff_mpeg4_static_rl_table_store[0]);
1255
1256         init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1257         init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1258     }
1259
1260     s->min_qcoeff= -2048;
1261     s->max_qcoeff=  2047;
1262     s->intra_ac_vlc_length     = uni_mpeg4_intra_rl_len;
1263     s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;
1264     s->inter_ac_vlc_length     = uni_mpeg4_inter_rl_len;
1265     s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;
1266     s->luma_dc_vlc_length= uni_DCtab_lum_len;
1267     s->chroma_dc_vlc_length= uni_DCtab_chrom_len;
1268     s->ac_esc_length= 7+2+1+6+1+12+1;
1269     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table;
1270     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
1271
1272     if(s->flags & CODEC_FLAG_GLOBAL_HEADER){
1273
1274         s->avctx->extradata= av_malloc(1024);
1275         init_put_bits(&s->pb, s->avctx->extradata, 1024);
1276
1277         if(!(s->workaround_bugs & FF_BUG_MS))
1278             mpeg4_encode_visual_object_header(s);
1279         mpeg4_encode_vol_header(s, 0, 0);
1280
1281 //            ff_mpeg4_stuffing(&s->pb); ?
1282         flush_put_bits(&s->pb);
1283         s->avctx->extradata_size= (put_bits_count(&s->pb)+7)>>3;
1284     }
1285     return 0;
1286 }
1287
1288 void ff_mpeg4_init_partitions(MpegEncContext *s)
1289 {
1290     uint8_t *start= put_bits_ptr(&s->pb);
1291     uint8_t *end= s->pb.buf_end;
1292     int size= end - start;
1293     int pb_size = (((intptr_t)start + size/3)&(~3)) - (intptr_t)start;
1294     int tex_size= (size - 2*pb_size)&(~3);
1295
1296     set_put_bits_buffer_size(&s->pb, pb_size);
1297     init_put_bits(&s->tex_pb, start + pb_size           , tex_size);
1298     init_put_bits(&s->pb2   , start + pb_size + tex_size, pb_size);
1299 }
1300
1301 void ff_mpeg4_merge_partitions(MpegEncContext *s)
1302 {
1303     const int pb2_len   = put_bits_count(&s->pb2   );
1304     const int tex_pb_len= put_bits_count(&s->tex_pb);
1305     const int bits= put_bits_count(&s->pb);
1306
1307     if(s->pict_type==FF_I_TYPE){
1308         put_bits(&s->pb, 19, DC_MARKER);
1309         s->misc_bits+=19 + pb2_len + bits - s->last_bits;
1310         s->i_tex_bits+= tex_pb_len;
1311     }else{
1312         put_bits(&s->pb, 17, MOTION_MARKER);
1313         s->misc_bits+=17 + pb2_len;
1314         s->mv_bits+= bits - s->last_bits;
1315         s->p_tex_bits+= tex_pb_len;
1316     }
1317
1318     flush_put_bits(&s->pb2);
1319     flush_put_bits(&s->tex_pb);
1320
1321     set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
1322     ff_copy_bits(&s->pb, s->pb2.buf   , pb2_len);
1323     ff_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
1324     s->last_bits= put_bits_count(&s->pb);
1325 }
1326
1327
1328 void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
1329 {
1330     int mb_num_bits= av_log2(s->mb_num - 1) + 1;
1331
1332     put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
1333     put_bits(&s->pb, 1, 1);
1334
1335     put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
1336     put_bits(&s->pb, s->quant_precision, s->qscale);
1337     put_bits(&s->pb, 1, 0); /* no HEC */
1338 }
1339
1340 AVCodec mpeg4_encoder = {
1341     "mpeg4",
1342     CODEC_TYPE_VIDEO,
1343     CODEC_ID_MPEG4,
1344     sizeof(MpegEncContext),
1345     encode_init,
1346     MPV_encode_picture,
1347     MPV_encode_end,
1348     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
1349     .capabilities= CODEC_CAP_DELAY,
1350     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
1351 };