3 * Copyright (c) 2000,2001 Fabrice Bellard
4 * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "libavutil/attributes.h"
24 #include "libavutil/log.h"
25 #include "libavutil/opt.h"
26 #include "mpegutils.h"
27 #include "mpegvideo.h"
29 #include "mpeg4video.h"
32 /* The uni_DCtab_* tables below contain unified bits+length tables to encode DC
33 * differences in MPEG-4. Unified in the sense that the specification specifies
34 * this encoding in several steps. */
35 static uint8_t uni_DCtab_lum_len[512];
36 static uint8_t uni_DCtab_chrom_len[512];
37 static uint16_t uni_DCtab_lum_bits[512];
38 static uint16_t uni_DCtab_chrom_bits[512];
40 /* Unified encoding tables for run length encoding of coefficients.
41 * Unified in the sense that the specification specifies the encoding in several steps. */
42 static uint32_t uni_mpeg4_intra_rl_bits[64 * 64 * 2 * 2];
43 static uint8_t uni_mpeg4_intra_rl_len[64 * 64 * 2 * 2];
44 static uint32_t uni_mpeg4_inter_rl_bits[64 * 64 * 2 * 2];
45 static uint8_t uni_mpeg4_inter_rl_len[64 * 64 * 2 * 2];
47 //#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 + (run) * 256 + (level))
48 //#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 * 64 + (run) + (level) * 64)
49 #define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 * 64 + (run) * 128 + (level))
62 * Return the number of bits that encoding the 8x8 block in block would need.
63 * @param[in] block_last_index last index in scantable order that refers to a non zero element in block.
65 static inline int get_block_rate(MpegEncContext *s, int16_t block[64],
66 int block_last_index, uint8_t scantable[64])
72 for (j = 1; j <= block_last_index; j++) {
73 const int index = scantable[j];
74 int level = block[index];
77 if ((level & (~127)) == 0) {
78 if (j < block_last_index)
79 rate += s->intra_ac_vlc_length[UNI_AC_ENC_INDEX(j - last - 1, level)];
81 rate += s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j - last - 1, level)];
83 rate += s->ac_esc_length;
93 * Restore the ac coefficients in block that have been changed by decide_ac_pred().
94 * This function also restores s->block_last_index.
95 * @param[in,out] block MB coefficients, these will be restored
96 * @param[in] dir ac prediction direction for each 8x8 block
97 * @param[out] st scantable for each 8x8 block
98 * @param[in] zigzag_last_index index referring to the last non zero coefficient in zigzag order
100 static inline void restore_ac_coeffs(MpegEncContext *s, int16_t block[6][64],
101 const int dir[6], uint8_t *st[6],
102 const int zigzag_last_index[6])
105 memcpy(s->block_last_index, zigzag_last_index, sizeof(int) * 6);
107 for (n = 0; n < 6; n++) {
108 int16_t *ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16;
110 st[n] = s->intra_scantable.permutated;
113 for (i = 1; i < 8; i++)
114 block[n][s->idsp.idct_permutation[i]] = ac_val[i + 8];
116 /* left prediction */
117 for (i = 1; i < 8; i++)
118 block[n][s->idsp.idct_permutation[i << 3]] = ac_val[i];
124 * Return the optimal value (0 or 1) for the ac_pred element for the given MB in MPEG-4.
125 * This function will also update s->block_last_index and s->ac_val.
126 * @param[in,out] block MB coefficients, these will be updated if 1 is returned
127 * @param[in] dir ac prediction direction for each 8x8 block
128 * @param[out] st scantable for each 8x8 block
129 * @param[out] zigzag_last_index index referring to the last non zero coefficient in zigzag order
131 static inline int decide_ac_pred(MpegEncContext *s, int16_t block[6][64],
132 const int dir[6], uint8_t *st[6],
133 int zigzag_last_index[6])
137 int8_t *const qscale_table = s->current_picture.qscale_table;
139 memcpy(zigzag_last_index, s->block_last_index, sizeof(int) * 6);
141 for (n = 0; n < 6; n++) {
142 int16_t *ac_val, *ac_val1;
144 score -= get_block_rate(s, block[n], s->block_last_index[n],
145 s->intra_scantable.permutated);
147 ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16;
150 const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
152 ac_val -= s->block_wrap[n] * 16;
153 if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) {
155 for (i = 1; i < 8; i++) {
156 const int level = block[n][s->idsp.idct_permutation[i]];
157 block[n][s->idsp.idct_permutation[i]] = level - ac_val[i + 8];
158 ac_val1[i] = block[n][s->idsp.idct_permutation[i << 3]];
159 ac_val1[i + 8] = level;
162 /* different qscale, we must rescale */
163 for (i = 1; i < 8; i++) {
164 const int level = block[n][s->idsp.idct_permutation[i]];
165 block[n][s->idsp.idct_permutation[i]] = level - ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
166 ac_val1[i] = block[n][s->idsp.idct_permutation[i << 3]];
167 ac_val1[i + 8] = level;
170 st[n] = s->intra_h_scantable.permutated;
172 const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
173 /* left prediction */
175 if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) {
177 for (i = 1; i < 8; i++) {
178 const int level = block[n][s->idsp.idct_permutation[i << 3]];
179 block[n][s->idsp.idct_permutation[i << 3]] = level - ac_val[i];
181 ac_val1[i + 8] = block[n][s->idsp.idct_permutation[i]];
184 /* different qscale, we must rescale */
185 for (i = 1; i < 8; i++) {
186 const int level = block[n][s->idsp.idct_permutation[i << 3]];
187 block[n][s->idsp.idct_permutation[i << 3]] = level - ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
189 ac_val1[i + 8] = block[n][s->idsp.idct_permutation[i]];
192 st[n] = s->intra_v_scantable.permutated;
195 for (i = 63; i > 0; i--) // FIXME optimize
196 if (block[n][st[n][i]])
198 s->block_last_index[n] = i;
200 score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
206 restore_ac_coeffs(s, block, dir, st, zigzag_last_index);
212 * modify mb_type & qscale so that encoding is actually possible in MPEG-4
214 void ff_clean_mpeg4_qscales(MpegEncContext *s)
217 int8_t *const qscale_table = s->current_picture.qscale_table;
219 ff_clean_h263_qscales(s);
221 if (s->pict_type == AV_PICTURE_TYPE_B) {
223 /* ok, come on, this isn't funny anymore, there's more code for
224 * handling this MPEG-4 mess than for the actual adaptive quantization */
226 for (i = 0; i < s->mb_num; i++) {
227 int mb_xy = s->mb_index2xy[i];
228 odd += qscale_table[mb_xy] & 1;
231 if (2 * odd > s->mb_num)
236 for (i = 0; i < s->mb_num; i++) {
237 int mb_xy = s->mb_index2xy[i];
238 if ((qscale_table[mb_xy] & 1) != odd)
239 qscale_table[mb_xy]++;
240 if (qscale_table[mb_xy] > 31)
241 qscale_table[mb_xy] = 31;
244 for (i = 1; i < s->mb_num; i++) {
245 int mb_xy = s->mb_index2xy[i];
246 if (qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i - 1]] &&
247 (s->mb_type[mb_xy] & CANDIDATE_MB_TYPE_DIRECT)) {
248 s->mb_type[mb_xy] |= CANDIDATE_MB_TYPE_BIDIR;
255 * Encode the dc value.
256 * @param n block index (0-3 are luma, 4-5 are chroma)
258 static inline void mpeg4_encode_dc(PutBitContext *s, int level, int n)
260 /* DC will overflow if level is outside the [-255,255] range. */
264 put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
267 put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
271 static inline int mpeg4_get_dc_length(int level, int n)
274 return uni_DCtab_lum_len[level + 256];
276 return uni_DCtab_chrom_len[level + 256];
280 * Encode an 8x8 block.
281 * @param n block index (0-3 are luma, 4-5 are chroma)
283 static inline void mpeg4_encode_block(MpegEncContext *s,
284 int16_t *block, int n, int intra_dc,
285 uint8_t *scan_table, PutBitContext *dc_pb,
286 PutBitContext *ac_pb)
288 int i, last_non_zero;
291 const int last_index = s->block_last_index[n];
293 if (s->mb_intra) { // Note gcc (3.2.1 at least) will optimize this away
294 /* MPEG-4 based DC predictor */
295 mpeg4_encode_dc(dc_pb, intra_dc, n);
299 bits_tab = uni_mpeg4_intra_rl_bits;
300 len_tab = uni_mpeg4_intra_rl_len;
305 bits_tab = uni_mpeg4_inter_rl_bits;
306 len_tab = uni_mpeg4_inter_rl_len;
310 last_non_zero = i - 1;
311 for (; i < last_index; i++) {
312 int level = block[scan_table[i]];
314 int run = i - last_non_zero - 1;
316 if ((level & (~127)) == 0) {
317 const int index = UNI_MPEG4_ENC_INDEX(0, run, level);
318 put_bits(ac_pb, len_tab[index], bits_tab[index]);
321 7 + 2 + 1 + 6 + 1 + 12 + 1,
322 (3 << 23) + (3 << 21) + (0 << 20) + (run << 14) +
323 (1 << 13) + (((level - 64) & 0xfff) << 1) + 1);
328 /* if (i <= last_index) */ {
329 int level = block[scan_table[i]];
330 int run = i - last_non_zero - 1;
332 if ((level & (~127)) == 0) {
333 const int index = UNI_MPEG4_ENC_INDEX(1, run, level);
334 put_bits(ac_pb, len_tab[index], bits_tab[index]);
337 7 + 2 + 1 + 6 + 1 + 12 + 1,
338 (3 << 23) + (3 << 21) + (1 << 20) + (run << 14) +
339 (1 << 13) + (((level - 64) & 0xfff) << 1) + 1);
344 static int mpeg4_get_block_length(MpegEncContext *s,
345 int16_t *block, int n,
346 int intra_dc, uint8_t *scan_table)
348 int i, last_non_zero;
350 const int last_index = s->block_last_index[n];
353 if (s->mb_intra) { // Note gcc (3.2.1 at least) will optimize this away
354 /* MPEG-4 based DC predictor */
355 len += mpeg4_get_dc_length(intra_dc, n);
359 len_tab = uni_mpeg4_intra_rl_len;
364 len_tab = uni_mpeg4_inter_rl_len;
368 last_non_zero = i - 1;
369 for (; i < last_index; i++) {
370 int level = block[scan_table[i]];
372 int run = i - last_non_zero - 1;
374 if ((level & (~127)) == 0) {
375 const int index = UNI_MPEG4_ENC_INDEX(0, run, level);
376 len += len_tab[index];
378 len += 7 + 2 + 1 + 6 + 1 + 12 + 1;
383 /* if (i <= last_index) */ {
384 int level = block[scan_table[i]];
385 int run = i - last_non_zero - 1;
387 if ((level & (~127)) == 0) {
388 const int index = UNI_MPEG4_ENC_INDEX(1, run, level);
389 len += len_tab[index];
391 len += 7 + 2 + 1 + 6 + 1 + 12 + 1;
398 static inline void mpeg4_encode_blocks(MpegEncContext *s, int16_t block[6][64],
399 int intra_dc[6], uint8_t **scan_table,
400 PutBitContext *dc_pb,
401 PutBitContext *ac_pb)
406 if (s->avctx->flags2 & AV_CODEC_FLAG2_NO_OUTPUT) {
407 for (i = 0; i < 6; i++)
408 skip_put_bits(&s->pb,
409 mpeg4_get_block_length(s, block[i], i,
410 intra_dc[i], scan_table[i]));
412 /* encode each block */
413 for (i = 0; i < 6; i++)
414 mpeg4_encode_block(s, block[i], i,
415 intra_dc[i], scan_table[i], dc_pb, ac_pb);
418 if (s->avctx->flags2 & AV_CODEC_FLAG2_NO_OUTPUT) {
419 for (i = 0; i < 6; i++)
420 skip_put_bits(&s->pb,
421 mpeg4_get_block_length(s, block[i], i, 0,
422 s->intra_scantable.permutated));
424 /* encode each block */
425 for (i = 0; i < 6; i++)
426 mpeg4_encode_block(s, block[i], i, 0,
427 s->intra_scantable.permutated, dc_pb, ac_pb);
432 static inline int get_b_cbp(MpegEncContext *s, int16_t block[6][64],
433 int motion_x, int motion_y, int mb_type)
437 if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {
439 const int lambda = s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
441 for (i = 0; i < 6; i++) {
442 if (s->coded_score[i] < 0) {
443 score += s->coded_score[i];
450 if ((motion_x | motion_y | s->dquant | mb_type) == 0)
451 zero_score -= 4; // 2 * MV + mb_type + cbp bit
453 zero_score *= lambda;
454 if (zero_score <= score)
458 for (i = 0; i < 6; i++) {
459 if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i)) & 1) == 0) {
460 s->block_last_index[i] = -1;
461 s->bdsp.clear_block(s->block[i]);
465 for (i = 0; i < 6; i++) {
466 if (s->block_last_index[i] >= 0)
473 // FIXME this is duplicated to h263.c
474 static const int dquant_code[5] = { 1, 0, 9, 2, 3 };
476 void ff_mpeg4_encode_mb(MpegEncContext *s, int16_t block[6][64],
477 int motion_x, int motion_y)
479 int cbpc, cbpy, pred_x, pred_y;
480 PutBitContext *const pb2 = s->data_partitioning ? &s->pb2 : &s->pb;
481 PutBitContext *const tex_pb = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B ? &s->tex_pb : &s->pb;
482 PutBitContext *const dc_pb = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_I ? &s->pb2 : &s->pb;
483 const int interleaved_stats = (s->avctx->flags & AV_CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
488 if (s->pict_type == AV_PICTURE_TYPE_B) {
489 /* convert from mv_dir to type */
490 static const int mb_type_table[8] = { -1, 3, 2, 1, -1, -1, -1, 0 };
491 int mb_type = mb_type_table[s->mv_dir];
494 for (i = 0; i < 2; i++)
495 s->last_mv[i][0][0] =
496 s->last_mv[i][0][1] =
497 s->last_mv[i][1][0] =
498 s->last_mv[i][1][1] = 0;
501 av_assert2(s->dquant >= -2 && s->dquant <= 2);
502 av_assert2((s->dquant & 1) == 0);
503 av_assert2(mb_type >= 0);
505 /* nothing to do if this MB was skipped in the next P-frame */
506 if (s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]) { // FIXME avoid DCT & ...
512 s->mv_dir = MV_DIR_FORWARD; // doesn't matter
513 s->qscale -= s->dquant;
514 // s->mb_skipped = 1;
519 cbp = get_b_cbp(s, block, motion_x, motion_y, mb_type);
521 if ((cbp | motion_x | motion_y | mb_type) == 0) {
522 /* direct MB with MV={0,0} */
523 av_assert2(s->dquant == 0);
525 put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
527 if (interleaved_stats) {
535 put_bits(&s->pb, 1, 0); /* mb coded modb1=0 */
536 put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ // FIXME merge
537 put_bits(&s->pb, mb_type + 1, 1); // this table is so simple that we don't need it :)
539 put_bits(&s->pb, 6, cbp);
541 if (cbp && mb_type) {
543 put_bits(&s->pb, 2, (s->dquant >> 2) + 3);
545 put_bits(&s->pb, 1, 0);
547 s->qscale -= s->dquant;
549 if (!s->progressive_sequence) {
551 put_bits(&s->pb, 1, s->interlaced_dct);
552 if (mb_type) // not direct mode
553 put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
556 if (interleaved_stats)
557 s->misc_bits += get_bits_diff(s);
560 av_assert2(s->mv_dir & MV_DIRECT);
561 ff_h263_encode_motion_vector(s, motion_x, motion_y, 1);
565 av_assert2(mb_type > 0 && mb_type < 4);
566 if (s->mv_type != MV_TYPE_FIELD) {
567 if (s->mv_dir & MV_DIR_FORWARD) {
568 ff_h263_encode_motion_vector(s,
569 s->mv[0][0][0] - s->last_mv[0][0][0],
570 s->mv[0][0][1] - s->last_mv[0][0][1],
572 s->last_mv[0][0][0] =
573 s->last_mv[0][1][0] = s->mv[0][0][0];
574 s->last_mv[0][0][1] =
575 s->last_mv[0][1][1] = s->mv[0][0][1];
578 if (s->mv_dir & MV_DIR_BACKWARD) {
579 ff_h263_encode_motion_vector(s,
580 s->mv[1][0][0] - s->last_mv[1][0][0],
581 s->mv[1][0][1] - s->last_mv[1][0][1],
583 s->last_mv[1][0][0] =
584 s->last_mv[1][1][0] = s->mv[1][0][0];
585 s->last_mv[1][0][1] =
586 s->last_mv[1][1][1] = s->mv[1][0][1];
590 if (s->mv_dir & MV_DIR_FORWARD) {
591 put_bits(&s->pb, 1, s->field_select[0][0]);
592 put_bits(&s->pb, 1, s->field_select[0][1]);
594 if (s->mv_dir & MV_DIR_BACKWARD) {
595 put_bits(&s->pb, 1, s->field_select[1][0]);
596 put_bits(&s->pb, 1, s->field_select[1][1]);
598 if (s->mv_dir & MV_DIR_FORWARD) {
599 for (i = 0; i < 2; i++) {
600 ff_h263_encode_motion_vector(s,
601 s->mv[0][i][0] - s->last_mv[0][i][0],
602 s->mv[0][i][1] - s->last_mv[0][i][1] / 2,
604 s->last_mv[0][i][0] = s->mv[0][i][0];
605 s->last_mv[0][i][1] = s->mv[0][i][1] * 2;
609 if (s->mv_dir & MV_DIR_BACKWARD) {
610 for (i = 0; i < 2; i++) {
611 ff_h263_encode_motion_vector(s,
612 s->mv[1][i][0] - s->last_mv[1][i][0],
613 s->mv[1][i][1] - s->last_mv[1][i][1] / 2,
615 s->last_mv[1][i][0] = s->mv[1][i][0];
616 s->last_mv[1][i][1] = s->mv[1][i][1] * 2;
623 if (interleaved_stats)
624 s->mv_bits += get_bits_diff(s);
626 mpeg4_encode_blocks(s, block, NULL, NULL, NULL, &s->pb);
628 if (interleaved_stats)
629 s->p_tex_bits += get_bits_diff(s);
630 } else { /* s->pict_type==AV_PICTURE_TYPE_B */
631 cbp = get_p_cbp(s, block, motion_x, motion_y);
633 if ((cbp | motion_x | motion_y | s->dquant) == 0 &&
634 s->mv_type == MV_TYPE_16X16) {
635 /* Check if the B-frames can skip it too, as we must skip it
636 * if we skip here why didn't they just compress
637 * the skip-mb bits instead of reusing them ?! */
638 if (s->max_b_frames > 0) {
646 offset = x + y * s->linesize;
647 p_pic = s->new_picture.f->data[0] + offset;
650 for (i = 0; i < s->max_b_frames; i++) {
653 Picture *pic = s->reordered_input_picture[i + 1];
655 if (!pic || pic->f->pict_type != AV_PICTURE_TYPE_B)
658 b_pic = pic->f->data[0] + offset;
660 b_pic += INPLACE_OFFSET;
662 if (x + 16 > s->width || y + 16 > s->height) {
664 int xe = FFMIN(16, s->width - x);
665 int ye = FFMIN(16, s->height - y);
667 for (y1 = 0; y1 < ye; y1++) {
668 for (x1 = 0; x1 < xe; x1++) {
669 diff += FFABS(p_pic[x1 + y1 * s->linesize] - b_pic[x1 + y1 * s->linesize]);
672 diff = diff * 256 / (xe * ye);
674 diff = s->mecc.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
676 if (diff > s->qscale * 70) { // FIXME check that 70 is optimal
684 if (s->mb_skipped == 1) {
685 /* skip macroblock */
686 put_bits(&s->pb, 1, 1);
688 if (interleaved_stats) {
698 put_bits(&s->pb, 1, 0); /* mb coded */
702 if (s->mv_type == MV_TYPE_16X16) {
706 ff_h263_inter_MCBPC_bits[cbpc],
707 ff_h263_inter_MCBPC_code[cbpc]);
709 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
711 put_bits(pb2, 2, dquant_code[s->dquant + 2]);
713 if (!s->progressive_sequence) {
715 put_bits(pb2, 1, s->interlaced_dct);
719 if (interleaved_stats)
720 s->misc_bits += get_bits_diff(s);
722 /* motion vectors: 16x16 mode */
723 ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
725 ff_h263_encode_motion_vector(s,
729 } else if (s->mv_type == MV_TYPE_FIELD) {
733 ff_h263_inter_MCBPC_bits[cbpc],
734 ff_h263_inter_MCBPC_code[cbpc]);
736 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
738 put_bits(pb2, 2, dquant_code[s->dquant + 2]);
740 av_assert2(!s->progressive_sequence);
742 put_bits(pb2, 1, s->interlaced_dct);
745 if (interleaved_stats)
746 s->misc_bits += get_bits_diff(s);
748 /* motion vectors: 16x8 interlaced mode */
749 ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
752 put_bits(&s->pb, 1, s->field_select[0][0]);
753 put_bits(&s->pb, 1, s->field_select[0][1]);
755 ff_h263_encode_motion_vector(s,
756 s->mv[0][0][0] - pred_x,
757 s->mv[0][0][1] - pred_y,
759 ff_h263_encode_motion_vector(s,
760 s->mv[0][1][0] - pred_x,
761 s->mv[0][1][1] - pred_y,
764 av_assert2(s->mv_type == MV_TYPE_8X8);
766 ff_h263_inter_MCBPC_bits[cbpc + 16],
767 ff_h263_inter_MCBPC_code[cbpc + 16]);
768 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
770 if (!s->progressive_sequence && cbp)
771 put_bits(pb2, 1, s->interlaced_dct);
773 if (interleaved_stats)
774 s->misc_bits += get_bits_diff(s);
776 for (i = 0; i < 4; i++) {
777 /* motion vectors: 8x8 mode*/
778 ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
780 ff_h263_encode_motion_vector(s,
781 s->current_picture.motion_val[0][s->block_index[i]][0] - pred_x,
782 s->current_picture.motion_val[0][s->block_index[i]][1] - pred_y,
787 if (interleaved_stats)
788 s->mv_bits += get_bits_diff(s);
790 mpeg4_encode_blocks(s, block, NULL, NULL, NULL, tex_pb);
792 if (interleaved_stats)
793 s->p_tex_bits += get_bits_diff(s);
799 int dc_diff[6]; // dc values with the dc prediction subtracted
800 int dir[6]; // prediction direction
801 int zigzag_last_index[6];
802 uint8_t *scan_table[6];
805 for (i = 0; i < 6; i++)
806 dc_diff[i] = ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
808 if (s->avctx->flags & AV_CODEC_FLAG_AC_PRED) {
809 s->ac_pred = decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
811 for (i = 0; i < 6; i++)
812 scan_table[i] = s->intra_scantable.permutated;
817 for (i = 0; i < 6; i++)
818 if (s->block_last_index[i] >= 1)
822 if (s->pict_type == AV_PICTURE_TYPE_I) {
826 ff_h263_intra_MCBPC_bits[cbpc],
827 ff_h263_intra_MCBPC_code[cbpc]);
831 put_bits(&s->pb, 1, 0); /* mb coded */
833 ff_h263_inter_MCBPC_bits[cbpc + 4],
834 ff_h263_inter_MCBPC_code[cbpc + 4]);
836 put_bits(pb2, 1, s->ac_pred);
838 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
840 put_bits(dc_pb, 2, dquant_code[s->dquant + 2]);
842 if (!s->progressive_sequence)
843 put_bits(dc_pb, 1, s->interlaced_dct);
845 if (interleaved_stats)
846 s->misc_bits += get_bits_diff(s);
848 mpeg4_encode_blocks(s, block, dc_diff, scan_table, dc_pb, tex_pb);
850 if (interleaved_stats)
851 s->i_tex_bits += get_bits_diff(s);
854 /* restore ac coeffs & last_index stuff
855 * if we messed them up with the prediction */
857 restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
862 * add MPEG-4 stuffing bits (01...1)
864 void ff_mpeg4_stuffing(PutBitContext *pbc)
868 length = (-put_bits_count(pbc)) & 7;
870 put_bits(pbc, length, (1 << length) - 1);
873 /* must be called before writing the header */
874 void ff_set_mpeg4_time(MpegEncContext *s)
876 if (s->pict_type == AV_PICTURE_TYPE_B) {
877 ff_mpeg4_init_direct_mv(s);
879 s->last_time_base = s->time_base;
880 s->time_base = FFUDIV(s->time, s->avctx->time_base.den);
884 static void mpeg4_encode_gop_header(MpegEncContext *s)
886 int64_t hours, minutes, seconds;
889 put_bits(&s->pb, 16, 0);
890 put_bits(&s->pb, 16, GOP_STARTCODE);
892 time = s->current_picture_ptr->f->pts;
893 if (s->reordered_input_picture[1])
894 time = FFMIN(time, s->reordered_input_picture[1]->f->pts);
895 time = time * s->avctx->time_base.num;
896 s->last_time_base = FFUDIV(time, s->avctx->time_base.den);
898 seconds = FFUDIV(time, s->avctx->time_base.den);
899 minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60);
900 hours = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60);
901 hours = FFUMOD(hours , 24);
903 put_bits(&s->pb, 5, hours);
904 put_bits(&s->pb, 6, minutes);
905 put_bits(&s->pb, 1, 1);
906 put_bits(&s->pb, 6, seconds);
908 put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
909 put_bits(&s->pb, 1, 0); // broken link == NO
911 ff_mpeg4_stuffing(&s->pb);
914 static void mpeg4_encode_visual_object_header(MpegEncContext *s)
916 int profile_and_level_indication;
919 if (s->avctx->profile != FF_PROFILE_UNKNOWN) {
920 profile_and_level_indication = s->avctx->profile << 4;
921 } else if (s->max_b_frames || s->quarter_sample) {
922 profile_and_level_indication = 0xF0; // adv simple
924 profile_and_level_indication = 0x00; // simple
927 if (s->avctx->level != FF_LEVEL_UNKNOWN)
928 profile_and_level_indication |= s->avctx->level;
930 profile_and_level_indication |= 1; // level 1
932 if (profile_and_level_indication >> 4 == 0xF)
939 put_bits(&s->pb, 16, 0);
940 put_bits(&s->pb, 16, VOS_STARTCODE);
942 put_bits(&s->pb, 8, profile_and_level_indication);
944 put_bits(&s->pb, 16, 0);
945 put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
947 put_bits(&s->pb, 1, 1);
948 put_bits(&s->pb, 4, vo_ver_id);
949 put_bits(&s->pb, 3, 1); // priority
951 put_bits(&s->pb, 4, 1); // visual obj type== video obj
953 put_bits(&s->pb, 1, 0); // video signal type == no clue // FIXME
955 ff_mpeg4_stuffing(&s->pb);
958 static void mpeg4_encode_vol_header(MpegEncContext *s,
964 if (s->max_b_frames || s->quarter_sample) {
966 s->vo_type = ADV_SIMPLE_VO_TYPE;
969 s->vo_type = SIMPLE_VO_TYPE;
972 put_bits(&s->pb, 16, 0);
973 put_bits(&s->pb, 16, 0x100 + vo_number); /* video obj */
974 put_bits(&s->pb, 16, 0);
975 put_bits(&s->pb, 16, 0x120 + vol_number); /* video obj layer */
977 put_bits(&s->pb, 1, 0); /* random access vol */
978 put_bits(&s->pb, 8, s->vo_type); /* video obj type indication */
979 if (s->workaround_bugs & FF_BUG_MS) {
980 put_bits(&s->pb, 1, 0); /* is obj layer id= no */
982 put_bits(&s->pb, 1, 1); /* is obj layer id= yes */
983 put_bits(&s->pb, 4, vo_ver_id); /* is obj layer ver id */
984 put_bits(&s->pb, 3, 1); /* is obj layer priority */
987 s->aspect_ratio_info = ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio);
989 put_bits(&s->pb, 4, s->aspect_ratio_info); /* aspect ratio info */
990 if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
991 av_reduce(&s->avctx->sample_aspect_ratio.num, &s->avctx->sample_aspect_ratio.den,
992 s->avctx->sample_aspect_ratio.num, s->avctx->sample_aspect_ratio.den, 255);
993 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
994 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
997 if (s->workaround_bugs & FF_BUG_MS) {
998 put_bits(&s->pb, 1, 0); /* vol control parameters= no @@@ */
1000 put_bits(&s->pb, 1, 1); /* vol control parameters= yes */
1001 put_bits(&s->pb, 2, 1); /* chroma format YUV 420/YV12 */
1002 put_bits(&s->pb, 1, s->low_delay);
1003 put_bits(&s->pb, 1, 0); /* vbv parameters= no */
1006 put_bits(&s->pb, 2, RECT_SHAPE); /* vol shape= rectangle */
1007 put_bits(&s->pb, 1, 1); /* marker bit */
1009 put_bits(&s->pb, 16, s->avctx->time_base.den);
1010 if (s->time_increment_bits < 1)
1011 s->time_increment_bits = 1;
1012 put_bits(&s->pb, 1, 1); /* marker bit */
1013 put_bits(&s->pb, 1, 0); /* fixed vop rate=no */
1014 put_bits(&s->pb, 1, 1); /* marker bit */
1015 put_bits(&s->pb, 13, s->width); /* vol width */
1016 put_bits(&s->pb, 1, 1); /* marker bit */
1017 put_bits(&s->pb, 13, s->height); /* vol height */
1018 put_bits(&s->pb, 1, 1); /* marker bit */
1019 put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1020 put_bits(&s->pb, 1, 1); /* obmc disable */
1022 put_bits(&s->pb, 1, 0); /* sprite enable */
1024 put_bits(&s->pb, 2, 0); /* sprite enable */
1026 put_bits(&s->pb, 1, 0); /* not 8 bit == false */
1027 put_bits(&s->pb, 1, s->mpeg_quant); /* quant type = (0 = H.263 style) */
1029 if (s->mpeg_quant) {
1030 ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
1031 ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
1035 put_bits(&s->pb, 1, s->quarter_sample);
1036 put_bits(&s->pb, 1, 1); /* complexity estimation disable */
1037 put_bits(&s->pb, 1, s->rtp_mode ? 0 : 1); /* resync marker disable */
1038 put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1039 if (s->data_partitioning)
1040 put_bits(&s->pb, 1, 0); /* no rvlc */
1042 if (vo_ver_id != 1) {
1043 put_bits(&s->pb, 1, 0); /* newpred */
1044 put_bits(&s->pb, 1, 0); /* reduced res vop */
1046 put_bits(&s->pb, 1, 0); /* scalability */
1048 ff_mpeg4_stuffing(&s->pb);
1051 if (!(s->avctx->flags & AV_CODEC_FLAG_BITEXACT)) {
1052 put_bits(&s->pb, 16, 0);
1053 put_bits(&s->pb, 16, 0x1B2); /* user_data */
1054 ff_put_string(&s->pb, LIBAVCODEC_IDENT, 0);
1058 /* write MPEG-4 VOP header */
1059 int ff_mpeg4_encode_picture_header(MpegEncContext *s, int picture_number)
1062 int64_t time_div, time_mod;
1064 if (s->pict_type == AV_PICTURE_TYPE_I) {
1065 if (!(s->avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1066 if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT) // HACK, the reference sw is buggy
1067 mpeg4_encode_visual_object_header(s);
1068 if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number == 0) // HACK, the reference sw is buggy
1069 mpeg4_encode_vol_header(s, 0, 0);
1071 if (!(s->workaround_bugs & FF_BUG_MS))
1072 mpeg4_encode_gop_header(s);
1075 s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
1077 put_bits(&s->pb, 16, 0); /* vop header */
1078 put_bits(&s->pb, 16, VOP_STARTCODE); /* vop header */
1079 put_bits(&s->pb, 2, s->pict_type - 1); /* pict type: I = 0 , P = 1 */
1081 time_div = FFUDIV(s->time, s->avctx->time_base.den);
1082 time_mod = FFUMOD(s->time, s->avctx->time_base.den);
1083 time_incr = time_div - s->last_time_base;
1085 // This limits the frame duration to max 1 hour
1086 if (time_incr > 3600) {
1087 av_log(s->avctx, AV_LOG_ERROR, "time_incr %"PRIu64" too large\n", time_incr);
1088 return AVERROR(EINVAL);
1091 put_bits(&s->pb, 1, 1);
1093 put_bits(&s->pb, 1, 0);
1095 put_bits(&s->pb, 1, 1); /* marker */
1096 put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
1097 put_bits(&s->pb, 1, 1); /* marker */
1098 put_bits(&s->pb, 1, 1); /* vop coded */
1099 if (s->pict_type == AV_PICTURE_TYPE_P) {
1100 put_bits(&s->pb, 1, s->no_rounding); /* rounding type */
1102 put_bits(&s->pb, 3, 0); /* intra dc VLC threshold */
1103 if (!s->progressive_sequence) {
1104 put_bits(&s->pb, 1, s->current_picture_ptr->f->top_field_first);
1105 put_bits(&s->pb, 1, s->alternate_scan);
1107 // FIXME sprite stuff
1109 put_bits(&s->pb, 5, s->qscale);
1111 if (s->pict_type != AV_PICTURE_TYPE_I)
1112 put_bits(&s->pb, 3, s->f_code); /* fcode_for */
1113 if (s->pict_type == AV_PICTURE_TYPE_B)
1114 put_bits(&s->pb, 3, s->b_code); /* fcode_back */
1119 static av_cold void init_uni_dc_tab(void)
1121 int level, uni_code, uni_len;
1123 for (level = -256; level < 256; level++) {
1125 /* find number of bits */
1134 l = (-level) ^ ((1 << size) - 1);
1139 uni_code = ff_mpeg4_DCtab_lum[size][0];
1140 uni_len = ff_mpeg4_DCtab_lum[size][1];
1152 uni_DCtab_lum_bits[level + 256] = uni_code;
1153 uni_DCtab_lum_len[level + 256] = uni_len;
1156 uni_code = ff_mpeg4_DCtab_chrom[size][0];
1157 uni_len = ff_mpeg4_DCtab_chrom[size][1];
1169 uni_DCtab_chrom_bits[level + 256] = uni_code;
1170 uni_DCtab_chrom_len[level + 256] = uni_len;
1174 static av_cold void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab,
1177 int slevel, run, last;
1179 av_assert0(MAX_LEVEL >= 64);
1180 av_assert0(MAX_RUN >= 63);
1182 for (slevel = -64; slevel < 64; slevel++) {
1185 for (run = 0; run < 64; run++) {
1186 for (last = 0; last <= 1; last++) {
1187 const int index = UNI_MPEG4_ENC_INDEX(last, run, slevel + 64);
1188 int level = slevel < 0 ? -slevel : slevel;
1189 int sign = slevel < 0 ? 1 : 0;
1190 int bits, len, code;
1193 len_tab[index] = 100;
1196 code = get_rl_index(rl, last, run, level);
1197 bits = rl->table_vlc[code][0];
1198 len = rl->table_vlc[code][1];
1199 bits = bits * 2 + sign;
1202 if (code != rl->n && len < len_tab[index]) {
1203 bits_tab[index] = bits;
1204 len_tab[index] = len;
1207 bits = rl->table_vlc[rl->n][0];
1208 len = rl->table_vlc[rl->n][1];
1211 level1 = level - rl->max_level[last][run];
1213 code = get_rl_index(rl, last, run, level1);
1214 bits <<= rl->table_vlc[code][1];
1215 len += rl->table_vlc[code][1];
1216 bits += rl->table_vlc[code][0];
1217 bits = bits * 2 + sign;
1220 if (code != rl->n && len < len_tab[index]) {
1221 bits_tab[index] = bits;
1222 len_tab[index] = len;
1226 bits = rl->table_vlc[rl->n][0];
1227 len = rl->table_vlc[rl->n][1];
1228 bits = bits * 4 + 2;
1230 run1 = run - rl->max_run[last][level] - 1;
1232 code = get_rl_index(rl, last, run1, level);
1233 bits <<= rl->table_vlc[code][1];
1234 len += rl->table_vlc[code][1];
1235 bits += rl->table_vlc[code][0];
1236 bits = bits * 2 + sign;
1239 if (code != rl->n && len < len_tab[index]) {
1240 bits_tab[index] = bits;
1241 len_tab[index] = len;
1245 bits = rl->table_vlc[rl->n][0];
1246 len = rl->table_vlc[rl->n][1];
1247 bits = bits * 4 + 3;
1249 bits = bits * 2 + last;
1251 bits = bits * 64 + run;
1253 bits = bits * 2 + 1;
1255 bits = bits * 4096 + (slevel & 0xfff);
1257 bits = bits * 2 + 1;
1260 if (len < len_tab[index]) {
1261 bits_tab[index] = bits;
1262 len_tab[index] = len;
1269 static av_cold int encode_init(AVCodecContext *avctx)
1271 MpegEncContext *s = avctx->priv_data;
1273 static int done = 0;
1275 if (avctx->width >= (1<<13) || avctx->height >= (1<<13)) {
1276 av_log(avctx, AV_LOG_ERROR, "dimensions too large for MPEG-4\n");
1277 return AVERROR(EINVAL);
1280 if ((ret = ff_mpv_encode_init(avctx)) < 0)
1288 ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
1290 init_uni_mpeg4_rl_tab(&ff_mpeg4_rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1291 init_uni_mpeg4_rl_tab(&ff_h263_rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1294 s->min_qcoeff = -2048;
1295 s->max_qcoeff = 2047;
1296 s->intra_ac_vlc_length = uni_mpeg4_intra_rl_len;
1297 s->intra_ac_vlc_last_length = uni_mpeg4_intra_rl_len + 128 * 64;
1298 s->inter_ac_vlc_length = uni_mpeg4_inter_rl_len;
1299 s->inter_ac_vlc_last_length = uni_mpeg4_inter_rl_len + 128 * 64;
1300 s->luma_dc_vlc_length = uni_DCtab_lum_len;
1301 s->ac_esc_length = 7 + 2 + 1 + 6 + 1 + 12 + 1;
1302 s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
1303 s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
1305 if (s->avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1306 s->avctx->extradata = av_malloc(1024);
1307 init_put_bits(&s->pb, s->avctx->extradata, 1024);
1309 if (!(s->workaround_bugs & FF_BUG_MS))
1310 mpeg4_encode_visual_object_header(s);
1311 mpeg4_encode_vol_header(s, 0, 0);
1313 // ff_mpeg4_stuffing(&s->pb); ?
1314 flush_put_bits(&s->pb);
1315 s->avctx->extradata_size = (put_bits_count(&s->pb) + 7) >> 3;
1320 void ff_mpeg4_init_partitions(MpegEncContext *s)
1322 uint8_t *start = put_bits_ptr(&s->pb);
1323 uint8_t *end = s->pb.buf_end;
1324 int size = end - start;
1325 int pb_size = (((intptr_t)start + size / 3) & (~3)) - (intptr_t)start;
1326 int tex_size = (size - 2 * pb_size) & (~3);
1328 set_put_bits_buffer_size(&s->pb, pb_size);
1329 init_put_bits(&s->tex_pb, start + pb_size, tex_size);
1330 init_put_bits(&s->pb2, start + pb_size + tex_size, pb_size);
1333 void ff_mpeg4_merge_partitions(MpegEncContext *s)
1335 const int pb2_len = put_bits_count(&s->pb2);
1336 const int tex_pb_len = put_bits_count(&s->tex_pb);
1337 const int bits = put_bits_count(&s->pb);
1339 if (s->pict_type == AV_PICTURE_TYPE_I) {
1340 put_bits(&s->pb, 19, DC_MARKER);
1341 s->misc_bits += 19 + pb2_len + bits - s->last_bits;
1342 s->i_tex_bits += tex_pb_len;
1344 put_bits(&s->pb, 17, MOTION_MARKER);
1345 s->misc_bits += 17 + pb2_len;
1346 s->mv_bits += bits - s->last_bits;
1347 s->p_tex_bits += tex_pb_len;
1350 flush_put_bits(&s->pb2);
1351 flush_put_bits(&s->tex_pb);
1353 set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
1354 ff_copy_bits(&s->pb, s->pb2.buf, pb2_len);
1355 ff_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
1356 s->last_bits = put_bits_count(&s->pb);
1359 void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
1361 int mb_num_bits = av_log2(s->mb_num - 1) + 1;
1363 put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
1364 put_bits(&s->pb, 1, 1);
1366 put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y * s->mb_width);
1367 put_bits(&s->pb, s->quant_precision, s->qscale);
1368 put_bits(&s->pb, 1, 0); /* no HEC */
1371 #define OFFSET(x) offsetof(MpegEncContext, x)
1372 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1373 static const AVOption options[] = {
1374 { "data_partitioning", "Use data partitioning.", OFFSET(data_partitioning), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1375 { "alternate_scan", "Enable alternate scantable.", OFFSET(alternate_scan), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1377 FF_MPEG4_PROFILE_OPTS
1381 static const AVClass mpeg4enc_class = {
1382 .class_name = "MPEG4 encoder",
1383 .item_name = av_default_item_name,
1385 .version = LIBAVUTIL_VERSION_INT,
1388 AVCodec ff_mpeg4_encoder = {
1390 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
1391 .type = AVMEDIA_TYPE_VIDEO,
1392 .id = AV_CODEC_ID_MPEG4,
1393 .priv_data_size = sizeof(MpegEncContext),
1394 .init = encode_init,
1395 .encode2 = ff_mpv_encode_picture,
1396 .close = ff_mpv_encode_end,
1397 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
1398 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
1399 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
1400 .priv_class = &mpeg4enc_class,