5d03ba611e766d4f519a73cfff4530fd2e9b5499
[libav.git] / libavcodec / h263.c
1 /*
2 * H263/MPEG4 backend for ffmpeg encoder and decoder
3 * Copyright (c) 2000,2001 Fabrice Bellard.
4 * H263+ support.
5 * Copyright (c) 2001 Juan J. Sierralta P.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 *
21 * ac prediction encoding, b-frame support, error resilience, optimizations,
22 * qpel decoding, gmc decoding, interlaced decoding,
23 * by Michael Niedermayer <michaelni@gmx.at>
24 */
25
26 /**
27 * @file h263.c
28 * h263/mpeg4 codec.
29 */
30
31 //#define DEBUG
32 #include <limits.h>
33
34 #include "common.h"
35 #include "dsputil.h"
36 #include "avcodec.h"
37 #include "mpegvideo.h"
38 #include "h263data.h"
39 #include "mpeg4data.h"
40
41 //#undef NDEBUG
42 //#include <assert.h>
43
44 #define INTRA_MCBPC_VLC_BITS 6
45 #define INTER_MCBPC_VLC_BITS 7
46 #define CBPY_VLC_BITS 6
47 #define MV_VLC_BITS 9
48 #define DC_VLC_BITS 9
49 #define SPRITE_TRAJ_VLC_BITS 6
50 #define MB_TYPE_B_VLC_BITS 4
51 #define TEX_VLC_BITS 9
52
53 #ifdef CONFIG_ENCODERS
54 static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
55 int n);
56 static void h263_encode_motion(MpegEncContext * s, int val, int fcode);
57 static void h263p_encode_umotion(MpegEncContext * s, int val);
58 static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
59 int n, int dc, uint8_t *scan_table,
60 PutBitContext *dc_pb, PutBitContext *ac_pb);
61 #endif
62
63 static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
64 static int h263p_decode_umotion(MpegEncContext * s, int pred);
65 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
66 int n, int coded);
67 static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr);
68 static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
69 int n, int coded, int intra, int rvlc);
70 static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr);
71 #ifdef CONFIG_ENCODERS
72 static void mpeg4_encode_visual_object_header(MpegEncContext * s);
73 static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number);
74 #endif //CONFIG_ENCODERS
75 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s);
76 static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr);
77
78 #ifdef CONFIG_ENCODERS
79 static uint8_t uni_DCtab_lum_len[512];
80 static uint8_t uni_DCtab_chrom_len[512];
81 static uint16_t uni_DCtab_lum_bits[512];
82 static uint16_t uni_DCtab_chrom_bits[512];
83
84 static uint8_t (*mv_penalty)[MAX_MV*2+1]= NULL;
85 static uint8_t fcode_tab[MAX_MV*2+1];
86 static uint8_t umv_fcode_tab[MAX_MV*2+1];
87
88 static uint32_t uni_mpeg4_intra_rl_bits[64*64*2*2];
89 static uint8_t uni_mpeg4_intra_rl_len [64*64*2*2];
90 static uint32_t uni_mpeg4_inter_rl_bits[64*64*2*2];
91 static uint8_t uni_mpeg4_inter_rl_len [64*64*2*2];
92 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
93 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
94 #define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
95
96 /* mpeg4
97 inter
98 max level: 24/6
99 max run: 53/63
100
101 intra
102 max level: 53/16
103 max run: 29/41
104 */
105 #endif
106
107 #if 0 //3IV1 is quite rare and tis slows things down a tiny bit
108 #define IS_3IV1 s->avctx->codec_tag == ff_get_fourcc("3IV1")
109 #else
110 #define IS_3IV1 0
111 #endif
112
113 int h263_get_picture_format(int width, int height)
114 {
115 int format;
116
117 if (width == 128 && height == 96)
118 format = 1;
119 else if (width == 176 && height == 144)
120 format = 2;
121 else if (width == 352 && height == 288)
122 format = 3;
123 else if (width == 704 && height == 576)
124 format = 4;
125 else if (width == 1408 && height == 1152)
126 format = 5;
127 else
128 format = 7;
129 return format;
130 }
131
132 #ifdef CONFIG_ENCODERS
133
134 static void float_aspect_to_info(MpegEncContext * s, float aspect){
135 int i;
136
137 aspect*= s->height/(double)s->width;
138 //printf("%f\n", aspect);
139
140 if(aspect==0) aspect= 1.0;
141
142 ff_float2fraction(&s->aspected_width, &s->aspected_height, aspect, 255);
143
144 //printf("%d %d\n", s->aspected_width, s->aspected_height);
145 for(i=1; i<6; i++){
146 if(s->aspected_width == pixel_aspect[i][0] && s->aspected_height== pixel_aspect[i][1]){
147 s->aspect_ratio_info=i;
148 return;
149 }
150 }
151
152 s->aspect_ratio_info= FF_ASPECT_EXTENDED;
153 }
154
155 void ff_flv_encode_picture_header(MpegEncContext * s, int picture_number)
156 {
157 int format;
158
159 align_put_bits(&s->pb);
160
161 put_bits(&s->pb, 17, 1);
162 put_bits(&s->pb, 5, (s->h263_flv-1)); /* 0: h263 escape codes 1: 11-bit escape codes */
163 put_bits(&s->pb, 8, (((int64_t)s->picture_number * 30 * s->avctx->frame_rate_base) /
164 s->avctx->frame_rate) & 0xff); /* TemporalReference */
165 if (s->width == 352 && s->height == 288)
166 format = 2;
167 else if (s->width == 176 && s->height == 144)
168 format = 3;
169 else if (s->width == 128 && s->height == 96)
170 format = 4;
171 else if (s->width == 320 && s->height == 240)
172 format = 5;
173 else if (s->width == 160 && s->height == 120)
174 format = 6;
175 else if (s->width <= 255 && s->height <= 255)
176 format = 0; /* use 1 byte width & height */
177 else
178 format = 1; /* use 2 bytes width & height */
179 put_bits(&s->pb, 3, format); /* PictureSize */
180 if (format == 0) {
181 put_bits(&s->pb, 8, s->width);
182 put_bits(&s->pb, 8, s->height);
183 } else if (format == 1) {
184 put_bits(&s->pb, 16, s->width);
185 put_bits(&s->pb, 16, s->height);
186 }
187 put_bits(&s->pb, 2, s->pict_type == P_TYPE); /* PictureType */
188 put_bits(&s->pb, 1, 1); /* DeblockingFlag: on */
189 put_bits(&s->pb, 5, s->qscale); /* Quantizer */
190 put_bits(&s->pb, 1, 0); /* ExtraInformation */
191
192 if(s->h263_aic){
193 s->y_dc_scale_table=
194 s->c_dc_scale_table= h263_aic_dc_scale_table;
195 }else{
196 s->y_dc_scale_table=
197 s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
198 }
199 }
200
201 void h263_encode_picture_header(MpegEncContext * s, int picture_number)
202 {
203 int format;
204
205 align_put_bits(&s->pb);
206
207 /* Update the pointer to last GOB */
208 s->ptr_lastgob = pbBufPtr(&s->pb);
209 s->gob_number = 0;
210
211 put_bits(&s->pb, 22, 0x20); /* PSC */
212 put_bits(&s->pb, 8, (((int64_t)s->picture_number * 30 * s->avctx->frame_rate_base) /
213 s->avctx->frame_rate) & 0xff);
214
215 put_bits(&s->pb, 1, 1); /* marker */
216 put_bits(&s->pb, 1, 0); /* h263 id */
217 put_bits(&s->pb, 1, 0); /* split screen off */
218 put_bits(&s->pb, 1, 0); /* camera off */
219 put_bits(&s->pb, 1, 0); /* freeze picture release off */
220
221 format = h263_get_picture_format(s->width, s->height);
222 if (!s->h263_plus) {
223 /* H.263v1 */
224 put_bits(&s->pb, 3, format);
225 put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
226 /* By now UMV IS DISABLED ON H.263v1, since the restrictions
227 of H.263v1 UMV implies to check the predicted MV after
228 calculation of the current MB to see if we're on the limits */
229 put_bits(&s->pb, 1, 0); /* unrestricted motion vector: off */
230 put_bits(&s->pb, 1, 0); /* SAC: off */
231 put_bits(&s->pb, 1, 0); /* advanced prediction mode: off */
232 put_bits(&s->pb, 1, 0); /* not PB frame */
233 put_bits(&s->pb, 5, s->qscale);
234 put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
235 } else {
236 /* H.263v2 */
237 /* H.263 Plus PTYPE */
238 put_bits(&s->pb, 3, 7);
239 put_bits(&s->pb,3,1); /* Update Full Extended PTYPE */
240 if (format == 7)
241 put_bits(&s->pb,3,6); /* Custom Source Format */
242 else
243 put_bits(&s->pb, 3, format);
244
245 put_bits(&s->pb,1,0); /* Custom PCF: off */
246 s->umvplus = s->unrestricted_mv;
247 put_bits(&s->pb, 1, s->umvplus); /* Unrestricted Motion Vector */
248 put_bits(&s->pb,1,0); /* SAC: off */
249 put_bits(&s->pb,1,0); /* Advanced Prediction Mode: off */
250 put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
251 put_bits(&s->pb,1,0); /* Deblocking Filter: off */
252 put_bits(&s->pb,1,0); /* Slice Structured: off */
253 put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
254 put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
255 put_bits(&s->pb,1,0); /* Alternative Inter VLC: off */
256 put_bits(&s->pb,1,0); /* Modified Quantization: off */
257 put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
258 put_bits(&s->pb,3,0); /* Reserved */
259
260 put_bits(&s->pb, 3, s->pict_type == P_TYPE);
261
262 put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
263 put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
264 put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
265 put_bits(&s->pb,2,0); /* Reserved */
266 put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
267
268 /* This should be here if PLUSPTYPE */
269 put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
270
271 if (format == 7) {
272 /* Custom Picture Format (CPFMT) */
273 float_aspect_to_info(s, s->avctx->aspect_ratio);
274
275 put_bits(&s->pb,4,s->aspect_ratio_info);
276 put_bits(&s->pb,9,(s->width >> 2) - 1);
277 put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
278 put_bits(&s->pb,9,(s->height >> 2));
279 if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
280 {
281 put_bits(&s->pb, 8, s->aspected_width);
282 put_bits(&s->pb, 8, s->aspected_height);
283 }
284 }
285
286 /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
287 if (s->umvplus)
288 // put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
289 put_bits(&s->pb,2,1); /* unlimited */
290
291 put_bits(&s->pb, 5, s->qscale);
292 }
293
294 put_bits(&s->pb, 1, 0); /* no PEI */
295
296 if(s->h263_aic){
297 s->y_dc_scale_table=
298 s->c_dc_scale_table= h263_aic_dc_scale_table;
299 }else{
300 s->y_dc_scale_table=
301 s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
302 }
303 }
304
305 /**
306 * Encodes a group of blocks header.
307 */
308 int h263_encode_gob_header(MpegEncContext * s, int mb_line)
309 {
310 align_put_bits(&s->pb);
311 flush_put_bits(&s->pb);
312 /* Call the RTP callback to send the last GOB */
313 if (s->rtp_callback) {
314 int pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
315 s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
316 }
317 put_bits(&s->pb, 17, 1); /* GBSC */
318 s->gob_number = mb_line / s->gob_index;
319 put_bits(&s->pb, 5, s->gob_number); /* GN */
320 put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
321 put_bits(&s->pb, 5, s->qscale); /* GQUANT */
322 //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
323 return 0;
324 }
325
326 static inline int get_block_rate(MpegEncContext * s, DCTELEM block[64], int block_last_index, uint8_t scantable[64]){
327 int last=0;
328 int j;
329 int rate=0;
330
331 for(j=1; j<=block_last_index; j++){
332 const int index= scantable[j];
333 int level= block[index];
334 if(level){
335 level+= 64;
336 if((level&(~127)) == 0){
337 if(j<block_last_index) rate+= s->intra_ac_vlc_length [UNI_AC_ENC_INDEX(j-last-1, level)];
338 else rate+= s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j-last-1, level)];
339 }else
340 rate += s->ac_esc_length;
341 level-= 64;
342
343 last= j;
344 }
345 }
346
347 return rate;
348 }
349
350 static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
351 {
352 int score= 0;
353 int i, n;
354 int8_t * const qscale_table= s->current_picture.qscale_table;
355
356 memcpy(zigzag_last_index, s->block_last_index, sizeof(int)*6);
357
358 for(n=0; n<6; n++){
359 int16_t *ac_val, *ac_val1;
360
361 score -= get_block_rate(s, block[n], s->block_last_index[n], s->intra_scantable.permutated);
362
363 ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
364 ac_val1= ac_val;
365 if(dir[n]){
366 const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
367 /* top prediction */
368 ac_val-= s->block_wrap[n]*16;
369 if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
370 /* same qscale */
371 for(i=1; i<8; i++){
372 const int level= block[n][s->dsp.idct_permutation[i ]];
373 block[n][s->dsp.idct_permutation[i ]] = level - ac_val[i+8];
374 ac_val1[i ]= block[n][s->dsp.idct_permutation[i<<3]];
375 ac_val1[i+8]= level;
376 }
377 }else{
378 /* different qscale, we must rescale */
379 for(i=1; i<8; i++){
380 const int level= block[n][s->dsp.idct_permutation[i ]];
381 block[n][s->dsp.idct_permutation[i ]] = level - ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
382 ac_val1[i ]= block[n][s->dsp.idct_permutation[i<<3]];
383 ac_val1[i+8]= level;
384 }
385 }
386 st[n]= s->intra_h_scantable.permutated;
387 }else{
388 const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
389 /* left prediction */
390 ac_val-= 16;
391 if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
392 /* same qscale */
393 for(i=1; i<8; i++){
394 const int level= block[n][s->dsp.idct_permutation[i<<3]];
395 block[n][s->dsp.idct_permutation[i<<3]]= level - ac_val[i];
396 ac_val1[i ]= level;
397 ac_val1[i+8]= block[n][s->dsp.idct_permutation[i ]];
398 }
399 }else{
400 /* different qscale, we must rescale */
401 for(i=1; i<8; i++){
402 const int level= block[n][s->dsp.idct_permutation[i<<3]];
403 block[n][s->dsp.idct_permutation[i<<3]]= level - ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
404 ac_val1[i ]= level;
405 ac_val1[i+8]= block[n][s->dsp.idct_permutation[i ]];
406 }
407 }
408 st[n]= s->intra_v_scantable.permutated;
409 }
410
411 for(i=63; i>0; i--) //FIXME optimize
412 if(block[n][ st[n][i] ]) break;
413 s->block_last_index[n]= i;
414
415 score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
416 }
417
418 return score < 0;
419 }
420
421 static inline void restore_ac_coeffs(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
422 {
423 int i, n;
424 memcpy(s->block_last_index, zigzag_last_index, sizeof(int)*6);
425
426 for(n=0; n<6; n++){
427 int16_t *ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
428
429 st[n]= s->intra_scantable.permutated;
430 if(dir[n]){
431 /* top prediction */
432 for(i=1; i<8; i++){
433 block[n][s->dsp.idct_permutation[i ]] = ac_val[i+8];
434 }
435 }else{
436 /* left prediction */
437 for(i=1; i<8; i++){
438 block[n][s->dsp.idct_permutation[i<<3]]= ac_val[i ];
439 }
440 }
441 }
442 }
443
444 /**
445 * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
446 */
447 void ff_clean_h263_qscales(MpegEncContext *s){
448 int i;
449 int8_t * const qscale_table= s->current_picture.qscale_table;
450
451 for(i=1; i<s->mb_num; i++){
452 if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i-1] ] >2)
453 qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i-1] ]+2;
454 }
455 for(i=s->mb_num-2; i>=0; i--){
456 if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i+1] ] >2)
457 qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i+1] ]+2;
458 }
459 }
460
461 /**
462 * modify mb_type & qscale so that encoding is acually possible in mpeg4
463 */
464 void ff_clean_mpeg4_qscales(MpegEncContext *s){
465 int i;
466 int8_t * const qscale_table= s->current_picture.qscale_table;
467
468 ff_clean_h263_qscales(s);
469
470 for(i=1; i<s->mb_num; i++){
471 int mb_xy= s->mb_index2xy[i];
472
473 if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&MB_TYPE_INTER4V)){
474 s->mb_type[mb_xy]&= ~MB_TYPE_INTER4V;
475 s->mb_type[mb_xy]|= MB_TYPE_INTER;
476 }
477 }
478
479 if(s->pict_type== B_TYPE){
480 int odd=0;
481 /* ok, come on, this isnt funny anymore, theres more code for handling this mpeg4 mess than
482 for the actual adaptive quantization */
483
484 for(i=0; i<s->mb_num; i++){
485 int mb_xy= s->mb_index2xy[i];
486 odd += qscale_table[mb_xy]&1;
487 }
488
489 if(2*odd > s->mb_num) odd=1;
490 else odd=0;
491
492 for(i=0; i<s->mb_num; i++){
493 int mb_xy= s->mb_index2xy[i];
494 if((qscale_table[mb_xy]&1) != odd)
495 qscale_table[mb_xy]++;
496 if(qscale_table[mb_xy] > 31)
497 qscale_table[mb_xy]= 31;
498 }
499
500 for(i=1; i<s->mb_num; i++){
501 int mb_xy= s->mb_index2xy[i];
502 if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&MB_TYPE_DIRECT)){
503 s->mb_type[mb_xy]&= ~MB_TYPE_DIRECT;
504 s->mb_type[mb_xy]|= MB_TYPE_BIDIR;
505 }
506 }
507 }
508 }
509
510 #endif //CONFIG_ENCODERS
511 /**
512 *
513 * @return the mb_type
514 */
515 int ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
516 const int mb_index= s->mb_x + s->mb_y*s->mb_stride;
517 const int colocated_mb_type= s->next_picture.mb_type[mb_index]; //FIXME or next?
518 int xy= s->block_index[0];
519 uint16_t time_pp= s->pp_time;
520 uint16_t time_pb= s->pb_time;
521 int i;
522
523 //FIXME avoid divides
524
525 if(IS_8X8(colocated_mb_type)){
526 s->mv_type = MV_TYPE_8X8;
527 for(i=0; i<4; i++){
528 xy= s->block_index[i];
529 s->mv[0][i][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
530 s->mv[0][i][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
531 s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->motion_val[xy][0]
532 : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
533 s->mv[1][i][1] = my ? s->mv[0][i][1] - s->motion_val[xy][1]
534 : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
535 }
536 return MB_TYPE_DIRECT2 | MB_TYPE_8x8 | MB_TYPE_L0L1;
537 } else if(IS_INTERLACED(colocated_mb_type)){
538 s->mv_type = MV_TYPE_FIELD;
539 for(i=0; i<2; i++){
540 if(s->top_field_first){
541 time_pp= s->pp_field_time - s->field_select_table[mb_index][i] + i;
542 time_pb= s->pb_field_time - s->field_select_table[mb_index][i] + i;
543 }else{
544 time_pp= s->pp_field_time + s->field_select_table[mb_index][i] - i;
545 time_pb= s->pb_field_time + s->field_select_table[mb_index][i] - i;
546 }
547 s->mv[0][i][0] = s->field_mv_table[mb_index][i][0]*time_pb/time_pp + mx;
548 s->mv[0][i][1] = s->field_mv_table[mb_index][i][1]*time_pb/time_pp + my;
549 s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->field_mv_table[mb_index][i][0]
550 : s->field_mv_table[mb_index][i][0]*(time_pb - time_pp)/time_pp;
551 s->mv[1][i][1] = my ? s->mv[0][i][1] - s->field_mv_table[mb_index][i][1]
552 : s->field_mv_table[mb_index][i][1]*(time_pb - time_pp)/time_pp;
553 }
554 return MB_TYPE_DIRECT2 | MB_TYPE_16x8 | MB_TYPE_L0L1 | MB_TYPE_INTERLACED;
555 }else{
556 s->mv[0][0][0] = s->mv[0][1][0] = s->mv[0][2][0] = s->mv[0][3][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
557 s->mv[0][0][1] = s->mv[0][1][1] = s->mv[0][2][1] = s->mv[0][3][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
558 s->mv[1][0][0] = s->mv[1][1][0] = s->mv[1][2][0] = s->mv[1][3][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
559 : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
560 s->mv[1][0][1] = s->mv[1][1][1] = s->mv[1][2][1] = s->mv[1][3][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1]
561 : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
562 if((s->avctx->workaround_bugs & FF_BUG_DIRECT_BLOCKSIZE) || !s->quarter_sample)
563 s->mv_type= MV_TYPE_16X16;
564 else
565 s->mv_type= MV_TYPE_8X8;
566 return MB_TYPE_DIRECT2 | MB_TYPE_16x16 | MB_TYPE_L0L1; //Note see prev line
567 }
568 }
569
570 void ff_h263_update_motion_val(MpegEncContext * s){
571 const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
572 //FIXME a lot of thet is only needed for !low_delay
573 const int wrap = s->block_wrap[0];
574 const int xy = s->block_index[0];
575
576 s->current_picture.mbskip_table[mb_xy]= s->mb_skiped;
577
578 if(s->mv_type != MV_TYPE_8X8){
579 int motion_x, motion_y;
580 if (s->mb_intra) {
581 motion_x = 0;
582 motion_y = 0;
583 } else if (s->mv_type == MV_TYPE_16X16) {
584 motion_x = s->mv[0][0][0];
585 motion_y = s->mv[0][0][1];
586 } else /*if (s->mv_type == MV_TYPE_FIELD)*/ {
587 int i;
588 motion_x = s->mv[0][0][0] + s->mv[0][1][0];
589 motion_y = s->mv[0][0][1] + s->mv[0][1][1];
590 motion_x = (motion_x>>1) | (motion_x&1);
591 for(i=0; i<2; i++){
592 s->field_mv_table[mb_xy][i][0]= s->mv[0][i][0];
593 s->field_mv_table[mb_xy][i][1]= s->mv[0][i][1];
594 s->field_select_table[mb_xy][i]= s->field_select[0][i];
595 }
596 }
597
598 /* no update if 8X8 because it has been done during parsing */
599 s->motion_val[xy][0] = motion_x;
600 s->motion_val[xy][1] = motion_y;
601 s->motion_val[xy + 1][0] = motion_x;
602 s->motion_val[xy + 1][1] = motion_y;
603 s->motion_val[xy + wrap][0] = motion_x;
604 s->motion_val[xy + wrap][1] = motion_y;
605 s->motion_val[xy + 1 + wrap][0] = motion_x;
606 s->motion_val[xy + 1 + wrap][1] = motion_y;
607 }
608
609 if(s->encoding){ //FIXME encoding MUST be cleaned up
610 if (s->mv_type == MV_TYPE_8X8)
611 s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_8x8;
612 else
613 s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_16x16;
614 }
615 }
616
617 #ifdef CONFIG_ENCODERS
618
619 static inline int get_p_cbp(MpegEncContext * s,
620 DCTELEM block[6][64],
621 int motion_x, int motion_y){
622 int cbp, i;
623
624 if(s->flags & CODEC_FLAG_CBP_RD){
625 int best_cbpy_score= INT_MAX;
626 int best_cbpc_score= INT_MAX;
627 int cbpc, cbpy;
628 const int offset= (s->mv_type==MV_TYPE_16X16 ? 0 : 16) + (s->dquant ? 8 : 0);
629 const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
630
631 for(i=0; i<4; i++){
632 int score= inter_MCBPC_bits[i + offset] * lambda;
633 if(i&1) score += s->coded_score[5];
634 if(i&2) score += s->coded_score[4];
635
636 if(score < best_cbpc_score){
637 best_cbpc_score= score;
638 cbpc= i;
639 }
640 }
641
642 for(i=0; i<16; i++){
643 int score= cbpy_tab[i ^ 0xF][1] * lambda;
644 if(i&1) score += s->coded_score[3];
645 if(i&2) score += s->coded_score[2];
646 if(i&4) score += s->coded_score[1];
647 if(i&8) score += s->coded_score[0];
648
649 if(score < best_cbpy_score){
650 best_cbpy_score= score;
651 cbpy= i;
652 }
653 }
654 cbp= cbpc + 4*cbpy;
655 if ((motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16){
656 if(best_cbpy_score + best_cbpc_score + 2*lambda >= 0)
657 cbp= 0;
658 }
659
660 for (i = 0; i < 6; i++) {
661 if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
662 s->block_last_index[i]= -1;
663 memset(s->block[i], 0, sizeof(DCTELEM)*64);
664 }
665 }
666 }else{
667 cbp= 0;
668 for (i = 0; i < 6; i++) {
669 if (s->block_last_index[i] >= 0)
670 cbp |= 1 << (5 - i);
671 }
672 }
673 return cbp;
674 }
675
676 static inline int get_b_cbp(MpegEncContext * s, DCTELEM block[6][64],
677 int motion_x, int motion_y, int mb_type){
678 int cbp=0, i;
679
680 if(s->flags & CODEC_FLAG_CBP_RD){
681 int score=0;
682 const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
683
684 for(i=0; i<6; i++){
685 if(s->coded_score[i] < 0){
686 score += s->coded_score[i];
687 cbp |= 1 << (5 - i);
688 }
689 }
690
691 if(cbp){
692 int zero_score= -6;
693 if ((motion_x | motion_y | s->dquant | mb_type) == 0){
694 zero_score-= 4; //2*MV + mb_type + cbp bit
695 }
696
697 zero_score*= lambda;
698 if(zero_score <= score){
699 cbp=0;
700 }
701 }
702
703 for (i = 0; i < 6; i++) {
704 if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
705 s->block_last_index[i]= -1;
706 memset(s->block[i], 0, sizeof(DCTELEM)*64);
707 }
708 }
709 }else{
710 for (i = 0; i < 6; i++) {
711 if (s->block_last_index[i] >= 0)
712 cbp |= 1 << (5 - i);
713 }
714 }
715 return cbp;
716 }
717
718 void mpeg4_encode_mb(MpegEncContext * s,
719 DCTELEM block[6][64],
720 int motion_x, int motion_y)
721 {
722 int cbpc, cbpy, pred_x, pred_y;
723 PutBitContext * const pb2 = s->data_partitioning ? &s->pb2 : &s->pb;
724 PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=B_TYPE ? &s->tex_pb : &s->pb;
725 PutBitContext * const dc_pb = s->data_partitioning && s->pict_type!=I_TYPE ? &s->pb2 : &s->pb;
726 const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
727 const int dquant_code[5]= {1,0,9,2,3};
728
729 // printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
730 if (!s->mb_intra) {
731 /* compute cbp */
732 int i, cbp;
733
734 if(s->pict_type==B_TYPE){
735 static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
736 int mb_type= mb_type_table[s->mv_dir];
737
738 if(s->mb_x==0){
739 s->last_mv[0][0][0]=
740 s->last_mv[0][0][1]=
741 s->last_mv[1][0][0]=
742 s->last_mv[1][0][1]= 0;
743 }
744
745 assert(s->dquant>=-2 && s->dquant<=2);
746 assert((s->dquant&1)==0);
747 assert(mb_type>=0);
748
749 /* nothing to do if this MB was skiped in the next P Frame */
750 if(s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]){ //FIXME avoid DCT & ...
751 s->skip_count++;
752 s->mv[0][0][0]=
753 s->mv[0][0][1]=
754 s->mv[1][0][0]=
755 s->mv[1][0][1]= 0;
756 s->mv_dir= MV_DIR_FORWARD; //doesnt matter
757 s->qscale -= s->dquant;
758 // s->mb_skiped=1;
759
760 return;
761 }
762
763 cbp= get_b_cbp(s, block, motion_x, motion_y, mb_type);
764
765 if ((cbp | motion_x | motion_y | mb_type) ==0) {
766 /* direct MB with MV={0,0} */
767 assert(s->dquant==0);
768
769 put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
770
771 if(interleaved_stats){
772 s->misc_bits++;
773 s->last_bits++;
774 }
775 s->skip_count++;
776 return;
777 }
778
779 put_bits(&s->pb, 1, 0); /* mb coded modb1=0 */
780 put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
781 put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we dont need it :)
782 if(cbp) put_bits(&s->pb, 6, cbp);
783
784 if(cbp && mb_type){
785 if(s->dquant)
786 put_bits(&s->pb, 2, (s->dquant>>2)+3);
787 else
788 put_bits(&s->pb, 1, 0);
789 }else
790 s->qscale -= s->dquant;
791
792 if(!s->progressive_sequence){
793 if(cbp)
794 put_bits(&s->pb, 1, s->interlaced_dct);
795 if(mb_type) // not diect mode
796 put_bits(&s->pb, 1, 0); // no interlaced ME yet
797 }
798
799 if(interleaved_stats){
800 s->misc_bits+= get_bits_diff(s);
801 }
802
803 switch(mb_type)
804 {
805 case 0: /* direct */
806 h263_encode_motion(s, motion_x, 1);
807 h263_encode_motion(s, motion_y, 1);
808 s->b_count++;
809 s->f_count++;
810 break;
811 case 1: /* bidir */
812 h263_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
813 h263_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
814 h263_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
815 h263_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
816 s->last_mv[0][0][0]= s->mv[0][0][0];
817 s->last_mv[0][0][1]= s->mv[0][0][1];
818 s->last_mv[1][0][0]= s->mv[1][0][0];
819 s->last_mv[1][0][1]= s->mv[1][0][1];
820 s->b_count++;
821 s->f_count++;
822 break;
823 case 2: /* backward */
824 h263_encode_motion(s, motion_x - s->last_mv[1][0][0], s->b_code);
825 h263_encode_motion(s, motion_y - s->last_mv[1][0][1], s->b_code);
826 s->last_mv[1][0][0]= motion_x;
827 s->last_mv[1][0][1]= motion_y;
828 s->b_count++;
829 break;
830 case 3: /* forward */
831 h263_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);
832 h263_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);
833 s->last_mv[0][0][0]= motion_x;
834 s->last_mv[0][0][1]= motion_y;
835 s->f_count++;
836 break;
837 default:
838 printf("unknown mb type\n");
839 return;
840 }
841
842 if(interleaved_stats){
843 s->mv_bits+= get_bits_diff(s);
844 }
845
846 /* encode each block */
847 for (i = 0; i < 6; i++) {
848 mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, &s->pb);
849 }
850
851 if(interleaved_stats){
852 s->p_tex_bits+= get_bits_diff(s);
853 }
854 }else{ /* s->pict_type==B_TYPE */
855 cbp= get_p_cbp(s, block, motion_x, motion_y);
856
857 if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
858 /* check if the B frames can skip it too, as we must skip it if we skip here
859 why didnt they just compress the skip-mb bits instead of reusing them ?! */
860 if(s->max_b_frames>0){
861 int i;
862 int x,y, offset;
863 uint8_t *p_pic;
864
865 x= s->mb_x*16;
866 y= s->mb_y*16;
867 if(x+16 > s->width) x= s->width-16;
868 if(y+16 > s->height) y= s->height-16;
869
870 offset= x + y*s->linesize;
871 p_pic= s->new_picture.data[0] + offset;
872
873 s->mb_skiped=1;
874 for(i=0; i<s->max_b_frames; i++){
875 uint8_t *b_pic;
876 int diff;
877 Picture *pic= s->reordered_input_picture[i+1];
878
879 if(pic==NULL || pic->pict_type!=B_TYPE) break;
880
881 b_pic= pic->data[0] + offset + 16; //FIXME +16
882 diff= s->dsp.pix_abs16x16(p_pic, b_pic, s->linesize);
883 if(diff>s->qscale*70){ //FIXME check that 70 is optimal
884 s->mb_skiped=0;
885 break;
886 }
887 }
888 }else
889 s->mb_skiped=1;
890
891 if(s->mb_skiped==1){
892 /* skip macroblock */
893 put_bits(&s->pb, 1, 1);
894
895 if(interleaved_stats){
896 s->misc_bits++;
897 s->last_bits++;
898 }
899 s->skip_count++;
900
901 return;
902 }
903 }
904
905 put_bits(&s->pb, 1, 0); /* mb coded */
906 if(s->mv_type==MV_TYPE_16X16){
907 cbpc = cbp & 3;
908 if(s->dquant) cbpc+= 8;
909 put_bits(&s->pb,
910 inter_MCBPC_bits[cbpc],
911 inter_MCBPC_code[cbpc]);
912
913 cbpy = cbp >> 2;
914 cbpy ^= 0xf;
915 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
916 if(s->dquant)
917 put_bits(pb2, 2, dquant_code[s->dquant+2]);
918
919 if(!s->progressive_sequence){
920 if(cbp)
921 put_bits(pb2, 1, s->interlaced_dct);
922 put_bits(pb2, 1, 0); // no interlaced ME yet
923 }
924
925 if(interleaved_stats){
926 s->misc_bits+= get_bits_diff(s);
927 }
928
929 /* motion vectors: 16x16 mode */
930 h263_pred_motion(s, 0, &pred_x, &pred_y);
931
932 h263_encode_motion(s, motion_x - pred_x, s->f_code);
933 h263_encode_motion(s, motion_y - pred_y, s->f_code);
934 }else{
935 cbpc = (cbp & 3)+16;
936 put_bits(&s->pb,
937 inter_MCBPC_bits[cbpc],
938 inter_MCBPC_code[cbpc]);
939 cbpy = cbp >> 2;
940 cbpy ^= 0xf;
941 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
942
943 if(!s->progressive_sequence){
944 if(cbp)
945 put_bits(pb2, 1, s->interlaced_dct);
946 }
947
948 if(interleaved_stats){
949 s->misc_bits+= get_bits_diff(s);
950 }
951
952 for(i=0; i<4; i++){
953 /* motion vectors: 8x8 mode*/
954 h263_pred_motion(s, i, &pred_x, &pred_y);
955
956 h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x, s->f_code);
957 h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y, s->f_code);
958 }
959 }
960
961 if(interleaved_stats){
962 s->mv_bits+= get_bits_diff(s);
963 }
964
965 /* encode each block */
966 for (i = 0; i < 6; i++) {
967 mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, tex_pb);
968 }
969
970 if(interleaved_stats){
971 s->p_tex_bits+= get_bits_diff(s);
972 }
973 s->f_count++;
974 }
975 } else {
976 int cbp;
977 int dc_diff[6]; //dc values with the dc prediction subtracted
978 int dir[6]; //prediction direction
979 int zigzag_last_index[6];
980 uint8_t *scan_table[6];
981 int i;
982
983 for(i=0; i<6; i++){
984 const int level= block[i][0];
985 uint16_t *dc_ptr;
986
987 dc_diff[i]= level - ff_mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
988 if (i < 4) {
989 *dc_ptr = level * s->y_dc_scale;
990 } else {
991 *dc_ptr = level * s->c_dc_scale;
992 }
993 }
994
995 if(s->flags & CODEC_FLAG_AC_PRED){
996 s->ac_pred= decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
997 if(!s->ac_pred)
998 restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
999 }else{
1000 for(i=0; i<6; i++)
1001 scan_table[i]= s->intra_scantable.permutated;
1002 }
1003
1004 /* compute cbp */
1005 cbp = 0;
1006 for (i = 0; i < 6; i++) {
1007 if (s->block_last_index[i] >= 1)
1008 cbp |= 1 << (5 - i);
1009 }
1010
1011 cbpc = cbp & 3;
1012 if (s->pict_type == I_TYPE) {
1013 if(s->dquant) cbpc+=4;
1014 put_bits(&s->pb,
1015 intra_MCBPC_bits[cbpc],
1016 intra_MCBPC_code[cbpc]);
1017 } else {
1018 if(s->dquant) cbpc+=8;
1019 put_bits(&s->pb, 1, 0); /* mb coded */
1020 put_bits(&s->pb,
1021 inter_MCBPC_bits[cbpc + 4],
1022 inter_MCBPC_code[cbpc + 4]);
1023 }
1024 put_bits(pb2, 1, s->ac_pred);
1025 cbpy = cbp >> 2;
1026 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1027 if(s->dquant)
1028 put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
1029
1030 if(!s->progressive_sequence){
1031 put_bits(dc_pb, 1, s->interlaced_dct);
1032 }
1033
1034 if(interleaved_stats){
1035 s->misc_bits+= get_bits_diff(s);
1036 }
1037
1038 /* encode each block */
1039 for (i = 0; i < 6; i++) {
1040 mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
1041 }
1042
1043 if(interleaved_stats){
1044 s->i_tex_bits+= get_bits_diff(s);
1045 }
1046 s->i_count++;
1047
1048 /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
1049 if(s->ac_pred)
1050 restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1051 }
1052 }
1053
1054 void h263_encode_mb(MpegEncContext * s,
1055 DCTELEM block[6][64],
1056 int motion_x, int motion_y)
1057 {
1058 int cbpc, cbpy, i, cbp, pred_x, pred_y;
1059 int16_t pred_dc;
1060 int16_t rec_intradc[6];
1061 uint16_t *dc_ptr[6];
1062 const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1);
1063 const int dquant_code[5]= {1,0,9,2,3};
1064
1065 //printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
1066 if (!s->mb_intra) {
1067 /* compute cbp */
1068 cbp= get_p_cbp(s, block, motion_x, motion_y);
1069
1070 if ((cbp | motion_x | motion_y | s->dquant) == 0) {
1071 /* skip macroblock */
1072 put_bits(&s->pb, 1, 1);
1073 if(interleaved_stats){
1074 s->misc_bits++;
1075 s->last_bits++;
1076 }
1077 return;
1078 }
1079 put_bits(&s->pb, 1, 0); /* mb coded */
1080 cbpc = cbp & 3;
1081 if(s->dquant) cbpc+= 8;
1082 put_bits(&s->pb,
1083 inter_MCBPC_bits[cbpc],
1084 inter_MCBPC_code[cbpc]);
1085 cbpy = cbp >> 2;
1086 cbpy ^= 0xf;
1087 put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1088 if(s->dquant)
1089 put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1090
1091 if(interleaved_stats){
1092 s->misc_bits+= get_bits_diff(s);
1093 }
1094
1095 /* motion vectors: 16x16 mode only now */
1096 h263_pred_motion(s, 0, &pred_x, &pred_y);
1097
1098 if (!s->umvplus) {
1099 h263_encode_motion(s, motion_x - pred_x, s->f_code);
1100 h263_encode_motion(s, motion_y - pred_y, s->f_code);
1101 }
1102 else {
1103 h263p_encode_umotion(s, motion_x - pred_x);
1104 h263p_encode_umotion(s, motion_y - pred_y);
1105 if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1106 /* To prevent Start Code emulation */
1107 put_bits(&s->pb,1,1);
1108 }
1109
1110 if(interleaved_stats){
1111 s->mv_bits+= get_bits_diff(s);
1112 }
1113 } else {
1114 int li = s->h263_aic ? 0 : 1;
1115
1116 cbp = 0;
1117 for(i=0; i<6; i++) {
1118 /* Predict DC */
1119 if (s->h263_aic && s->mb_intra) {
1120 int16_t level = block[i][0];
1121
1122 pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
1123 level -= pred_dc;
1124 /* Quant */
1125 if (level < 0)
1126 level = (level + (s->qscale >> 1))/(s->y_dc_scale);
1127 else
1128 level = (level - (s->qscale >> 1))/(s->y_dc_scale);
1129
1130 /* AIC can change CBP */
1131 if (level == 0 && s->block_last_index[i] == 0)
1132 s->block_last_index[i] = -1;
1133 else if (level < -127)
1134 level = -127;
1135 else if (level > 127)
1136 level = 127;
1137
1138 block[i][0] = level;
1139 /* Reconstruction */
1140 rec_intradc[i] = (s->y_dc_scale*level) + pred_dc;
1141 /* Oddify */
1142 rec_intradc[i] |= 1;
1143 //if ((rec_intradc[i] % 2) == 0)
1144 // rec_intradc[i]++;
1145 /* Clipping */
1146 if (rec_intradc[i] < 0)
1147 rec_intradc[i] = 0;
1148 else if (rec_intradc[i] > 2047)
1149 rec_intradc[i] = 2047;
1150
1151 /* Update AC/DC tables */
1152 *dc_ptr[i] = rec_intradc[i];
1153 }
1154 /* compute cbp */
1155 if (s->block_last_index[i] >= li)
1156 cbp |= 1 << (5 - i);
1157 }
1158
1159 cbpc = cbp & 3;
1160 if (s->pict_type == I_TYPE) {
1161 if(s->dquant) cbpc+=4;
1162 put_bits(&s->pb,
1163 intra_MCBPC_bits[cbpc],
1164 intra_MCBPC_code[cbpc]);
1165 } else {
1166 if(s->dquant) cbpc+=8;
1167 put_bits(&s->pb, 1, 0); /* mb coded */
1168 put_bits(&s->pb,
1169 inter_MCBPC_bits[cbpc + 4],
1170 inter_MCBPC_code[cbpc + 4]);
1171 }
1172 if (s->h263_aic) {
1173 /* XXX: currently, we do not try to use ac prediction */
1174 put_bits(&s->pb, 1, 0); /* no AC prediction */
1175 }
1176 cbpy = cbp >> 2;
1177 put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1178 if(s->dquant)
1179 put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1180
1181 if(interleaved_stats){
1182 s->misc_bits+= get_bits_diff(s);
1183 }
1184 }
1185
1186 for(i=0; i<6; i++) {
1187 /* encode each block */
1188 h263_encode_block(s, block[i], i);
1189
1190 /* Update INTRADC for decoding */
1191 if (s->h263_aic && s->mb_intra) {
1192 block[i][0] = rec_intradc[i];
1193
1194 }
1195 }
1196
1197 if(interleaved_stats){
1198 if (!s->mb_intra) {
1199 s->p_tex_bits+= get_bits_diff(s);
1200 s->f_count++;
1201 }else{
1202 s->i_tex_bits+= get_bits_diff(s);
1203 s->i_count++;
1204 }
1205 }
1206 }
1207 #endif
1208
1209 static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr)
1210 {
1211 int x, y, wrap, a, c, pred_dc, scale;
1212 int16_t *dc_val, *ac_val;
1213
1214 /* find prediction */
1215 if (n < 4) {
1216 x = 2 * s->mb_x + 1 + (n & 1);
1217 y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
1218 wrap = s->mb_width * 2 + 2;
1219 dc_val = s->dc_val[0];
1220 ac_val = s->ac_val[0][0];
1221 scale = s->y_dc_scale;
1222 } else {
1223 x = s->mb_x + 1;
1224 y = s->mb_y + 1;
1225 wrap = s->mb_width + 2;
1226 dc_val = s->dc_val[n - 4 + 1];
1227 ac_val = s->ac_val[n - 4 + 1][0];
1228 scale = s->c_dc_scale;
1229 }
1230 /* B C
1231 * A X
1232 */
1233 a = dc_val[(x - 1) + (y) * wrap];
1234 c = dc_val[(x) + (y - 1) * wrap];
1235
1236 /* No prediction outside GOB boundary */
1237 if (s->first_slice_line && ((n < 2) || (n > 3)))
1238 c = 1024;
1239 pred_dc = 1024;
1240 /* just DC prediction */
1241 if (a != 1024 && c != 1024)
1242 pred_dc = (a + c) >> 1;
1243 else if (a != 1024)
1244 pred_dc = a;
1245 else
1246 pred_dc = c;
1247
1248 /* we assume pred is positive */
1249 //pred_dc = (pred_dc + (scale >> 1)) / scale;
1250 *dc_val_ptr = &dc_val[x + y * wrap];
1251 return pred_dc;
1252 }
1253
1254 static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1255 {
1256 int x, y, wrap, a, c, pred_dc, scale, i;
1257 int16_t *dc_val, *ac_val, *ac_val1;
1258
1259 /* find prediction */
1260 if (n < 4) {
1261 x = 2 * s->mb_x + 1 + (n & 1);
1262 y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
1263 wrap = s->mb_width * 2 + 2;
1264 dc_val = s->dc_val[0];
1265 ac_val = s->ac_val[0][0];
1266 scale = s->y_dc_scale;
1267 } else {
1268 x = s->mb_x + 1;
1269 y = s->mb_y + 1;
1270 wrap = s->mb_width + 2;
1271 dc_val = s->dc_val[n - 4 + 1];
1272 ac_val = s->ac_val[n - 4 + 1][0];
1273 scale = s->c_dc_scale;
1274 }
1275
1276 ac_val += ((y) * wrap + (x)) * 16;
1277 ac_val1 = ac_val;
1278
1279 /* B C
1280 * A X
1281 */
1282 a = dc_val[(x - 1) + (y) * wrap];
1283 c = dc_val[(x) + (y - 1) * wrap];
1284
1285 /* No prediction outside GOB boundary */
1286 if (s->first_slice_line && ((n < 2) || (n > 3)))
1287 c = 1024;
1288 pred_dc = 1024;
1289 if (s->ac_pred) {
1290 if (s->h263_aic_dir) {
1291 /* left prediction */
1292 if (a != 1024) {
1293 ac_val -= 16;
1294 for(i=1;i<8;i++) {
1295 block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1296 }
1297 pred_dc = a;
1298 }
1299 } else {
1300 /* top prediction */
1301 if (c != 1024) {
1302 ac_val -= 16 * wrap;
1303 for(i=1;i<8;i++) {
1304 block[s->dsp.idct_permutation[i ]] += ac_val[i + 8];
1305 }
1306 pred_dc = c;
1307 }
1308 }
1309 } else {
1310 /* just DC prediction */
1311 if (a != 1024 && c != 1024)
1312 pred_dc = (a + c) >> 1;
1313 else if (a != 1024)
1314 pred_dc = a;
1315 else
1316 pred_dc = c;
1317 }
1318
1319 /* we assume pred is positive */
1320 block[0]=block[0]*scale + pred_dc;
1321
1322 if (block[0] < 0)
1323 block[0] = 0;
1324 else if (!(block[0] & 1))
1325 block[0]++;
1326
1327 /* Update AC/DC tables */
1328 dc_val[(x) + (y) * wrap] = block[0];
1329
1330 /* left copy */
1331 for(i=1;i<8;i++)
1332 ac_val1[i ] = block[s->dsp.idct_permutation[i<<3]];
1333 /* top copy */
1334 for(i=1;i<8;i++)
1335 ac_val1[8 + i] = block[s->dsp.idct_permutation[i ]];
1336 }
1337
1338 int16_t *h263_pred_motion(MpegEncContext * s, int block,
1339 int *px, int *py)
1340 {
1341 int xy, wrap;
1342 int16_t *A, *B, *C, *mot_val;
1343 static const int off[4]= {2, 1, 1, -1};
1344
1345 wrap = s->block_wrap[0];
1346 xy = s->block_index[block];
1347
1348 mot_val = s->motion_val[xy];
1349
1350 A = s->motion_val[xy - 1];
1351 /* special case for first (slice) line */
1352 if (s->first_slice_line && block<3) {
1353 // we cant just change some MVs to simulate that as we need them for the B frames (and ME)
1354 // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1355 if(block==0){ //most common case
1356 if(s->mb_x == s->resync_mb_x){ //rare
1357 *px= *py = 0;
1358 }else if(s->mb_x + 1 == s->resync_mb_x){ //rare
1359 C = s->motion_val[xy + off[block] - wrap];
1360 if(s->mb_x==0){
1361 *px = C[0];
1362 *py = C[1];
1363 }else{
1364 *px = mid_pred(A[0], 0, C[0]);
1365 *py = mid_pred(A[1], 0, C[1]);
1366 }
1367 }else{
1368 *px = A[0];
1369 *py = A[1];
1370 }
1371 }else if(block==1){
1372 if(s->mb_x + 1 == s->resync_mb_x){ //rare
1373 C = s->motion_val[xy + off[block] - wrap];
1374 *px = mid_pred(A[0], 0, C[0]);
1375 *py = mid_pred(A[1], 0, C[1]);
1376 }else{
1377 *px = A[0];
1378 *py = A[1];
1379 }
1380 }else{ /* block==2*/
1381 B = s->motion_val[xy - wrap];
1382 C = s->motion_val[xy + off[block] - wrap];
1383 if(s->mb_x == s->resync_mb_x) //rare
1384 A[0]=A[1]=0;
1385
1386 *px = mid_pred(A[0], B[0], C[0]);
1387 *py = mid_pred(A[1], B[1], C[1]);
1388 }
1389 } else {
1390 B = s->motion_val[xy - wrap];
1391 C = s->motion_val[xy + off[block] - wrap];
1392 *px = mid_pred(A[0], B[0], C[0]);
1393 *py = mid_pred(A[1], B[1], C[1]);
1394 }
1395 return mot_val;
1396 }
1397
1398 #ifdef CONFIG_ENCODERS
1399 static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
1400 {
1401 int range, l, bit_size, sign, code, bits;
1402
1403 if (val == 0) {
1404 /* zero vector */
1405 code = 0;
1406 put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1407 } else {
1408 bit_size = f_code - 1;
1409 range = 1 << bit_size;
1410 /* modulo encoding */
1411 l = range * 32;
1412 #if 1
1413 val+= l;
1414 val&= 2*l-1;
1415 val-= l;
1416 sign = val>>31;
1417 val= (val^sign)-sign;
1418 sign&=1;
1419 #else
1420 if (val < -l) {
1421 val += 2*l;
1422 } else if (val >= l) {
1423 val -= 2*l;
1424 }
1425
1426 assert(val>=-l && val<l);
1427
1428 if (val >= 0) {
1429 sign = 0;
1430 } else {
1431 val = -val;
1432 sign = 1;
1433 }
1434 #endif
1435 val--;
1436 code = (val >> bit_size) + 1;
1437 bits = val & (range - 1);
1438
1439 put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign);
1440 if (bit_size > 0) {
1441 put_bits(&s->pb, bit_size, bits);
1442 }
1443 }
1444
1445 }
1446
1447 /* Encode MV differences on H.263+ with Unrestricted MV mode */
1448 static void h263p_encode_umotion(MpegEncContext * s, int val)
1449 {
1450 short sval = 0;
1451 short i = 0;
1452 short n_bits = 0;
1453 short temp_val;
1454 int code = 0;
1455 int tcode;
1456
1457 if ( val == 0)
1458 put_bits(&s->pb, 1, 1);
1459 else if (val == 1)
1460 put_bits(&s->pb, 3, 0);
1461 else if (val == -1)
1462 put_bits(&s->pb, 3, 2);
1463 else {
1464
1465 sval = ((val < 0) ? (short)(-val):(short)val);
1466 temp_val = sval;
1467
1468 while (temp_val != 0) {
1469 temp_val = temp_val >> 1;
1470 n_bits++;
1471 }
1472
1473 i = n_bits - 1;
1474 while (i > 0) {
1475 tcode = (sval & (1 << (i-1))) >> (i-1);
1476 tcode = (tcode << 1) | 1;
1477 code = (code << 2) | tcode;
1478 i--;
1479 }
1480 code = ((code << 1) | (val < 0)) << 1;
1481 put_bits(&s->pb, (2*n_bits)+1, code);
1482 //printf("\nVal = %d\tCode = %d", sval, code);
1483 }
1484 }
1485
1486 static void init_mv_penalty_and_fcode(MpegEncContext *s)
1487 {
1488 int f_code;
1489 int mv;
1490
1491 if(mv_penalty==NULL)
1492 mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1493
1494 for(f_code=1; f_code<=MAX_FCODE; f_code++){
1495 for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1496 int len;
1497
1498 if(mv==0) len= mvtab[0][1];
1499 else{
1500 int val, bit_size, range, code;
1501
1502 bit_size = s->f_code - 1;
1503 range = 1 << bit_size;
1504
1505 val=mv;
1506 if (val < 0)
1507 val = -val;
1508 val--;
1509 code = (val >> bit_size) + 1;
1510 if(code<33){
1511 len= mvtab[code][1] + 1 + bit_size;
1512 }else{
1513 len= mvtab[32][1] + 2 + bit_size;
1514 }
1515 }
1516
1517 mv_penalty[f_code][mv+MAX_MV]= len;
1518 }
1519 }
1520
1521 for(f_code=MAX_FCODE; f_code>0; f_code--){
1522 for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1523 fcode_tab[mv+MAX_MV]= f_code;
1524 }
1525 }
1526
1527 for(mv=0; mv<MAX_MV*2+1; mv++){
1528 umv_fcode_tab[mv]= 1;
1529 }
1530 }
1531 #endif
1532
1533 #ifdef CONFIG_ENCODERS
1534
1535 static void init_uni_dc_tab(void)
1536 {
1537 int level, uni_code, uni_len;
1538
1539 for(level=-256; level<256; level++){
1540 int size, v, l;
1541 /* find number of bits */
1542 size = 0;
1543 v = abs(level);
1544 while (v) {
1545 v >>= 1;
1546 size++;
1547 }
1548
1549 if (level < 0)
1550 l= (-level) ^ ((1 << size) - 1);
1551 else
1552 l= level;
1553
1554 /* luminance */
1555 uni_code= DCtab_lum[size][0];
1556 uni_len = DCtab_lum[size][1];
1557
1558 if (size > 0) {
1559 uni_code<<=size; uni_code|=l;
1560 uni_len+=size;
1561 if (size > 8){
1562 uni_code<<=1; uni_code|=1;
1563 uni_len++;
1564 }
1565 }
1566 uni_DCtab_lum_bits[level+256]= uni_code;
1567 uni_DCtab_lum_len [level+256]= uni_len;
1568
1569 /* chrominance */
1570 uni_code= DCtab_chrom[size][0];
1571 uni_len = DCtab_chrom[size][1];
1572
1573 if (size > 0) {
1574 uni_code<<=size; uni_code|=l;
1575 uni_len+=size;
1576 if (size > 8){
1577 uni_code<<=1; uni_code|=1;
1578 uni_len++;
1579 }
1580 }
1581 uni_DCtab_chrom_bits[level+256]= uni_code;
1582 uni_DCtab_chrom_len [level+256]= uni_len;
1583
1584 }
1585 }
1586
1587 #endif //CONFIG_ENCODERS
1588
1589 #ifdef CONFIG_ENCODERS
1590 static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1591 int slevel, run, last;
1592
1593 assert(MAX_LEVEL >= 64);
1594 assert(MAX_RUN >= 63);
1595
1596 for(slevel=-64; slevel<64; slevel++){
1597 if(slevel==0) continue;
1598 for(run=0; run<64; run++){
1599 for(last=0; last<=1; last++){
1600 const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1601 int level= slevel < 0 ? -slevel : slevel;
1602 int sign= slevel < 0 ? 1 : 0;
1603 int bits, len, code;
1604 int level1, run1;
1605
1606 len_tab[index]= 100;
1607
1608 /* ESC0 */
1609 code= get_rl_index(rl, last, run, level);
1610 bits= rl->table_vlc[code][0];
1611 len= rl->table_vlc[code][1];
1612 bits=bits*2+sign; len++;
1613
1614 if(code!=rl->n && len < len_tab[index]){
1615 bits_tab[index]= bits;
1616 len_tab [index]= len;
1617 }
1618 #if 1
1619 /* ESC1 */
1620 bits= rl->table_vlc[rl->n][0];
1621 len= rl->table_vlc[rl->n][1];
1622 bits=bits*2; len++; //esc1
1623 level1= level - rl->max_level[last][run];
1624 if(level1>0){
1625 code= get_rl_index(rl, last, run, level1);
1626 bits<<= rl->table_vlc[code][1];
1627 len += rl->table_vlc[code][1];
1628 bits += rl->table_vlc[code][0];
1629 bits=bits*2+sign; len++;
1630
1631 if(code!=rl->n && len < len_tab[index]){
1632 bits_tab[index]= bits;
1633 len_tab [index]= len;
1634 }
1635 }
1636 #endif
1637 #if 1
1638 /* ESC2 */
1639 bits= rl->table_vlc[rl->n][0];
1640 len= rl->table_vlc[rl->n][1];
1641 bits=bits*4+2; len+=2; //esc2
1642 run1 = run - rl->max_run[last][level] - 1;
1643 if(run1>=0){
1644 code= get_rl_index(rl, last, run1, level);
1645 bits<<= rl->table_vlc[code][1];
1646 len += rl->table_vlc[code][1];
1647 bits += rl->table_vlc[code][0];
1648 bits=bits*2+sign; len++;
1649
1650 if(code!=rl->n && len < len_tab[index]){
1651 bits_tab[index]= bits;
1652 len_tab [index]= len;
1653 }
1654 }
1655 #endif
1656 /* ESC3 */
1657 bits= rl->table_vlc[rl->n][0];
1658 len = rl->table_vlc[rl->n][1];
1659 bits=bits*4+3; len+=2; //esc3
1660 bits=bits*2+last; len++;
1661 bits=bits*64+run; len+=6;
1662 bits=bits*2+1; len++; //marker
1663 bits=bits*4096+(slevel&0xfff); len+=12;
1664 bits=bits*2+1; len++; //marker
1665
1666 if(len < len_tab[index]){
1667 bits_tab[index]= bits;
1668 len_tab [index]= len;
1669 }
1670 }
1671 }
1672 }
1673 }
1674
1675 void h263_encode_init(MpegEncContext *s)
1676 {
1677 static int done = 0;
1678
1679 if (!done) {
1680 done = 1;
1681
1682 init_uni_dc_tab();
1683
1684 init_rl(&rl_inter);
1685 init_rl(&rl_intra);
1686 init_rl(&rl_intra_aic);
1687
1688 init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1689 init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1690
1691 init_mv_penalty_and_fcode(s);
1692 }
1693 s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
1694
1695 // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
1696 switch(s->codec_id){
1697 case CODEC_ID_MPEG4:
1698 s->fcode_tab= fcode_tab;
1699 s->min_qcoeff= -2048;
1700 s->max_qcoeff= 2047;
1701 s->intra_ac_vlc_length = uni_mpeg4_intra_rl_len;
1702 s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;
1703 s->inter_ac_vlc_length = uni_mpeg4_inter_rl_len;
1704 s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;
1705 s->luma_dc_vlc_length= uni_DCtab_lum_len;
1706 s->chroma_dc_vlc_length= uni_DCtab_chrom_len;
1707 s->ac_esc_length= 7+2+1+6+1+12+1;
1708
1709 if(s->flags & CODEC_FLAG_GLOBAL_HEADER){
1710
1711 s->avctx->extradata= av_malloc(1024);
1712 init_put_bits(&s->pb, s->avctx->extradata, 1024);
1713
1714 mpeg4_encode_visual_object_header(s);
1715 mpeg4_encode_vol_header(s, 0, 0);
1716
1717 // ff_mpeg4_stuffing(&s->pb); ?
1718 flush_put_bits(&s->pb);
1719 s->avctx->extradata_size= (get_bit_count(&s->pb)+7)>>3;
1720 }
1721
1722 break;
1723 case CODEC_ID_H263P:
1724 s->fcode_tab= umv_fcode_tab;
1725 s->min_qcoeff= -127;
1726 s->max_qcoeff= 127;
1727 break;
1728 //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later
1729 case CODEC_ID_FLV1:
1730 if (s->h263_flv > 1) {
1731 s->min_qcoeff= -1023;
1732 s->max_qcoeff= 1023;
1733 } else {
1734 s->min_qcoeff= -127;
1735 s->max_qcoeff= 127;
1736 }
1737 s->y_dc_scale_table=
1738 s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1739 break;
1740 default: //nothing needed default table allready set in mpegvideo.c
1741 s->min_qcoeff= -127;
1742 s->max_qcoeff= 127;
1743 s->y_dc_scale_table=
1744 s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1745 }
1746 }
1747
1748 /**
1749 * encodes a 8x8 block.
1750 * @param block the 8x8 block
1751 * @param n block index (0-3 are luma, 4-5 are chroma)
1752 */
1753 static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
1754 {
1755 int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
1756 RLTable *rl;
1757
1758 rl = &rl_inter;
1759 if (s->mb_intra && !s->h263_aic) {
1760 /* DC coef */
1761 level = block[0];
1762 /* 255 cannot be represented, so we clamp */
1763 if (level > 254) {
1764 level = 254;
1765 block[0] = 254;
1766 }
1767 /* 0 cannot be represented also */
1768 else if (level < 1) {
1769 level = 1;
1770 block[0] = 1;
1771 }
1772 if (level == 128) //FIXME check rv10
1773 put_bits(&s->pb, 8, 0xff);
1774 else
1775 put_bits(&s->pb, 8, level & 0xff);
1776 i = 1;
1777 } else {
1778 i = 0;
1779 if (s->h263_aic && s->mb_intra)
1780 rl = &rl_intra_aic;
1781 }
1782
1783 /* AC coefs */
1784 last_index = s->block_last_index[n];
1785 last_non_zero = i - 1;
1786 for (; i <= last_index; i++) {
1787 j = s->intra_scantable.permutated[i];
1788 level = block[j];
1789 if (level) {
1790 run = i - last_non_zero - 1;
1791 last = (i == last_index);
1792 sign = 0;
1793 slevel = level;
1794 if (level < 0) {
1795 sign = 1;
1796 level = -level;
1797 }
1798 code = get_rl_index(rl, last, run, level);
1799 put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1800 if (code == rl->n) {
1801 if(s->h263_flv <= 1){
1802 put_bits(&s->pb, 1, last);
1803 put_bits(&s->pb, 6, run);
1804
1805 assert(slevel != 0);
1806
1807 if(slevel < 128 && slevel > -128)
1808 put_bits(&s->pb, 8, slevel & 0xff);
1809 else{
1810 put_bits(&s->pb, 8, 128);
1811 put_bits(&s->pb, 5, slevel & 0x1f);
1812 put_bits(&s->pb, 6, (slevel>>5)&0x3f);
1813 }
1814 }else{
1815 if(slevel < 64 && slevel > -64) {
1816 /* 7-bit level */
1817 put_bits(&s->pb, 1, 0);
1818 put_bits(&s->pb, 1, last);
1819 put_bits(&s->pb, 6, run);
1820
1821 put_bits(&s->pb, 7, slevel & 0x7f);
1822 } else {
1823 /* 11-bit level */
1824 put_bits(&s->pb, 1, 1);
1825 put_bits(&s->pb, 1, last);
1826 put_bits(&s->pb, 6, run);
1827
1828 put_bits(&s->pb, 11, slevel & 0x7ff);
1829 }
1830 }
1831 } else {
1832 put_bits(&s->pb, 1, sign);
1833 }
1834 last_non_zero = i;
1835 }
1836 }
1837 }
1838 #endif
1839
1840 #ifdef CONFIG_ENCODERS
1841
1842 /***************************************************/
1843 /**
1844 * add mpeg4 stuffing bits (01...1)
1845 */
1846 void ff_mpeg4_stuffing(PutBitContext * pbc)
1847 {
1848 int length;
1849 put_bits(pbc, 1, 0);
1850 length= (-get_bit_count(pbc))&7;
1851 if(length) put_bits(pbc, length, (1<<length)-1);
1852 }
1853
1854 /* must be called before writing the header */
1855 void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
1856 int time_div, time_mod;
1857
1858 if(s->current_picture.pts)
1859 s->time= (s->current_picture.pts*s->time_increment_resolution + 500*1000)/(1000*1000);
1860 else
1861 s->time= av_rescale(picture_number*(int64_t)s->avctx->frame_rate_base, s->time_increment_resolution, s->avctx->frame_rate);
1862 time_div= s->time/s->time_increment_resolution;
1863 time_mod= s->time%s->time_increment_resolution;
1864
1865 if(s->pict_type==B_TYPE){
1866 s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
1867 }else{
1868 s->last_time_base= s->time_base;
1869 s->time_base= time_div;
1870 s->pp_time= s->time - s->last_non_b_time;
1871 s->last_non_b_time= s->time;
1872 }
1873 }
1874
1875 static void mpeg4_encode_gop_header(MpegEncContext * s){
1876 int hours, minutes, seconds;
1877
1878 put_bits(&s->pb, 16, 0);
1879 put_bits(&s->pb, 16, GOP_STARTCODE);
1880
1881 seconds= s->time/s->time_increment_resolution;
1882 minutes= seconds/60; seconds %= 60;
1883 hours= minutes/60; minutes %= 60;
1884 hours%=24;
1885
1886 put_bits(&s->pb, 5, hours);
1887 put_bits(&s->pb, 6, minutes);
1888 put_bits(&s->pb, 1, 1);
1889 put_bits(&s->pb, 6, seconds);
1890
1891 put_bits(&s->pb, 1, 0); //closed gov == NO
1892 put_bits(&s->pb, 1, 0); //broken link == NO
1893
1894 ff_mpeg4_stuffing(&s->pb);
1895 }
1896
1897 static void mpeg4_encode_visual_object_header(MpegEncContext * s){
1898 int profile_and_level_indication;
1899 int vo_ver_id;
1900
1901 if(s->max_b_frames || s->quarter_sample){
1902 profile_and_level_indication= 0xF1; // adv simple level 1
1903 vo_ver_id= 5;
1904 }else{
1905 profile_and_level_indication= 0x01; // simple level 1
1906 vo_ver_id= 1;
1907 }
1908 //FIXME levels
1909
1910 put_bits(&s->pb, 16, 0);
1911 put_bits(&s->pb, 16, VOS_STARTCODE);
1912
1913 put_bits(&s->pb, 8, profile_and_level_indication);
1914
1915 put_bits(&s->pb, 16, 0);
1916 put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
1917
1918 put_bits(&s->pb, 1, 1);
1919 put_bits(&s->pb, 4, vo_ver_id);
1920 put_bits(&s->pb, 3, 1); //priority
1921
1922 put_bits(&s->pb, 4, 1); //visual obj type== video obj
1923
1924 put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
1925
1926 ff_mpeg4_stuffing(&s->pb);
1927 }
1928
1929 static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
1930 {
1931 int vo_ver_id;
1932
1933 if(s->max_b_frames || s->quarter_sample){
1934 vo_ver_id= 5;
1935 s->vo_type= ADV_SIMPLE_VO_TYPE;
1936 }else{
1937 vo_ver_id= 1;
1938 s->vo_type= SIMPLE_VO_TYPE;
1939 }
1940
1941 put_bits(&s->pb, 16, 0);
1942 put_bits(&s->pb, 16, 0x100 + vo_number); /* video obj */
1943 put_bits(&s->pb, 16, 0);
1944 put_bits(&s->pb, 16, 0x120 + vol_number); /* video obj layer */
1945
1946 put_bits(&s->pb, 1, 0); /* random access vol */
1947 put_bits(&s->pb, 8, s->vo_type); /* video obj type indication */
1948 put_bits(&s->pb, 1, 1); /* is obj layer id= yes */
1949 put_bits(&s->pb, 4, vo_ver_id); /* is obj layer ver id */
1950 put_bits(&s->pb, 3, 1); /* is obj layer priority */
1951
1952 float_aspect_to_info(s, s->avctx->aspect_ratio);
1953
1954 put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
1955 if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
1956 {
1957 put_bits(&s->pb, 8, s->aspected_width);
1958 put_bits(&s->pb, 8, s->aspected_height);
1959 }
1960
1961 if(s->low_delay){
1962 put_bits(&s->pb, 1, 1); /* vol control parameters= yes */
1963 put_bits(&s->pb, 2, 1); /* chroma format YUV 420/YV12 */
1964 put_bits(&s->pb, 1, s->low_delay);
1965 put_bits(&s->pb, 1, 0); /* vbv parameters= no */
1966 }else{
1967 put_bits(&s->pb, 1, 0); /* vol control parameters= no */
1968 }
1969
1970 put_bits(&s->pb, 2, RECT_SHAPE); /* vol shape= rectangle */
1971 put_bits(&s->pb, 1, 1); /* marker bit */
1972
1973 put_bits(&s->pb, 16, s->time_increment_resolution);
1974 if (s->time_increment_bits < 1)
1975 s->time_increment_bits = 1;
1976 put_bits(&s->pb, 1, 1); /* marker bit */
1977 put_bits(&s->pb, 1, 0); /* fixed vop rate=no */
1978 put_bits(&s->pb, 1, 1); /* marker bit */
1979 put_bits(&s->pb, 13, s->width); /* vol width */
1980 put_bits(&s->pb, 1, 1); /* marker bit */
1981 put_bits(&s->pb, 13, s->height); /* vol height */
1982 put_bits(&s->pb, 1, 1); /* marker bit */
1983 put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1984 put_bits(&s->pb, 1, 1); /* obmc disable */
1985 if (vo_ver_id == 1) {
1986 put_bits(&s->pb, 1, s->vol_sprite_usage=0); /* sprite enable */
1987 }else{
1988 put_bits(&s->pb, 2, s->vol_sprite_usage=0); /* sprite enable */
1989 }
1990
1991 s->quant_precision=5;
1992 put_bits(&s->pb, 1, 0); /* not 8 bit == false */
1993 put_bits(&s->pb, 1, s->mpeg_quant); /* quant type= (0=h263 style)*/
1994
1995 if(s->mpeg_quant){
1996 ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
1997 ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
1998 }
1999
2000 if (vo_ver_id != 1)
2001 put_bits(&s->pb, 1, s->quarter_sample);
2002 put_bits(&s->pb, 1, 1); /* complexity estimation disable */
2003 s->resync_marker= s->rtp_mode;
2004 put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
2005 put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
2006 if(s->data_partitioning){
2007 put_bits(&s->pb, 1, 0); /* no rvlc */
2008 }
2009
2010 if (vo_ver_id != 1){
2011 put_bits(&s->pb, 1, 0); /* newpred */
2012 put_bits(&s->pb, 1, 0); /* reduced res vop */
2013 }
2014 put_bits(&s->pb, 1, 0); /* scalability */
2015
2016 ff_mpeg4_stuffing(&s->pb);
2017
2018 /* user data */
2019 if(!(s->flags & CODEC_FLAG_BITEXACT)){
2020 put_bits(&s->pb, 16, 0);
2021 put_bits(&s->pb, 16, 0x1B2); /* user_data */
2022 put_string(&s->pb, LIBAVCODEC_IDENT);
2023 ff_mpeg4_stuffing(&s->pb);
2024 }
2025 }
2026
2027 /* write mpeg4 VOP header */
2028 void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
2029 {
2030 int time_incr;
2031 int time_div, time_mod;
2032
2033 if(s->pict_type==I_TYPE){
2034 if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
2035 if(s->strict_std_compliance < 2) //HACK, the reference sw is buggy
2036 mpeg4_encode_visual_object_header(s);
2037 if(s->strict_std_compliance < 2 || picture_number==0) //HACK, the reference sw is buggy
2038 mpeg4_encode_vol_header(s, 0, 0);
2039 }
2040 mpeg4_encode_gop_header(s);
2041 }
2042
2043 s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
2044
2045 //printf("num:%d rate:%d base:%d\n", s->picture_number, s->frame_rate, FRAME_RATE_BASE);
2046
2047 put_bits(&s->pb, 16, 0); /* vop header */
2048 put_bits(&s->pb, 16, VOP_STARTCODE); /* vop header */
2049 put_bits(&s->pb, 2, s->pict_type - 1); /* pict type: I = 0 , P = 1 */
2050
2051 time_div= s->time/s->time_increment_resolution;
2052 time_mod= s->time%s->time_increment_resolution;
2053 time_incr= time_div - s->last_time_base;
2054 while(time_incr--)
2055 put_bits(&s->pb, 1, 1);
2056
2057 put_bits(&s->pb, 1, 0);
2058
2059 put_bits(&s->pb, 1, 1); /* marker */
2060 put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
2061 put_bits(&s->pb, 1, 1); /* marker */
2062 put_bits(&s->pb, 1, 1); /* vop coded */
2063 if ( s->pict_type == P_TYPE
2064 || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
2065 put_bits(&s->pb, 1, s->no_rounding); /* rounding type */
2066 }
2067 put_bits(&s->pb, 3, 0); /* intra dc VLC threshold */
2068 if(!s->progressive_sequence){
2069 put_bits(&s->pb, 1, s->top_field_first);
2070 put_bits(&s->pb, 1, s->alternate_scan);
2071 }
2072 //FIXME sprite stuff
2073
2074 put_bits(&s->pb, 5, s->qscale);
2075
2076 if (s->pict_type != I_TYPE)
2077 put_bits(&s->pb, 3, s->f_code); /* fcode_for */
2078 if (s->pict_type == B_TYPE)
2079 put_bits(&s->pb, 3, s->b_code); /* fcode_back */
2080 // printf("****frame %d\n", picture_number);
2081
2082 s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support
2083 s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
2084 }
2085
2086 #endif //CONFIG_ENCODERS
2087
2088 /**
2089 * change qscale by given dquant and update qscale dependant variables.
2090 */
2091 static void change_qscale(MpegEncContext * s, int dquant)
2092 {
2093 s->qscale += dquant;
2094
2095 if (s->qscale < 1)
2096 s->qscale = 1;
2097 else if (s->qscale > 31)
2098 s->qscale = 31;
2099
2100 s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
2101 s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
2102 }
2103
2104 /**
2105 * predicts the dc.
2106 * @param n block index (0-3 are luma, 4-5 are chroma)
2107 * @param dc_val_ptr a pointer to the dc_val entry for the current MB will be stored here
2108 * @param dir_ptr pointer to an integer where the prediction direction will be stored
2109 * @return the quantized predicted dc
2110 */
2111 static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr)
2112 {
2113 int a, b, c, wrap, pred, scale;
2114 uint16_t *dc_val;
2115
2116 /* find prediction */
2117 if (n < 4) {
2118 scale = s->y_dc_scale;
2119 } else {
2120 scale = s->c_dc_scale;
2121 }
2122 if(IS_3IV1)
2123 scale= 8;
2124
2125 wrap= s->block_wrap[n];
2126 dc_val = s->dc_val[0] + s->block_index[n];
2127
2128 /* B C
2129 * A X
2130 */
2131 a = dc_val[ - 1];
2132 b = dc_val[ - 1 - wrap];
2133 c = dc_val[ - wrap];
2134
2135 /* outside slice handling (we cant do that by memset as we need the dc for error resilience) */
2136 if(s->first_slice_line && n!=3){
2137 if(n!=2) b=c= 1024;
2138 if(n!=1 && s->mb_x == s->resync_mb_x) b=a= 1024;
2139 }
2140 if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1){
2141 if(n==0 || n==4 || n==5)
2142 b=1024;
2143 }
2144
2145 if (abs(a - b) < abs(b - c)) {
2146 pred = c;
2147 *dir_ptr = 1; /* top */
2148 } else {
2149 pred = a;
2150 *dir_ptr = 0; /* left */
2151 }
2152 /* we assume pred is positive */
2153 pred = FASTDIV((pred + (scale >> 1)), scale);
2154
2155 /* prepare address for prediction update */
2156 *dc_val_ptr = &dc_val[0];
2157
2158 return pred;
2159 }
2160
2161 /**
2162 * predicts the ac.
2163 * @param n block index (0-3 are luma, 4-5 are chroma)
2164 * @param dir the ac prediction direction
2165 */
2166 void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
2167 int dir)
2168 {
2169 int i;
2170 int16_t *ac_val, *ac_val1;
2171 int8_t * const qscale_table= s->current_picture.qscale_table;
2172
2173 /* find prediction */
2174 ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
2175 ac_val1 = ac_val;
2176 if (s->ac_pred) {
2177 if (dir == 0) {
2178 const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
2179 /* left prediction */
2180 ac_val -= 16;
2181
2182 if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
2183 /* same qscale */
2184 for(i=1;i<8;i++) {
2185 block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
2186 }
2187 }else{
2188 /* different qscale, we must rescale */
2189 for(i=1;i<8;i++) {
2190 block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
2191 }
2192 }
2193 } else {
2194 const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
2195 /* top prediction */
2196 ac_val -= 16 * s->block_wrap[n];
2197
2198 if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
2199 /* same qscale */
2200 for(i=1;i<8;i++) {
2201 block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
2202 }
2203 }else{
2204 /* different qscale, we must rescale */
2205 for(i=1;i<8;i++) {
2206 block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
2207 }
2208 }
2209 }
2210 }
2211 /* left copy */
2212 for(i=1;i<8;i++)
2213 ac_val1[i ] = block[s->dsp.idct_permutation[i<<3]];
2214
2215 /* top copy */
2216 for(i=1;i<8;i++)
2217 ac_val1[8 + i] = block[s->dsp.idct_permutation[i ]];
2218
2219 }
2220
2221 #ifdef CONFIG_ENCODERS
2222
2223 /**
2224 * encodes the dc value.
2225 * @param n block index (0-3 are luma, 4-5 are chroma)
2226 */
2227 static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
2228 {
2229 #if 1
2230 // if(level<-255 || level>255) printf("dc overflow\n");
2231 level+=256;
2232 if (n < 4) {
2233 /* luminance */
2234 put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
2235 } else {
2236 /* chrominance */
2237 put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
2238 }
2239 #else
2240 int size, v;
2241 /* find number of bits */
2242 size = 0;
2243 v = abs(level);
2244 while (v) {
2245 v >>= 1;
2246 size++;
2247 }
2248
2249 if (n < 4) {
2250 /* luminance */
2251 put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
2252 } else {
2253 /* chrominance */
2254 put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
2255 }
2256
2257 /* encode remaining bits */
2258 if (size > 0) {
2259 if (level < 0)
2260 level = (-level) ^ ((1 << size) - 1);
2261 put_bits(&s->pb, size, level);
2262 if (size > 8)
2263 put_bits(&s->pb, 1, 1);
2264 }
2265 #endif
2266 }
2267
2268 /**
2269 * encodes a 8x8 block
2270 * @param n block index (0-3 are luma, 4-5 are chroma)
2271 */
2272 static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc,
2273 uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
2274 {
2275 int i, last_non_zero;
2276 #if 0 //variables for the outcommented version
2277 int code, sign, last;
2278 #endif
2279 const RLTable *rl;
2280 uint32_t *bits_tab;
2281 uint8_t *len_tab;
2282 const int last_index = s->block_last_index[n];
2283
2284 if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2285 /* mpeg4 based DC predictor */
2286 mpeg4_encode_dc(dc_pb, intra_dc, n);
2287 if(last_index<1) return;
2288 i = 1;
2289 rl = &rl_intra;
2290 bits_tab= uni_mpeg4_intra_rl_bits;
2291 len_tab = uni_mpeg4_intra_rl_len;
2292 } else {
2293 if(last_index<0) return;
2294 i = 0;
2295 rl = &rl_inter;
2296 bits_tab= uni_mpeg4_inter_rl_bits;
2297 len_tab = uni_mpeg4_inter_rl_len;
2298 }
2299
2300 /* AC coefs */
2301 last_non_zero = i - 1;
2302 #if 1
2303 for (; i < last_index; i++) {
2304 int level = block[ scan_table[i] ];
2305 if (level) {
2306 int run = i - last_non_zero - 1;
2307 level+=64;
2308 if((level&(~127)) == 0){
2309 const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2310 put_bits(ac_pb, len_tab[index], bits_tab[index]);
2311 }else{ //ESC3
2312 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);
2313 }
2314 last_non_zero = i;
2315 }
2316 }
2317 /*if(i<=last_index)*/{
2318 int level = block[ scan_table[i] ];
2319 int run = i - last_non_zero - 1;
2320 level+=64;
2321 if((level&(~127)) == 0){
2322 const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2323 put_bits(ac_pb, len_tab[index], bits_tab[index]);
2324 }else{ //ESC3
2325 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);
2326 }
2327 }
2328 #else
2329 for (; i <= last_index; i++) {
2330 const int slevel = block[ scan_table[i] ];
2331 if (slevel) {
2332 int level;
2333 int run = i - last_non_zero - 1;
2334 last = (i == last_index);
2335 sign = 0;
2336 level = slevel;
2337 if (level < 0) {
2338 sign = 1;
2339 level = -level;
2340 }
2341 code = get_rl_index(rl, last, run, level);
2342 put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2343 if (code == rl->n) {
2344 int level1, run1;
2345 level1 = level - rl->max_level[last][run];
2346 if (level1 < 1)
2347 goto esc2;
2348 code = get_rl_index(rl, last, run, level1);
2349 if (code == rl->n) {
2350 esc2:
2351 put_bits(ac_pb, 1, 1);
2352 if (level > MAX_LEVEL)
2353 goto esc3;
2354 run1 = run - rl->max_run[last][level] - 1;
2355 if (run1 < 0)
2356 goto esc3;
2357 code = get_rl_index(rl, last, run1, level);
2358 if (code == rl->n) {
2359 esc3:
2360 /* third escape */
2361 put_bits(ac_pb, 1, 1);
2362 put_bits(ac_pb, 1, last);
2363 put_bits(ac_pb, 6, run);
2364 put_bits(ac_pb, 1, 1);
2365 put_bits(ac_pb, 12, slevel & 0xfff);
2366 put_bits(ac_pb, 1, 1);
2367 } else {
2368 /* second escape */
2369 put_bits(ac_pb, 1, 0);
2370 put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2371 put_bits(ac_pb, 1, sign);
2372 }
2373 } else {
2374 /* first escape */
2375 put_bits(ac_pb, 1, 0);
2376 put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2377 put_bits(ac_pb, 1, sign);
2378 }
2379 } else {
2380 put_bits(ac_pb, 1, sign);
2381 }
2382 last_non_zero = i;
2383 }
2384 }
2385 #endif
2386 }
2387
2388 static inline int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc,
2389 uint8_t *scan_table)
2390 {
2391 int i, last_non_zero;
2392 const RLTable *rl;
2393 uint8_t *len_tab;
2394 const int last_index = s->block_last_index[n];
2395 int len=0;
2396
2397 if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2398 /* mpeg4 based DC predictor */
2399 //mpeg4_encode_dc(dc_pb, intra_dc, n); //FIXME
2400 if(last_index<1) return len;
2401 i = 1;
2402 rl = &rl_intra;
2403 len_tab = uni_mpeg4_intra_rl_len;
2404 } else {
2405 if(last_index<0) return 0;
2406 i = 0;
2407 rl = &rl_inter;
2408 len_tab = uni_mpeg4_inter_rl_len;
2409 }
2410
2411 /* AC coefs */
2412 last_non_zero = i - 1;
2413 for (; i < last_index; i++) {
2414 int level = block[ scan_table[i] ];
2415 if (level) {
2416 int run = i - last_non_zero - 1;
2417 level+=64;
2418 if((level&(~127)) == 0){
2419 const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2420 len += len_tab[index];
2421 }else{ //ESC3
2422 len += 7+2+1+6+1+12+1;
2423 }
2424 last_non_zero = i;
2425 }
2426 }
2427 /*if(i<=last_index)*/{
2428 int level = block[ scan_table[i] ];
2429 int run = i - last_non_zero - 1;
2430 level+=64;
2431 if((level&(~127)) == 0){
2432 const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2433 len += len_tab[index];
2434 }else{ //ESC3
2435 len += 7+2+1+6+1+12+1;
2436 }
2437 }
2438
2439 return len;
2440 }
2441
2442 #endif
2443
2444
2445 /***********************************************/
2446 /* decoding */
2447
2448 static VLC intra_MCBPC_vlc;
2449 static VLC inter_MCBPC_vlc;
2450 static VLC cbpy_vlc;
2451 static VLC mv_vlc;
2452 static VLC dc_lum, dc_chrom;
2453 static VLC sprite_trajectory;
2454 static VLC mb_type_b_vlc;
2455
2456 void init_vlc_rl(RLTable *rl)
2457 {
2458 int i, q;
2459
2460 init_vlc(&rl->vlc, 9, rl->n + 1,
2461 &rl->table_vlc[0][1], 4, 2,
2462 &rl->table_vlc[0][0], 4, 2);
2463
2464
2465 for(q=0; q<32; q++){
2466 int qmul= q*2;
2467 int qadd= (q-1)|1;
2468
2469 if(q==0){
2470 qmul=1;
2471 qadd=0;
2472 }
2473
2474 rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2475 for(i=0; i<rl->vlc.table_size; i++){
2476 int code= rl->vlc.table[i][0];
2477 int len = rl->vlc.table[i][1];
2478 int level, run;
2479
2480 if(len==0){ // illegal code
2481 run= 66;
2482 level= MAX_LEVEL;
2483 }else if(len<0){ //more bits needed
2484 run= 0;
2485 level= code;
2486 }else{
2487 if(code==rl->n){ //esc
2488 run= 66;
2489 level= 0;
2490 }else{
2491 run= rl->table_run [code] + 1;
2492 level= rl->table_level[code] * qmul + qadd;
2493 if(code >= rl->last) run+=192;
2494 }
2495 }
2496 rl->rl_vlc[q][i].len= len;
2497 rl->rl_vlc[q][i].level= level;
2498 rl->rl_vlc[q][i].run= run;
2499 }
2500 }
2501 }
2502
2503 /* init vlcs */
2504
2505 /* XXX: find a better solution to handle static init */
2506 void h263_decode_init_vlc(MpegEncContext *s)
2507 {
2508 static int done = 0;
2509
2510 if (!done) {
2511 done = 1;
2512
2513 init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 9,
2514 intra_MCBPC_bits, 1, 1,
2515 intra_MCBPC_code, 1, 1);
2516 init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 28,
2517 inter_MCBPC_bits, 1, 1,
2518 inter_MCBPC_code, 1, 1);
2519 init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,
2520 &cbpy_tab[0][1], 2, 1,
2521 &cbpy_tab[0][0], 2, 1);
2522 init_vlc(&mv_vlc, MV_VLC_BITS, 33,
2523 &mvtab[0][1], 2, 1,
2524 &mvtab[0][0], 2, 1);
2525 init_rl(&rl_inter);
2526 init_rl(&rl_intra);
2527 init_rl(&rvlc_rl_inter);
2528 init_rl(&rvlc_rl_intra);
2529 init_rl(&rl_intra_aic);
2530 init_vlc_rl(&rl_inter);
2531 init_vlc_rl(&rl_intra);
2532 init_vlc_rl(&rvlc_rl_inter);
2533 init_vlc_rl(&rvlc_rl_intra);
2534 init_vlc_rl(&rl_intra_aic);
2535 init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2536 &DCtab_lum[0][1], 2, 1,
2537 &DCtab_lum[0][0], 2, 1);
2538 init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2539 &DCtab_chrom[0][1], 2, 1,
2540 &DCtab_chrom[0][0], 2, 1);
2541 init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2542 &sprite_trajectory_tab[0][1], 4, 2,
2543 &sprite_trajectory_tab[0][0], 4, 2);
2544 init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2545 &mb_type_b_tab[0][1], 2, 1,
2546 &mb_type_b_tab[0][0], 2, 1);
2547 }
2548 }
2549
2550 /**
2551 * Get the GOB height based on picture height.
2552 */
2553 int ff_h263_get_gob_height(MpegEncContext *s){
2554 if (s->height <= 400)
2555 return 1;
2556 else if (s->height <= 800)
2557 return 2;
2558 else
2559 return 4;
2560 }
2561
2562 /**
2563 * decodes the group of blocks header.
2564 * @return <0 if an error occured
2565 */
2566 static int h263_decode_gob_header(MpegEncContext *s)
2567 {
2568 unsigned int val, gfid;
2569 int left;
2570
2571 /* Check for GOB Start Code */
2572 val = show_bits(&s->gb, 16);
2573 if(val)
2574 return -1;
2575
2576 /* We have a GBSC probably with GSTUFF */
2577 skip_bits(&s->gb, 16); /* Drop the zeros */
2578 left= s->gb.size_in_bits - get_bits_count(&s->gb);
2579 //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2580 for(;left>13; left--){
2581 if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2582 }
2583 if(left<=13)
2584 return -1;
2585
2586 #ifdef DEBUG
2587 fprintf(stderr,"\nGOB Start Code at MB %d\n", (s->mb_y * s->mb_width) + s->mb_x);
2588 #endif
2589 s->gob_number = get_bits(&s->gb, 5); /* GN */
2590 gfid = get_bits(&s->gb, 2); /* GFID */
2591 s->qscale = get_bits(&s->gb, 5); /* GQUANT */
2592 if(s->qscale==0)
2593 return -1;
2594 s->mb_x= 0;
2595 s->mb_y= s->gob_index* s->gob_number;
2596 if(s->mb_y >= s->mb_height)
2597 return -1;
2598 #ifdef DEBUG
2599 fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", s->gob_number, gfid, s->qscale);
2600 #endif
2601 return 0;
2602 }
2603
2604 static inline void memsetw(short *tab, int val, int n)
2605 {
2606 int i;
2607 for(i=0;i<n;i++)
2608 tab[i] = val;
2609 }
2610
2611 #ifdef CONFIG_ENCODERS
2612
2613 void ff_mpeg4_init_partitions(MpegEncContext *s)
2614 {
2615 init_put_bits(&s->tex_pb, s->tex_pb_buffer, PB_BUFFER_SIZE);
2616 init_put_bits(&s->pb2 , s->pb2_buffer , PB_BUFFER_SIZE);
2617 }
2618
2619 void ff_mpeg4_merge_partitions(MpegEncContext *s)
2620 {
2621 const int pb2_len = get_bit_count(&s->pb2 );
2622 const int tex_pb_len= get_bit_count(&s->tex_pb);
2623 const int bits= get_bit_count(&s->pb);
2624
2625 if(s->pict_type==I_TYPE){
2626 put_bits(&s->pb, 19, DC_MARKER);
2627 s->misc_bits+=19 + pb2_len + bits - s->last_bits;
2628 s->i_tex_bits+= tex_pb_len;
2629 }else{
2630 put_bits(&s->pb, 17, MOTION_MARKER);
2631 s->misc_bits+=17 + pb2_len;
2632 s->mv_bits+= bits - s->last_bits;
2633 s->p_tex_bits+= tex_pb_len;
2634 }
2635
2636 flush_put_bits(&s->pb2);
2637 flush_put_bits(&s->tex_pb);
2638
2639 ff_copy_bits(&s->pb, s->pb2_buffer , pb2_len);
2640 ff_copy_bits(&s->pb, s->tex_pb_buffer, tex_pb_len);
2641 s->last_bits= get_bit_count(&s->pb);
2642 }
2643
2644 #endif //CONFIG_ENCODERS
2645
2646 int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
2647 switch(s->pict_type){
2648 case I_TYPE:
2649 return 16;
2650 case P_TYPE:
2651 case S_TYPE:
2652 return s->f_code+15;
2653 case B_TYPE:
2654 return FFMAX(FFMAX(s->f_code, s->b_code)+15, 17);
2655 default:
2656 return -1;
2657 }
2658 }
2659
2660 #ifdef CONFIG_ENCODERS
2661
2662 void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
2663 {
2664 int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2665
2666 ff_mpeg4_stuffing(&s->pb);
2667 put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
2668 put_bits(&s->pb, 1, 1);
2669
2670 put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
2671 put_bits(&s->pb, s->quant_precision, s->qscale);
2672 put_bits(&s->pb, 1, 0); /* no HEC */
2673 }
2674
2675 #endif //CONFIG_ENCODERS
2676
2677 /**
2678 * check if the next stuff is a resync marker or the end.
2679 * @return 0 if not
2680 */
2681 static inline int mpeg4_is_resync(MpegEncContext *s){
2682 const int bits_count= get_bits_count(&s->gb);
2683
2684 if(s->workaround_bugs&FF_BUG_NO_PADDING){
2685 return 0;
2686 }
2687
2688 if(bits_count + 8 >= s->gb.size_in_bits){
2689 int v= show_bits(&s->gb, 8);
2690 v|= 0x7F >> (7-(bits_count&7));
2691
2692 if(v==0x7F)
2693 return 1;
2694 }else{
2695 if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){
2696 int len;
2697 GetBitContext gb= s->gb;
2698
2699 skip_bits(&s->gb, 1);
2700 align_get_bits(&s->gb);
2701
2702 for(len=0; len<32; len++){
2703 if(get_bits1(&s->gb)) break;
2704 }
2705
2706 s->gb= gb;
2707
2708 if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
2709 return 1;
2710 }
2711 }
2712 return 0;
2713 }
2714
2715 /**
2716 * decodes the next video packet.
2717 * @return <0 if something went wrong
2718 */
2719 static int mpeg4_decode_video_packet_header(MpegEncContext *s)
2720 {
2721 int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2722 int header_extension=0, mb_num, len;
2723
2724 /* is there enough space left for a video packet + header */
2725 if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
2726
2727 for(len=0; len<32; len++){
2728 if(get_bits1(&s->gb)) break;
2729 }
2730
2731 if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
2732 printf("marker does not match f_code\n");
2733 return -1;
2734 }
2735
2736 if(s->shape != RECT_SHAPE){
2737 header_extension= get_bits1(&s->gb);
2738 //FIXME more stuff here
2739 }
2740
2741 mb_num= get_bits(&s->gb, mb_num_bits);
2742 if(mb_num>=s->mb_num){
2743 fprintf(stderr, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
2744 return -1;
2745 }
2746 if(s->pict_type == B_TYPE){
2747 while(s->next_picture.mbskip_table[ s->mb_index2xy[ mb_num ] ]) mb_num++;
2748 if(mb_num >= s->mb_num) return -1; // slice contains just skiped MBs which where allready decoded
2749 }
2750
2751 s->mb_x= mb_num % s->mb_width;
2752 s->mb_y= mb_num / s->mb_width;
2753
2754 if(s->shape != BIN_ONLY_SHAPE){
2755 int qscale= get_bits(&s->gb, s->quant_precision);
2756 if(qscale)
2757 s->qscale= qscale;
2758 }
2759
2760 if(s->shape == RECT_SHAPE){
2761 header_extension= get_bits1(&s->gb);
2762 }
2763 if(header_extension){
2764 int time_increment;
2765 int time_incr=0;
2766
2767 while (get_bits1(&s->gb) != 0)
2768 time_incr++;
2769
2770 check_marker(&s->gb, "before time_increment in video packed header");
2771 time_increment= get_bits(&s->gb, s->time_increment_bits);
2772 check_marker(&s->gb, "before vop_coding_type in video packed header");
2773
2774 skip_bits(&s->gb, 2); /* vop coding type */
2775 //FIXME not rect stuff here
2776
2777 if(s->shape != BIN_ONLY_SHAPE){
2778 skip_bits(&s->gb, 3); /* intra dc vlc threshold */
2779 //FIXME dont just ignore everything
2780 if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2781 mpeg4_decode_sprite_trajectory(s);
2782 fprintf(stderr, "untested\n");
2783 }
2784
2785 //FIXME reduced res stuff here
2786
2787 if (s->pict_type != I_TYPE) {
2788 int f_code = get_bits(&s->gb, 3); /* fcode_for */
2789 if(f_code==0){
2790 printf("Error, video packet header damaged (f_code=0)\n");
2791 }
2792 }
2793 if (s->pict_type == B_TYPE) {
2794 int b_code = get_bits(&s->gb, 3);
2795 if(b_code==0){
2796 printf("Error, video packet header damaged (b_code=0)\n");
2797 }
2798 }
2799 }
2800 }
2801 //FIXME new-pred stuff
2802
2803 //printf("parse ok %d %d %d %d\n", mb_num, s->mb_x + s->mb_y*s->mb_width, get_bits_count(gb), get_bits_count(&s->gb));
2804
2805 return 0;
2806 }
2807
2808 void ff_mpeg4_clean_buffers(MpegEncContext *s)
2809 {
2810 int c_wrap, c_xy, l_wrap, l_xy;
2811
2812 l_wrap= s->block_wrap[0];
2813 l_xy= s->mb_y*l_wrap*2 + s->mb_x*2;
2814 c_wrap= s->block_wrap[4];
2815 c_xy= s->mb_y*c_wrap + s->mb_x;
2816
2817 #if 0
2818 /* clean DC */
2819 memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
2820 memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
2821 memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
2822 #endif
2823
2824 /* clean AC */
2825 memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(int16_t));
2826 memset(s->ac_val[1] + c_xy, 0, (c_wrap +1)*16*sizeof(int16_t));
2827 memset(s->ac_val[2] + c_xy, 0, (c_wrap +1)*16*sizeof(int16_t));
2828
2829 /* clean MV */
2830 // we cant clear the MVs as they might be needed by a b frame
2831 // memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(int16_t));
2832 // memset(s->motion_val, 0, 2*sizeof(int16_t)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
2833 s->last_mv[0][0][0]=
2834 s->last_mv[0][0][1]=
2835 s->last_mv[1][0][0]=
2836 s->last_mv[1][0][1]= 0;
2837 }
2838
2839 /**
2840 * decodes the group of blocks / video packet header.
2841 * @return <0 if no resync found
2842 */
2843 int ff_h263_resync(MpegEncContext *s){
2844 int left, ret;
2845
2846 if(s->codec_id==CODEC_ID_MPEG4){
2847 skip_bits1(&s->gb);
2848 align_get_bits(&s->gb);
2849 }
2850
2851 if(show_bits(&s->gb, 16)==0){
2852 if(s->codec_id==CODEC_ID_MPEG4)
2853 ret= mpeg4_decode_video_packet_header(s);
2854 else
2855 ret= h263_decode_gob_header(s);
2856 if(ret>=0)
2857 return 0;
2858 }
2859 //ok, its not where its supposed to be ...
2860 s->gb= s->last_resync_gb;
2861 align_get_bits(&s->gb);
2862 left= s->gb.size_in_bits - get_bits_count(&s->gb);
2863
2864 for(;left>16+1+5+5; left-=8){
2865 if(show_bits(&s->gb, 16)==0){
2866 GetBitContext bak= s->gb;
2867
2868 if(s->codec_id==CODEC_ID_MPEG4)
2869 ret= mpeg4_decode_video_packet_header(s);
2870 else
2871 ret= h263_decode_gob_header(s);
2872 if(ret>=0)
2873 return 0;
2874
2875 s->gb= bak;
2876 }
2877 skip_bits(&s->gb, 8);
2878 }
2879
2880 return -1;
2881 }
2882
2883 /**
2884 * gets the average motion vector for a GMC MB.
2885 * @param n either 0 for the x component or 1 for y
2886 * @returns the average MV for a GMC MB
2887 */
2888 static inline int get_amv(MpegEncContext *s, int n){
2889 int x, y, mb_v, sum, dx, dy, shift;
2890 int len = 1 << (s->f_code + 4);
2891 const int a= s->sprite_warping_accuracy;
2892
2893 if(s->real_sprite_warping_points==1){
2894 if(s->divx_version==500 && s->divx_build==413)
2895 sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
2896 else
2897 sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
2898 }else{
2899 dx= s->sprite_delta[n][0];
2900 dy= s->sprite_delta[n][1];
2901 shift= s->sprite_shift[0];
2902 if(n) dy -= 1<<(shift + a + 1);
2903 else dx -= 1<<(shift + a + 1);
2904 mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
2905
2906 sum=0;
2907 for(y=0; y<16; y++){
2908 int v;
2909
2910 v= mb_v + dy*y;
2911 //XXX FIXME optimize
2912 for(x=0; x<16; x++){
2913 sum+= v>>shift;
2914 v+= dx;
2915 }
2916 }
2917 sum= RSHIFT(sum, a+8-s->quarter_sample);
2918 }
2919
2920 if (sum < -len) sum= -len;
2921 else if (sum >= len) sum= len-1;
2922
2923 return sum;
2924 }
2925
2926 /**
2927 * decodes first partition.
2928 * @return number of MBs decoded or <0 if an error occured
2929 */
2930 static int mpeg4_decode_partition_a(MpegEncContext *s){
2931 int mb_num;
2932 static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
2933
2934 /* decode first partition */
2935 mb_num=0;
2936 s->first_slice_line=1;
2937 for(; s->mb_y<s->mb_height; s->mb_y++){
2938 ff_init_block_index(s);
2939 for(; s->mb_x<s->mb_width; s->mb_x++){
2940 const int xy= s->mb_x + s->mb_y*s->mb_stride;
2941 int cbpc;
2942 int dir=0;
2943
2944 mb_num++;
2945 ff_update_block_index(s);
2946 if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2947 s->first_slice_line=0;
2948
2949 if(s->pict_type==I_TYPE){
2950 int i;
2951
2952 if(show_bits_long(&s->gb, 19)==DC_MARKER){
2953 return mb_num