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