Merge remote branch 'qatar/master'
[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  * Return 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  * Restore 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  * Return 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== AV_PICTURE_TYPE_B){
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     /* DC will overflow if level is outside the [-255,255] range. */
246     level+=256;
247     if (n < 4) {
248         /* luminance */
249         put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
250     } else {
251         /* chrominance */
252         put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
253     }
254 #else
255     int size, v;
256     /* find number of bits */
257     size = 0;
258     v = abs(level);
259     while (v) {
260         v >>= 1;
261         size++;
262     }
263
264     if (n < 4) {
265         /* luminance */
266         put_bits(&s->pb, ff_mpeg4_DCtab_lum[size][1], ff_mpeg4_DCtab_lum[size][0]);
267     } else {
268         /* chrominance */
269         put_bits(&s->pb, ff_mpeg4_DCtab_chrom[size][1], ff_mpeg4_DCtab_chrom[size][0]);
270     }
271
272     /* encode remaining bits */
273     if (size > 0) {
274         if (level < 0)
275             level = (-level) ^ ((1 << size) - 1);
276         put_bits(&s->pb, size, level);
277         if (size > 8)
278             put_bits(&s->pb, 1, 1);
279     }
280 #endif
281 }
282
283 static inline int mpeg4_get_dc_length(int level, int n){
284     if (n < 4) {
285         return uni_DCtab_lum_len[level + 256];
286     } else {
287         return uni_DCtab_chrom_len[level + 256];
288     }
289 }
290
291 /**
292  * encodes a 8x8 block
293  * @param n block index (0-3 are luma, 4-5 are chroma)
294  */
295 static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc,
296                                uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
297 {
298     int i, last_non_zero;
299 #if 0 //variables for the outcommented version
300     int code, sign, last;
301 #endif
302     const RLTable *rl;
303     uint32_t *bits_tab;
304     uint8_t *len_tab;
305     const int last_index = s->block_last_index[n];
306
307     if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
308         /* mpeg4 based DC predictor */
309         mpeg4_encode_dc(dc_pb, intra_dc, n);
310         if(last_index<1) return;
311         i = 1;
312         rl = &ff_mpeg4_rl_intra;
313         bits_tab= uni_mpeg4_intra_rl_bits;
314         len_tab = uni_mpeg4_intra_rl_len;
315     } else {
316         if(last_index<0) return;
317         i = 0;
318         rl = &ff_h263_rl_inter;
319         bits_tab= uni_mpeg4_inter_rl_bits;
320         len_tab = uni_mpeg4_inter_rl_len;
321     }
322
323     /* AC coefs */
324     last_non_zero = i - 1;
325 #if 1
326     for (; i < last_index; i++) {
327         int level = block[ scan_table[i] ];
328         if (level) {
329             int run = i - last_non_zero - 1;
330             level+=64;
331             if((level&(~127)) == 0){
332                 const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
333                 put_bits(ac_pb, len_tab[index], bits_tab[index]);
334             }else{ //ESC3
335                 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);
336             }
337             last_non_zero = i;
338         }
339     }
340     /*if(i<=last_index)*/{
341         int level = block[ scan_table[i] ];
342         int run = i - last_non_zero - 1;
343         level+=64;
344         if((level&(~127)) == 0){
345             const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
346             put_bits(ac_pb, len_tab[index], bits_tab[index]);
347         }else{ //ESC3
348             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);
349         }
350     }
351 #else
352     for (; i <= last_index; i++) {
353         const int slevel = block[ scan_table[i] ];
354         if (slevel) {
355             int level;
356             int run = i - last_non_zero - 1;
357             last = (i == last_index);
358             sign = 0;
359             level = slevel;
360             if (level < 0) {
361                 sign = 1;
362                 level = -level;
363             }
364             code = get_rl_index(rl, last, run, level);
365             put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
366             if (code == rl->n) {
367                 int level1, run1;
368                 level1 = level - rl->max_level[last][run];
369                 if (level1 < 1)
370                     goto esc2;
371                 code = get_rl_index(rl, last, run, level1);
372                 if (code == rl->n) {
373                 esc2:
374                     put_bits(ac_pb, 1, 1);
375                     if (level > MAX_LEVEL)
376                         goto esc3;
377                     run1 = run - rl->max_run[last][level] - 1;
378                     if (run1 < 0)
379                         goto esc3;
380                     code = get_rl_index(rl, last, run1, level);
381                     if (code == rl->n) {
382                     esc3:
383                         /* third escape */
384                         put_bits(ac_pb, 1, 1);
385                         put_bits(ac_pb, 1, last);
386                         put_bits(ac_pb, 6, run);
387                         put_bits(ac_pb, 1, 1);
388                         put_sbits(ac_pb, 12, slevel);
389                         put_bits(ac_pb, 1, 1);
390                     } else {
391                         /* second escape */
392                         put_bits(ac_pb, 1, 0);
393                         put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
394                         put_bits(ac_pb, 1, sign);
395                     }
396                 } else {
397                     /* first escape */
398                     put_bits(ac_pb, 1, 0);
399                     put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
400                     put_bits(ac_pb, 1, sign);
401                 }
402             } else {
403                 put_bits(ac_pb, 1, sign);
404             }
405             last_non_zero = i;
406         }
407     }
408 #endif
409 }
410
411 static int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc,
412                                uint8_t *scan_table)
413 {
414     int i, last_non_zero;
415     uint8_t *len_tab;
416     const int last_index = s->block_last_index[n];
417     int len=0;
418
419     if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
420         /* mpeg4 based DC predictor */
421         len += mpeg4_get_dc_length(intra_dc, n);
422         if(last_index<1) return len;
423         i = 1;
424         len_tab = uni_mpeg4_intra_rl_len;
425     } else {
426         if(last_index<0) return 0;
427         i = 0;
428         len_tab = uni_mpeg4_inter_rl_len;
429     }
430
431     /* AC coefs */
432     last_non_zero = i - 1;
433     for (; i < last_index; i++) {
434         int level = block[ scan_table[i] ];
435         if (level) {
436             int run = i - last_non_zero - 1;
437             level+=64;
438             if((level&(~127)) == 0){
439                 const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
440                 len += len_tab[index];
441             }else{ //ESC3
442                 len += 7+2+1+6+1+12+1;
443             }
444             last_non_zero = i;
445         }
446     }
447     /*if(i<=last_index)*/{
448         int level = block[ scan_table[i] ];
449         int run = i - last_non_zero - 1;
450         level+=64;
451         if((level&(~127)) == 0){
452             const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
453             len += len_tab[index];
454         }else{ //ESC3
455             len += 7+2+1+6+1+12+1;
456         }
457     }
458
459     return len;
460 }
461
462 static inline void mpeg4_encode_blocks(MpegEncContext * s, DCTELEM block[6][64], int intra_dc[6],
463                                uint8_t **scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb){
464     int i;
465
466     if(scan_table){
467         if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
468             for (i = 0; i < 6; i++) {
469                 skip_put_bits(&s->pb, mpeg4_get_block_length(s, block[i], i, intra_dc[i], scan_table[i]));
470             }
471         }else{
472             /* encode each block */
473             for (i = 0; i < 6; i++) {
474                 mpeg4_encode_block(s, block[i], i, intra_dc[i], scan_table[i], dc_pb, ac_pb);
475             }
476         }
477     }else{
478         if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
479             for (i = 0; i < 6; i++) {
480                 skip_put_bits(&s->pb, mpeg4_get_block_length(s, block[i], i, 0, s->intra_scantable.permutated));
481             }
482         }else{
483             /* encode each block */
484             for (i = 0; i < 6; i++) {
485                 mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, dc_pb, ac_pb);
486             }
487         }
488     }
489 }
490
491 //FIXME this is duplicated to h263.c
492 static const int dquant_code[5]= {1,0,9,2,3};
493
494 void mpeg4_encode_mb(MpegEncContext * s,
495                     DCTELEM block[6][64],
496                     int motion_x, int motion_y)
497 {
498     int cbpc, cbpy, pred_x, pred_y;
499     PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
500     PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=AV_PICTURE_TYPE_B ? &s->tex_pb : &s->pb;
501     PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=AV_PICTURE_TYPE_I ? &s->pb2    : &s->pb;
502     const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
503
504     if (!s->mb_intra) {
505         int i, cbp;
506
507         if(s->pict_type==AV_PICTURE_TYPE_B){
508             static const int mb_type_table[8]= {-1, 3, 2, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
509             int mb_type=  mb_type_table[s->mv_dir];
510
511             if(s->mb_x==0){
512                 for(i=0; i<2; i++){
513                     s->last_mv[i][0][0]=
514                     s->last_mv[i][0][1]=
515                     s->last_mv[i][1][0]=
516                     s->last_mv[i][1][1]= 0;
517                 }
518             }
519
520             assert(s->dquant>=-2 && s->dquant<=2);
521             assert((s->dquant&1)==0);
522             assert(mb_type>=0);
523
524             /* nothing to do if this MB was skipped in the next P Frame */
525             if(s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]){ //FIXME avoid DCT & ...
526                 s->skip_count++;
527                 s->mv[0][0][0]=
528                 s->mv[0][0][1]=
529                 s->mv[1][0][0]=
530                 s->mv[1][0][1]= 0;
531                 s->mv_dir= MV_DIR_FORWARD; //doesn't matter
532                 s->qscale -= s->dquant;
533 //                s->mb_skipped=1;
534
535                 return;
536             }
537
538             cbp= get_b_cbp(s, block, motion_x, motion_y, mb_type);
539
540             if ((cbp | motion_x | motion_y | mb_type) ==0) {
541                 /* direct MB with MV={0,0} */
542                 assert(s->dquant==0);
543
544                 put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
545
546                 if(interleaved_stats){
547                     s->misc_bits++;
548                     s->last_bits++;
549                 }
550                 s->skip_count++;
551                 return;
552             }
553
554             put_bits(&s->pb, 1, 0);     /* mb coded modb1=0 */
555             put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
556             put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we don't need it :)
557             if(cbp) put_bits(&s->pb, 6, cbp);
558
559             if(cbp && mb_type){
560                 if(s->dquant)
561                     put_bits(&s->pb, 2, (s->dquant>>2)+3);
562                 else
563                     put_bits(&s->pb, 1, 0);
564             }else
565                 s->qscale -= s->dquant;
566
567             if(!s->progressive_sequence){
568                 if(cbp)
569                     put_bits(&s->pb, 1, s->interlaced_dct);
570                 if(mb_type) // not direct mode
571                     put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
572             }
573
574             if(interleaved_stats){
575                 s->misc_bits+= get_bits_diff(s);
576             }
577
578             if(mb_type == 0){
579                 assert(s->mv_dir & MV_DIRECT);
580                 ff_h263_encode_motion_vector(s, motion_x, motion_y, 1);
581                 s->b_count++;
582                 s->f_count++;
583             }else{
584                 assert(mb_type > 0 && mb_type < 4);
585                 if(s->mv_type != MV_TYPE_FIELD){
586                     if(s->mv_dir & MV_DIR_FORWARD){
587                         ff_h263_encode_motion_vector(s, s->mv[0][0][0] - s->last_mv[0][0][0],
588                                                         s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
589                         s->last_mv[0][0][0]= s->last_mv[0][1][0]= s->mv[0][0][0];
590                         s->last_mv[0][0][1]= s->last_mv[0][1][1]= s->mv[0][0][1];
591                         s->f_count++;
592                     }
593                     if(s->mv_dir & MV_DIR_BACKWARD){
594                         ff_h263_encode_motion_vector(s, s->mv[1][0][0] - s->last_mv[1][0][0],
595                                                         s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
596                         s->last_mv[1][0][0]= s->last_mv[1][1][0]= s->mv[1][0][0];
597                         s->last_mv[1][0][1]= s->last_mv[1][1][1]= s->mv[1][0][1];
598                         s->b_count++;
599                     }
600                 }else{
601                     if(s->mv_dir & MV_DIR_FORWARD){
602                         put_bits(&s->pb, 1, s->field_select[0][0]);
603                         put_bits(&s->pb, 1, s->field_select[0][1]);
604                     }
605                     if(s->mv_dir & MV_DIR_BACKWARD){
606                         put_bits(&s->pb, 1, s->field_select[1][0]);
607                         put_bits(&s->pb, 1, s->field_select[1][1]);
608                     }
609                     if(s->mv_dir & MV_DIR_FORWARD){
610                         for(i=0; i<2; i++){
611                             ff_h263_encode_motion_vector(s, s->mv[0][i][0] - s->last_mv[0][i][0]  ,
612                                                             s->mv[0][i][1] - s->last_mv[0][i][1]/2, s->f_code);
613                             s->last_mv[0][i][0]= s->mv[0][i][0];
614                             s->last_mv[0][i][1]= s->mv[0][i][1]*2;
615                         }
616                         s->f_count++;
617                     }
618                     if(s->mv_dir & MV_DIR_BACKWARD){
619                         for(i=0; i<2; i++){
620                             ff_h263_encode_motion_vector(s, s->mv[1][i][0] - s->last_mv[1][i][0]  ,
621                                                             s->mv[1][i][1] - s->last_mv[1][i][1]/2, s->b_code);
622                             s->last_mv[1][i][0]= s->mv[1][i][0];
623                             s->last_mv[1][i][1]= s->mv[1][i][1]*2;
624                         }
625                         s->b_count++;
626                     }
627                 }
628             }
629
630             if(interleaved_stats){
631                 s->mv_bits+= get_bits_diff(s);
632             }
633
634             mpeg4_encode_blocks(s, block, NULL, NULL, NULL, &s->pb);
635
636             if(interleaved_stats){
637                 s->p_tex_bits+= get_bits_diff(s);
638             }
639
640         }else{ /* s->pict_type==AV_PICTURE_TYPE_B */
641             cbp= get_p_cbp(s, block, motion_x, motion_y);
642
643             if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
644                 /* check if the B frames can skip it too, as we must skip it if we skip here
645                    why didn't they just compress the skip-mb bits instead of reusing them ?! */
646                 if(s->max_b_frames>0){
647                     int i;
648                     int x,y, offset;
649                     uint8_t *p_pic;
650
651                     x= s->mb_x*16;
652                     y= s->mb_y*16;
653
654                     offset= x + y*s->linesize;
655                     p_pic= s->new_picture.data[0] + offset;
656
657                     s->mb_skipped=1;
658                     for(i=0; i<s->max_b_frames; i++){
659                         uint8_t *b_pic;
660                         int diff;
661                         Picture *pic= s->reordered_input_picture[i+1];
662
663                         if(pic==NULL || pic->pict_type!=AV_PICTURE_TYPE_B) break;
664
665                         b_pic= pic->data[0] + offset;
666                         if(pic->type != FF_BUFFER_TYPE_SHARED)
667                             b_pic+= INPLACE_OFFSET;
668
669                         if(x+16 > s->width || y+16 > s->height){
670                             int x1,y1;
671                             int xe= FFMIN(16, s->width - x);
672                             int ye= FFMIN(16, s->height- y);
673                             diff=0;
674                             for(y1=0; y1<ye; y1++){
675                                 for(x1=0; x1<xe; x1++){
676                                     diff+= FFABS(p_pic[x1+y1*s->linesize] - b_pic[x1+y1*s->linesize]);
677                                 }
678                             }
679                             diff= diff*256/(xe*ye);
680                         }else{
681                             diff= s->dsp.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
682                         }
683                         if(diff>s->qscale*70){ //FIXME check that 70 is optimal
684                             s->mb_skipped=0;
685                             break;
686                         }
687                     }
688                 }else
689                     s->mb_skipped=1;
690
691                 if(s->mb_skipped==1){
692                     /* skip macroblock */
693                     put_bits(&s->pb, 1, 1);
694
695                     if(interleaved_stats){
696                         s->misc_bits++;
697                         s->last_bits++;
698                     }
699                     s->skip_count++;
700
701                     return;
702                 }
703             }
704
705             put_bits(&s->pb, 1, 0);     /* mb coded */
706             cbpc = cbp & 3;
707             cbpy = cbp >> 2;
708             cbpy ^= 0xf;
709             if(s->mv_type==MV_TYPE_16X16){
710                 if(s->dquant) cbpc+= 8;
711                 put_bits(&s->pb,
712                         ff_h263_inter_MCBPC_bits[cbpc],
713                         ff_h263_inter_MCBPC_code[cbpc]);
714
715                 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
716                 if(s->dquant)
717                     put_bits(pb2, 2, dquant_code[s->dquant+2]);
718
719                 if(!s->progressive_sequence){
720                     if(cbp)
721                         put_bits(pb2, 1, s->interlaced_dct);
722                     put_bits(pb2, 1, 0);
723                 }
724
725                 if(interleaved_stats){
726                     s->misc_bits+= get_bits_diff(s);
727                 }
728
729                 /* motion vectors: 16x16 mode */
730                 h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
731
732                 ff_h263_encode_motion_vector(s, motion_x - pred_x,
733                                                 motion_y - pred_y, s->f_code);
734             }else if(s->mv_type==MV_TYPE_FIELD){
735                 if(s->dquant) cbpc+= 8;
736                 put_bits(&s->pb,
737                         ff_h263_inter_MCBPC_bits[cbpc],
738                         ff_h263_inter_MCBPC_code[cbpc]);
739
740                 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
741                 if(s->dquant)
742                     put_bits(pb2, 2, dquant_code[s->dquant+2]);
743
744                 assert(!s->progressive_sequence);
745                 if(cbp)
746                     put_bits(pb2, 1, s->interlaced_dct);
747                 put_bits(pb2, 1, 1);
748
749                 if(interleaved_stats){
750                     s->misc_bits+= get_bits_diff(s);
751                 }
752
753                 /* motion vectors: 16x8 interlaced mode */
754                 h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
755                 pred_y /=2;
756
757                 put_bits(&s->pb, 1, s->field_select[0][0]);
758                 put_bits(&s->pb, 1, s->field_select[0][1]);
759
760                 ff_h263_encode_motion_vector(s, s->mv[0][0][0] - pred_x,
761                                                 s->mv[0][0][1] - pred_y, s->f_code);
762                 ff_h263_encode_motion_vector(s, s->mv[0][1][0] - pred_x,
763                                                 s->mv[0][1][1] - pred_y, s->f_code);
764             }else{
765                 assert(s->mv_type==MV_TYPE_8X8);
766                 put_bits(&s->pb,
767                         ff_h263_inter_MCBPC_bits[cbpc+16],
768                         ff_h263_inter_MCBPC_code[cbpc+16]);
769                 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
770
771                 if(!s->progressive_sequence){
772                     if(cbp)
773                         put_bits(pb2, 1, s->interlaced_dct);
774                 }
775
776                 if(interleaved_stats){
777                     s->misc_bits+= get_bits_diff(s);
778                 }
779
780                 for(i=0; i<4; i++){
781                     /* motion vectors: 8x8 mode*/
782                     h263_pred_motion(s, i, 0, &pred_x, &pred_y);
783
784                     ff_h263_encode_motion_vector(s, s->current_picture.motion_val[0][ s->block_index[i] ][0] - pred_x,
785                                                     s->current_picture.motion_val[0][ s->block_index[i] ][1] - pred_y, s->f_code);
786                 }
787             }
788
789             if(interleaved_stats){
790                 s->mv_bits+= get_bits_diff(s);
791             }
792
793             mpeg4_encode_blocks(s, block, NULL, NULL, NULL, tex_pb);
794
795             if(interleaved_stats){
796                 s->p_tex_bits+= get_bits_diff(s);
797             }
798             s->f_count++;
799         }
800     } else {
801         int cbp;
802         int dc_diff[6];   //dc values with the dc prediction subtracted
803         int dir[6];  //prediction direction
804         int zigzag_last_index[6];
805         uint8_t *scan_table[6];
806         int i;
807
808         for(i=0; i<6; i++){
809             dc_diff[i]= ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
810         }
811
812         if(s->flags & CODEC_FLAG_AC_PRED){
813             s->ac_pred= decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
814         }else{
815             for(i=0; i<6; i++)
816                 scan_table[i]= s->intra_scantable.permutated;
817         }
818
819         /* compute cbp */
820         cbp = 0;
821         for (i = 0; i < 6; i++) {
822             if (s->block_last_index[i] >= 1)
823                 cbp |= 1 << (5 - i);
824         }
825
826         cbpc = cbp & 3;
827         if (s->pict_type == AV_PICTURE_TYPE_I) {
828             if(s->dquant) cbpc+=4;
829             put_bits(&s->pb,
830                 ff_h263_intra_MCBPC_bits[cbpc],
831                 ff_h263_intra_MCBPC_code[cbpc]);
832         } else {
833             if(s->dquant) cbpc+=8;
834             put_bits(&s->pb, 1, 0);     /* mb coded */
835             put_bits(&s->pb,
836                 ff_h263_inter_MCBPC_bits[cbpc + 4],
837                 ff_h263_inter_MCBPC_code[cbpc + 4]);
838         }
839         put_bits(pb2, 1, s->ac_pred);
840         cbpy = cbp >> 2;
841         put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
842         if(s->dquant)
843             put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
844
845         if(!s->progressive_sequence){
846             put_bits(dc_pb, 1, s->interlaced_dct);
847         }
848
849         if(interleaved_stats){
850             s->misc_bits+= get_bits_diff(s);
851         }
852
853         mpeg4_encode_blocks(s, block, dc_diff, scan_table, dc_pb, tex_pb);
854
855         if(interleaved_stats){
856             s->i_tex_bits+= get_bits_diff(s);
857         }
858         s->i_count++;
859
860         /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
861         if(s->ac_pred)
862             restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
863     }
864 }
865
866 /**
867  * add mpeg4 stuffing bits (01...1)
868  */
869 void ff_mpeg4_stuffing(PutBitContext * pbc)
870 {
871     int length;
872     put_bits(pbc, 1, 0);
873     length= (-put_bits_count(pbc))&7;
874     if(length) put_bits(pbc, length, (1<<length)-1);
875 }
876
877 /* must be called before writing the header */
878 void ff_set_mpeg4_time(MpegEncContext * s){
879     if(s->pict_type==AV_PICTURE_TYPE_B){
880         ff_mpeg4_init_direct_mv(s);
881     }else{
882         s->last_time_base= s->time_base;
883         s->time_base= FFUDIV(s->time, s->avctx->time_base.den);
884     }
885 }
886
887 static void mpeg4_encode_gop_header(MpegEncContext * s){
888     int hours, minutes, seconds;
889     int64_t time;
890
891     put_bits(&s->pb, 16, 0);
892     put_bits(&s->pb, 16, GOP_STARTCODE);
893
894     time= s->current_picture_ptr->pts;
895     if(s->reordered_input_picture[1])
896         time= FFMIN(time, s->reordered_input_picture[1]->pts);
897     time= time*s->avctx->time_base.num;
898     s->last_time_base= FFUDIV(time, s->avctx->time_base.den);
899
900     seconds= FFUDIV(time, s->avctx->time_base.den);
901     minutes= FFUDIV(seconds, 60); FFUMOD(seconds, 60);
902     hours  = FFUDIV(minutes, 60); FFUMOD(minutes, 60);
903     hours  = FFUMOD(hours  , 24);
904
905     put_bits(&s->pb, 5, hours);
906     put_bits(&s->pb, 6, minutes);
907     put_bits(&s->pb, 1, 1);
908     put_bits(&s->pb, 6, seconds);
909
910     put_bits(&s->pb, 1, !!(s->flags&CODEC_FLAG_CLOSED_GOP));
911     put_bits(&s->pb, 1, 0); //broken link == NO
912
913     ff_mpeg4_stuffing(&s->pb);
914 }
915
916 static void mpeg4_encode_visual_object_header(MpegEncContext * s){
917     int profile_and_level_indication;
918     int vo_ver_id;
919
920     if(s->avctx->profile != FF_PROFILE_UNKNOWN){
921         profile_and_level_indication = s->avctx->profile << 4;
922     }else if(s->max_b_frames || s->quarter_sample){
923         profile_and_level_indication= 0xF0; // adv simple
924     }else{
925         profile_and_level_indication= 0x00; // simple
926     }
927
928     if(s->avctx->level != FF_LEVEL_UNKNOWN){
929         profile_and_level_indication |= s->avctx->level;
930     }else{
931         profile_and_level_indication |= 1; //level 1
932     }
933
934     if(profile_and_level_indication>>4 == 0xF){
935         vo_ver_id= 5;
936     }else{
937         vo_ver_id= 1;
938     }
939
940     //FIXME levels
941
942     put_bits(&s->pb, 16, 0);
943     put_bits(&s->pb, 16, VOS_STARTCODE);
944
945     put_bits(&s->pb, 8, profile_and_level_indication);
946
947     put_bits(&s->pb, 16, 0);
948     put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
949
950     put_bits(&s->pb, 1, 1);
951         put_bits(&s->pb, 4, vo_ver_id);
952         put_bits(&s->pb, 3, 1); //priority
953
954     put_bits(&s->pb, 4, 1); //visual obj type== video obj
955
956     put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
957
958     ff_mpeg4_stuffing(&s->pb);
959 }
960
961 static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
962 {
963     int vo_ver_id;
964
965     if (!CONFIG_MPEG4_ENCODER)  return;
966
967     if(s->max_b_frames || s->quarter_sample){
968         vo_ver_id= 5;
969         s->vo_type= ADV_SIMPLE_VO_TYPE;
970     }else{
971         vo_ver_id= 1;
972         s->vo_type= SIMPLE_VO_TYPE;
973     }
974
975     put_bits(&s->pb, 16, 0);
976     put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
977     put_bits(&s->pb, 16, 0);
978     put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
979
980     put_bits(&s->pb, 1, 0);             /* random access vol */
981     put_bits(&s->pb, 8, s->vo_type);    /* video obj type indication */
982     if(s->workaround_bugs & FF_BUG_MS) {
983         put_bits(&s->pb, 1, 0);         /* is obj layer id= no */
984     } else {
985         put_bits(&s->pb, 1, 1);         /* is obj layer id= yes */
986         put_bits(&s->pb, 4, vo_ver_id); /* is obj layer ver id */
987         put_bits(&s->pb, 3, 1);         /* is obj layer priority */
988     }
989
990     s->aspect_ratio_info= ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio);
991
992     put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
993     if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
994         put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
995         put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
996     }
997
998     if(s->workaround_bugs & FF_BUG_MS) { //
999         put_bits(&s->pb, 1, 0);         /* vol control parameters= no @@@ */
1000     } else {
1001         put_bits(&s->pb, 1, 1);         /* vol control parameters= yes */
1002         put_bits(&s->pb, 2, 1);         /* chroma format YUV 420/YV12 */
1003         put_bits(&s->pb, 1, s->low_delay);
1004         put_bits(&s->pb, 1, 0);         /* vbv parameters= no */
1005     }
1006
1007     put_bits(&s->pb, 2, RECT_SHAPE);    /* vol shape= rectangle */
1008     put_bits(&s->pb, 1, 1);             /* marker bit */
1009
1010     put_bits(&s->pb, 16, s->avctx->time_base.den);
1011     if (s->time_increment_bits < 1)
1012         s->time_increment_bits = 1;
1013     put_bits(&s->pb, 1, 1);             /* marker bit */
1014     put_bits(&s->pb, 1, 0);             /* fixed vop rate=no */
1015     put_bits(&s->pb, 1, 1);             /* marker bit */
1016     put_bits(&s->pb, 13, s->width);     /* vol width */
1017     put_bits(&s->pb, 1, 1);             /* marker bit */
1018     put_bits(&s->pb, 13, s->height);    /* vol height */
1019     put_bits(&s->pb, 1, 1);             /* marker bit */
1020     put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1021     put_bits(&s->pb, 1, 1);             /* obmc disable */
1022     if (vo_ver_id == 1) {
1023         put_bits(&s->pb, 1, s->vol_sprite_usage);       /* sprite enable */
1024     }else{
1025         put_bits(&s->pb, 2, s->vol_sprite_usage);       /* sprite enable */
1026     }
1027
1028     put_bits(&s->pb, 1, 0);             /* not 8 bit == false */
1029     put_bits(&s->pb, 1, s->mpeg_quant); /* quant type= (0=h263 style)*/
1030
1031     if(s->mpeg_quant){
1032         ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
1033         ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
1034     }
1035
1036     if (vo_ver_id != 1)
1037         put_bits(&s->pb, 1, s->quarter_sample);
1038     put_bits(&s->pb, 1, 1);             /* complexity estimation disable */
1039     s->resync_marker= s->rtp_mode;
1040     put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
1041     put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1042     if(s->data_partitioning){
1043         put_bits(&s->pb, 1, 0);         /* no rvlc */
1044     }
1045
1046     if (vo_ver_id != 1){
1047         put_bits(&s->pb, 1, 0);         /* newpred */
1048         put_bits(&s->pb, 1, 0);         /* reduced res vop */
1049     }
1050     put_bits(&s->pb, 1, 0);             /* scalability */
1051
1052     ff_mpeg4_stuffing(&s->pb);
1053
1054     /* user data */
1055     if(!(s->flags & CODEC_FLAG_BITEXACT)){
1056         put_bits(&s->pb, 16, 0);
1057         put_bits(&s->pb, 16, 0x1B2);    /* user_data */
1058         ff_put_string(&s->pb, LIBAVCODEC_IDENT, 0);
1059     }
1060 }
1061
1062 /* write mpeg4 VOP header */
1063 void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
1064 {
1065     int time_incr;
1066     int time_div, time_mod;
1067
1068     if(s->pict_type==AV_PICTURE_TYPE_I){
1069         if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
1070             if(s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT) //HACK, the reference sw is buggy
1071                 mpeg4_encode_visual_object_header(s);
1072             if(s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number==0) //HACK, the reference sw is buggy
1073                 mpeg4_encode_vol_header(s, 0, 0);
1074         }
1075         if(!(s->workaround_bugs & FF_BUG_MS))
1076             mpeg4_encode_gop_header(s);
1077     }
1078
1079     s->partitioned_frame= s->data_partitioning && s->pict_type!=AV_PICTURE_TYPE_B;
1080
1081     put_bits(&s->pb, 16, 0);                /* vop header */
1082     put_bits(&s->pb, 16, VOP_STARTCODE);    /* vop header */
1083     put_bits(&s->pb, 2, s->pict_type - 1);  /* pict type: I = 0 , P = 1 */
1084
1085     time_div= FFUDIV(s->time, s->avctx->time_base.den);
1086     time_mod= FFUMOD(s->time, s->avctx->time_base.den);
1087     time_incr= time_div - s->last_time_base;
1088     assert(time_incr >= 0);
1089     while(time_incr--)
1090         put_bits(&s->pb, 1, 1);
1091
1092     put_bits(&s->pb, 1, 0);
1093
1094     put_bits(&s->pb, 1, 1);                             /* marker */
1095     put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
1096     put_bits(&s->pb, 1, 1);                             /* marker */
1097     put_bits(&s->pb, 1, 1);                             /* vop coded */
1098     if (    s->pict_type == AV_PICTURE_TYPE_P
1099         || (s->pict_type == AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE)) {
1100         put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */
1101     }
1102     put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */
1103     if(!s->progressive_sequence){
1104          put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
1105          put_bits(&s->pb, 1, s->alternate_scan);
1106     }
1107     //FIXME sprite stuff
1108
1109     put_bits(&s->pb, 5, s->qscale);
1110
1111     if (s->pict_type != AV_PICTURE_TYPE_I)
1112         put_bits(&s->pb, 3, s->f_code); /* fcode_for */
1113     if (s->pict_type == AV_PICTURE_TYPE_B)
1114         put_bits(&s->pb, 3, s->b_code); /* fcode_back */
1115 }
1116
1117
1118 static void init_uni_dc_tab(void)
1119 {
1120     int level, uni_code, uni_len;
1121
1122     for(level=-256; level<256; level++){
1123         int size, v, l;
1124         /* find number of bits */
1125         size = 0;
1126         v = abs(level);
1127         while (v) {
1128             v >>= 1;
1129             size++;
1130         }
1131
1132         if (level < 0)
1133             l= (-level) ^ ((1 << size) - 1);
1134         else
1135             l= level;
1136
1137         /* luminance */
1138         uni_code= ff_mpeg4_DCtab_lum[size][0];
1139         uni_len = ff_mpeg4_DCtab_lum[size][1];
1140
1141         if (size > 0) {
1142             uni_code<<=size; uni_code|=l;
1143             uni_len+=size;
1144             if (size > 8){
1145                 uni_code<<=1; uni_code|=1;
1146                 uni_len++;
1147             }
1148         }
1149         uni_DCtab_lum_bits[level+256]= uni_code;
1150         uni_DCtab_lum_len [level+256]= uni_len;
1151
1152         /* chrominance */
1153         uni_code= ff_mpeg4_DCtab_chrom[size][0];
1154         uni_len = ff_mpeg4_DCtab_chrom[size][1];
1155
1156         if (size > 0) {
1157             uni_code<<=size; uni_code|=l;
1158             uni_len+=size;
1159             if (size > 8){
1160                 uni_code<<=1; uni_code|=1;
1161                 uni_len++;
1162             }
1163         }
1164         uni_DCtab_chrom_bits[level+256]= uni_code;
1165         uni_DCtab_chrom_len [level+256]= uni_len;
1166
1167     }
1168 }
1169
1170 static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1171     int slevel, run, last;
1172
1173     assert(MAX_LEVEL >= 64);
1174     assert(MAX_RUN   >= 63);
1175
1176     for(slevel=-64; slevel<64; slevel++){
1177         if(slevel==0) continue;
1178         for(run=0; run<64; run++){
1179             for(last=0; last<=1; last++){
1180                 const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1181                 int level= slevel < 0 ? -slevel : slevel;
1182                 int sign= slevel < 0 ? 1 : 0;
1183                 int bits, len, code;
1184                 int level1, run1;
1185
1186                 len_tab[index]= 100;
1187
1188                 /* ESC0 */
1189                 code= get_rl_index(rl, last, run, level);
1190                 bits= rl->table_vlc[code][0];
1191                 len=  rl->table_vlc[code][1];
1192                 bits=bits*2+sign; len++;
1193
1194                 if(code!=rl->n && len < len_tab[index]){
1195                     bits_tab[index]= bits;
1196                     len_tab [index]= len;
1197                 }
1198                 /* ESC1 */
1199                 bits= rl->table_vlc[rl->n][0];
1200                 len=  rl->table_vlc[rl->n][1];
1201                 bits=bits*2;    len++; //esc1
1202                 level1= level - rl->max_level[last][run];
1203                 if(level1>0){
1204                     code= get_rl_index(rl, last, run, level1);
1205                     bits<<= rl->table_vlc[code][1];
1206                     len  += rl->table_vlc[code][1];
1207                     bits += rl->table_vlc[code][0];
1208                     bits=bits*2+sign; len++;
1209
1210                     if(code!=rl->n && len < len_tab[index]){
1211                         bits_tab[index]= bits;
1212                         len_tab [index]= len;
1213                     }
1214                 }
1215                 /* ESC2 */
1216                 bits= rl->table_vlc[rl->n][0];
1217                 len=  rl->table_vlc[rl->n][1];
1218                 bits=bits*4+2;    len+=2; //esc2
1219                 run1 = run - rl->max_run[last][level] - 1;
1220                 if(run1>=0){
1221                     code= get_rl_index(rl, last, run1, level);
1222                     bits<<= rl->table_vlc[code][1];
1223                     len  += rl->table_vlc[code][1];
1224                     bits += rl->table_vlc[code][0];
1225                     bits=bits*2+sign; len++;
1226
1227                     if(code!=rl->n && len < len_tab[index]){
1228                         bits_tab[index]= bits;
1229                         len_tab [index]= len;
1230                     }
1231                 }
1232                 /* ESC3 */
1233                 bits= rl->table_vlc[rl->n][0];
1234                 len = rl->table_vlc[rl->n][1];
1235                 bits=bits*4+3;    len+=2; //esc3
1236                 bits=bits*2+last; len++;
1237                 bits=bits*64+run; len+=6;
1238                 bits=bits*2+1;    len++;  //marker
1239                 bits=bits*4096+(slevel&0xfff); len+=12;
1240                 bits=bits*2+1;    len++;  //marker
1241
1242                 if(len < len_tab[index]){
1243                     bits_tab[index]= bits;
1244                     len_tab [index]= len;
1245                 }
1246             }
1247         }
1248     }
1249 }
1250
1251 static av_cold int encode_init(AVCodecContext *avctx)
1252 {
1253     MpegEncContext *s = avctx->priv_data;
1254     int ret;
1255     static int done = 0;
1256
1257     if((ret=MPV_encode_init(avctx)) < 0)
1258         return ret;
1259
1260     if (!done) {
1261         done = 1;
1262
1263         init_uni_dc_tab();
1264
1265         init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
1266
1267         init_uni_mpeg4_rl_tab(&ff_mpeg4_rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1268         init_uni_mpeg4_rl_tab(&ff_h263_rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1269     }
1270
1271     s->min_qcoeff= -2048;
1272     s->max_qcoeff=  2047;
1273     s->intra_ac_vlc_length     = uni_mpeg4_intra_rl_len;
1274     s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;
1275     s->inter_ac_vlc_length     = uni_mpeg4_inter_rl_len;
1276     s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;
1277     s->luma_dc_vlc_length= uni_DCtab_lum_len;
1278     s->chroma_dc_vlc_length= uni_DCtab_chrom_len;
1279     s->ac_esc_length= 7+2+1+6+1+12+1;
1280     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table;
1281     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
1282
1283     if(s->flags & CODEC_FLAG_GLOBAL_HEADER){
1284
1285         s->avctx->extradata= av_malloc(1024);
1286         init_put_bits(&s->pb, s->avctx->extradata, 1024);
1287
1288         if(!(s->workaround_bugs & FF_BUG_MS))
1289             mpeg4_encode_visual_object_header(s);
1290         mpeg4_encode_vol_header(s, 0, 0);
1291
1292 //            ff_mpeg4_stuffing(&s->pb); ?
1293         flush_put_bits(&s->pb);
1294         s->avctx->extradata_size= (put_bits_count(&s->pb)+7)>>3;
1295     }
1296     return 0;
1297 }
1298
1299 void ff_mpeg4_init_partitions(MpegEncContext *s)
1300 {
1301     uint8_t *start= put_bits_ptr(&s->pb);
1302     uint8_t *end= s->pb.buf_end;
1303     int size= end - start;
1304     int pb_size = (((intptr_t)start + size/3)&(~3)) - (intptr_t)start;
1305     int tex_size= (size - 2*pb_size)&(~3);
1306
1307     set_put_bits_buffer_size(&s->pb, pb_size);
1308     init_put_bits(&s->tex_pb, start + pb_size           , tex_size);
1309     init_put_bits(&s->pb2   , start + pb_size + tex_size, pb_size);
1310 }
1311
1312 void ff_mpeg4_merge_partitions(MpegEncContext *s)
1313 {
1314     const int pb2_len   = put_bits_count(&s->pb2   );
1315     const int tex_pb_len= put_bits_count(&s->tex_pb);
1316     const int bits= put_bits_count(&s->pb);
1317
1318     if(s->pict_type==AV_PICTURE_TYPE_I){
1319         put_bits(&s->pb, 19, DC_MARKER);
1320         s->misc_bits+=19 + pb2_len + bits - s->last_bits;
1321         s->i_tex_bits+= tex_pb_len;
1322     }else{
1323         put_bits(&s->pb, 17, MOTION_MARKER);
1324         s->misc_bits+=17 + pb2_len;
1325         s->mv_bits+= bits - s->last_bits;
1326         s->p_tex_bits+= tex_pb_len;
1327     }
1328
1329     flush_put_bits(&s->pb2);
1330     flush_put_bits(&s->tex_pb);
1331
1332     set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
1333     ff_copy_bits(&s->pb, s->pb2.buf   , pb2_len);
1334     ff_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
1335     s->last_bits= put_bits_count(&s->pb);
1336 }
1337
1338
1339 void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
1340 {
1341     int mb_num_bits= av_log2(s->mb_num - 1) + 1;
1342
1343     put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
1344     put_bits(&s->pb, 1, 1);
1345
1346     put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
1347     put_bits(&s->pb, s->quant_precision, s->qscale);
1348     put_bits(&s->pb, 1, 0); /* no HEC */
1349 }
1350
1351 AVCodec ff_mpeg4_encoder = {
1352     "mpeg4",
1353     AVMEDIA_TYPE_VIDEO,
1354     CODEC_ID_MPEG4,
1355     sizeof(MpegEncContext),
1356     encode_init,
1357     MPV_encode_picture,
1358     MPV_encode_end,
1359     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
1360     .capabilities= CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
1361     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
1362 };