3 * Copyright (c) 2000,2001 Fabrice Bellard
4 * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
6 * This file is part of Libav.
8 * Libav is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * Libav is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "libavutil/attributes.h"
24 #include "libavutil/log.h"
25 #include "libavutil/opt.h"
26 #include "mpegvideo.h"
28 #include "mpeg4video.h"
30 /* The uni_DCtab_* tables below contain unified bits+length tables to encode DC
31 * differences in mpeg4. Unified in the sense that the specification specifies
32 * this encoding in several steps. */
33 static uint8_t uni_DCtab_lum_len[512];
34 static uint8_t uni_DCtab_chrom_len[512];
35 static uint16_t uni_DCtab_lum_bits[512];
36 static uint16_t uni_DCtab_chrom_bits[512];
38 /* Unified encoding tables for run length encoding of coefficients.
39 * Unified in the sense that the specification specifies the encoding in several steps. */
40 static uint32_t uni_mpeg4_intra_rl_bits[64 * 64 * 2 * 2];
41 static uint8_t uni_mpeg4_intra_rl_len[64 * 64 * 2 * 2];
42 static uint32_t uni_mpeg4_inter_rl_bits[64 * 64 * 2 * 2];
43 static uint8_t uni_mpeg4_inter_rl_len[64 * 64 * 2 * 2];
45 //#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 + (run) * 256 + (level))
46 //#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 * 64 + (run) + (level) * 64)
47 #define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 * 64 + (run) * 128 + (level))
60 * Return the number of bits that encoding the 8x8 block in block would need.
61 * @param[in] block_last_index last index in scantable order that refers to a non zero element in block.
63 static inline int get_block_rate(MpegEncContext *s, int16_t block[64],
64 int block_last_index, uint8_t scantable[64])
70 for (j = 1; j <= block_last_index; j++) {
71 const int index = scantable[j];
72 int level = block[index];
75 if ((level & (~127)) == 0) {
76 if (j < block_last_index)
77 rate += s->intra_ac_vlc_length[UNI_AC_ENC_INDEX(j - last - 1, level)];
79 rate += s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j - last - 1, level)];
81 rate += s->ac_esc_length;
91 * Restore the ac coefficients in block that have been changed by decide_ac_pred().
92 * This function also restores s->block_last_index.
93 * @param[in,out] block MB coefficients, these will be restored
94 * @param[in] dir ac prediction direction for each 8x8 block
95 * @param[out] st scantable for each 8x8 block
96 * @param[in] zigzag_last_index index referring to the last non zero coefficient in zigzag order
98 static inline void restore_ac_coeffs(MpegEncContext *s, int16_t block[6][64],
99 const int dir[6], uint8_t *st[6],
100 const int zigzag_last_index[6])
103 memcpy(s->block_last_index, zigzag_last_index, sizeof(int) * 6);
105 for (n = 0; n < 6; n++) {
106 int16_t *ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
108 st[n] = s->intra_scantable.permutated;
111 for (i = 1; i < 8; i++)
112 block[n][s->dsp.idct_permutation[i]] = ac_val[i + 8];
114 /* left prediction */
115 for (i = 1; i < 8; i++)
116 block[n][s->dsp.idct_permutation[i << 3]] = ac_val[i];
122 * Return the optimal value (0 or 1) for the ac_pred element for the given MB in mpeg4.
123 * This function will also update s->block_last_index and s->ac_val.
124 * @param[in,out] block MB coefficients, these will be updated if 1 is returned
125 * @param[in] dir ac prediction direction for each 8x8 block
126 * @param[out] st scantable for each 8x8 block
127 * @param[out] zigzag_last_index index referring to the last non zero coefficient in zigzag order
129 static inline int decide_ac_pred(MpegEncContext *s, int16_t block[6][64],
130 const int dir[6], uint8_t *st[6],
131 int zigzag_last_index[6])
135 int8_t *const qscale_table = s->current_picture.qscale_table;
137 memcpy(zigzag_last_index, s->block_last_index, sizeof(int) * 6);
139 for (n = 0; n < 6; n++) {
140 int16_t *ac_val, *ac_val1;
142 score -= get_block_rate(s, block[n], s->block_last_index[n],
143 s->intra_scantable.permutated);
145 ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
148 const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
150 ac_val -= s->block_wrap[n] * 16;
151 if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) {
153 for (i = 1; i < 8; i++) {
154 const int level = block[n][s->dsp.idct_permutation[i]];
155 block[n][s->dsp.idct_permutation[i]] = level - ac_val[i + 8];
156 ac_val1[i] = block[n][s->dsp.idct_permutation[i << 3]];
157 ac_val1[i + 8] = level;
160 /* different qscale, we must rescale */
161 for (i = 1; i < 8; i++) {
162 const int level = block[n][s->dsp.idct_permutation[i]];
163 block[n][s->dsp.idct_permutation[i]] = level - ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
164 ac_val1[i] = block[n][s->dsp.idct_permutation[i << 3]];
165 ac_val1[i + 8] = level;
168 st[n] = s->intra_h_scantable.permutated;
170 const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
171 /* left prediction */
173 if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) {
175 for (i = 1; i < 8; i++) {
176 const int level = block[n][s->dsp.idct_permutation[i << 3]];
177 block[n][s->dsp.idct_permutation[i << 3]] = level - ac_val[i];
179 ac_val1[i + 8] = block[n][s->dsp.idct_permutation[i]];
182 /* different qscale, we must rescale */
183 for (i = 1; i < 8; i++) {
184 const int level = block[n][s->dsp.idct_permutation[i << 3]];
185 block[n][s->dsp.idct_permutation[i << 3]] = level - ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
187 ac_val1[i + 8] = block[n][s->dsp.idct_permutation[i]];
190 st[n] = s->intra_v_scantable.permutated;
193 for (i = 63; i > 0; i--) // FIXME optimize
194 if (block[n][st[n][i]])
196 s->block_last_index[n] = i;
198 score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
204 restore_ac_coeffs(s, block, dir, st, zigzag_last_index);
210 * modify mb_type & qscale so that encoding is acually possible in mpeg4
212 void ff_clean_mpeg4_qscales(MpegEncContext *s)
215 int8_t *const qscale_table = s->current_picture.qscale_table;
217 ff_clean_h263_qscales(s);
219 if (s->pict_type == AV_PICTURE_TYPE_B) {
221 /* ok, come on, this isn't funny anymore, there's more code for
222 * handling this mpeg4 mess than for the actual adaptive quantization */
224 for (i = 0; i < s->mb_num; i++) {
225 int mb_xy = s->mb_index2xy[i];
226 odd += qscale_table[mb_xy] & 1;
229 if (2 * odd > s->mb_num)
234 for (i = 0; i < s->mb_num; i++) {
235 int mb_xy = s->mb_index2xy[i];
236 if ((qscale_table[mb_xy] & 1) != odd)
237 qscale_table[mb_xy]++;
238 if (qscale_table[mb_xy] > 31)
239 qscale_table[mb_xy] = 31;
242 for (i = 1; i < s->mb_num; i++) {
243 int mb_xy = s->mb_index2xy[i];
244 if (qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i - 1]] &&
245 (s->mb_type[mb_xy] & CANDIDATE_MB_TYPE_DIRECT)) {
246 s->mb_type[mb_xy] |= CANDIDATE_MB_TYPE_BIDIR;
253 * Encode the dc value.
254 * @param n block index (0-3 are luma, 4-5 are chroma)
256 static inline void mpeg4_encode_dc(PutBitContext *s, int level, int n)
259 /* DC will overflow if level is outside the [-255,255] range. */
263 put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
266 put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
270 /* find number of bits */
280 put_bits(&s->pb, ff_mpeg4_DCtab_lum[size][1], ff_mpeg4_DCtab_lum[size][0]);
283 put_bits(&s->pb, ff_mpeg4_DCtab_chrom[size][1], ff_mpeg4_DCtab_chrom[size][0]);
286 /* encode remaining bits */
289 level = (-level) ^ ((1 << size) - 1);
290 put_bits(&s->pb, size, level);
292 put_bits(&s->pb, 1, 1);
297 static inline int mpeg4_get_dc_length(int level, int n)
300 return uni_DCtab_lum_len[level + 256];
302 return uni_DCtab_chrom_len[level + 256];
306 * Encode an 8x8 block.
307 * @param n block index (0-3 are luma, 4-5 are chroma)
309 static inline void mpeg4_encode_block(MpegEncContext *s,
310 int16_t *block, int n, int intra_dc,
311 uint8_t *scan_table, PutBitContext *dc_pb,
312 PutBitContext *ac_pb)
314 int i, last_non_zero;
317 const int last_index = s->block_last_index[n];
319 if (s->mb_intra) { // Note gcc (3.2.1 at least) will optimize this away
320 /* mpeg4 based DC predictor */
321 mpeg4_encode_dc(dc_pb, intra_dc, n);
325 bits_tab = uni_mpeg4_intra_rl_bits;
326 len_tab = uni_mpeg4_intra_rl_len;
331 bits_tab = uni_mpeg4_inter_rl_bits;
332 len_tab = uni_mpeg4_inter_rl_len;
336 last_non_zero = i - 1;
337 for (; i < last_index; i++) {
338 int level = block[scan_table[i]];
340 int run = i - last_non_zero - 1;
342 if ((level & (~127)) == 0) {
343 const int index = UNI_MPEG4_ENC_INDEX(0, run, level);
344 put_bits(ac_pb, len_tab[index], bits_tab[index]);
347 7 + 2 + 1 + 6 + 1 + 12 + 1,
348 (3 << 23) + (3 << 21) + (0 << 20) + (run << 14) +
349 (1 << 13) + (((level - 64) & 0xfff) << 1) + 1);
354 /* if (i <= last_index) */ {
355 int level = block[scan_table[i]];
356 int run = i - last_non_zero - 1;
358 if ((level & (~127)) == 0) {
359 const int index = UNI_MPEG4_ENC_INDEX(1, run, level);
360 put_bits(ac_pb, len_tab[index], bits_tab[index]);
363 7 + 2 + 1 + 6 + 1 + 12 + 1,
364 (3 << 23) + (3 << 21) + (1 << 20) + (run << 14) +
365 (1 << 13) + (((level - 64) & 0xfff) << 1) + 1);
370 static int mpeg4_get_block_length(MpegEncContext *s,
371 int16_t *block, int n,
372 int intra_dc, uint8_t *scan_table)
374 int i, last_non_zero;
376 const int last_index = s->block_last_index[n];
379 if (s->mb_intra) { // Note gcc (3.2.1 at least) will optimize this away
380 /* mpeg4 based DC predictor */
381 len += mpeg4_get_dc_length(intra_dc, n);
385 len_tab = uni_mpeg4_intra_rl_len;
390 len_tab = uni_mpeg4_inter_rl_len;
394 last_non_zero = i - 1;
395 for (; i < last_index; i++) {
396 int level = block[scan_table[i]];
398 int run = i - last_non_zero - 1;
400 if ((level & (~127)) == 0) {
401 const int index = UNI_MPEG4_ENC_INDEX(0, run, level);
402 len += len_tab[index];
404 len += 7 + 2 + 1 + 6 + 1 + 12 + 1;
409 /* if (i <= last_index) */ {
410 int level = block[scan_table[i]];
411 int run = i - last_non_zero - 1;
413 if ((level & (~127)) == 0) {
414 const int index = UNI_MPEG4_ENC_INDEX(1, run, level);
415 len += len_tab[index];
417 len += 7 + 2 + 1 + 6 + 1 + 12 + 1;
424 static inline void mpeg4_encode_blocks(MpegEncContext *s, int16_t block[6][64],
425 int intra_dc[6], uint8_t **scan_table,
426 PutBitContext *dc_pb,
427 PutBitContext *ac_pb)
432 if (s->flags2 & CODEC_FLAG2_NO_OUTPUT) {
433 for (i = 0; i < 6; i++)
434 skip_put_bits(&s->pb,
435 mpeg4_get_block_length(s, block[i], i,
436 intra_dc[i], scan_table[i]));
438 /* encode each block */
439 for (i = 0; i < 6; i++)
440 mpeg4_encode_block(s, block[i], i,
441 intra_dc[i], scan_table[i], dc_pb, ac_pb);
444 if (s->flags2 & CODEC_FLAG2_NO_OUTPUT) {
445 for (i = 0; i < 6; i++)
446 skip_put_bits(&s->pb,
447 mpeg4_get_block_length(s, block[i], i, 0,
448 s->intra_scantable.permutated));
450 /* encode each block */
451 for (i = 0; i < 6; i++)
452 mpeg4_encode_block(s, block[i], i, 0,
453 s->intra_scantable.permutated, dc_pb, ac_pb);
458 static inline int get_b_cbp(MpegEncContext *s, int16_t block[6][64],
459 int motion_x, int motion_y, int mb_type)
463 if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {
465 const int lambda = s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
467 for (i = 0; i < 6; i++) {
468 if (s->coded_score[i] < 0) {
469 score += s->coded_score[i];
476 if ((motion_x | motion_y | s->dquant | mb_type) == 0)
477 zero_score -= 4; // 2 * MV + mb_type + cbp bit
479 zero_score *= lambda;
480 if (zero_score <= score)
484 for (i = 0; i < 6; i++) {
485 if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i)) & 1) == 0) {
486 s->block_last_index[i] = -1;
487 s->dsp.clear_block(s->block[i]);
491 for (i = 0; i < 6; i++) {
492 if (s->block_last_index[i] >= 0)
499 // FIXME this is duplicated to h263.c
500 static const int dquant_code[5] = { 1, 0, 9, 2, 3 };
502 void ff_mpeg4_encode_mb(MpegEncContext *s, int16_t block[6][64],
503 int motion_x, int motion_y)
505 int cbpc, cbpy, pred_x, pred_y;
506 PutBitContext *const pb2 = s->data_partitioning ? &s->pb2 : &s->pb;
507 PutBitContext *const tex_pb = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B ? &s->tex_pb : &s->pb;
508 PutBitContext *const dc_pb = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_I ? &s->pb2 : &s->pb;
509 const int interleaved_stats = (s->flags & CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
514 if (s->pict_type == AV_PICTURE_TYPE_B) {
515 /* convert from mv_dir to type */
516 static const int mb_type_table[8] = { -1, 3, 2, 1, -1, -1, -1, 0 };
517 int mb_type = mb_type_table[s->mv_dir];
520 for (i = 0; i < 2; i++)
521 s->last_mv[i][0][0] =
522 s->last_mv[i][0][1] =
523 s->last_mv[i][1][0] =
524 s->last_mv[i][1][1] = 0;
527 assert(s->dquant >= -2 && s->dquant <= 2);
528 assert((s->dquant & 1) == 0);
529 assert(mb_type >= 0);
531 /* nothing to do if this MB was skipped in the next P Frame */
532 if (s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]) { // FIXME avoid DCT & ...
538 s->mv_dir = MV_DIR_FORWARD; // doesn't matter
539 s->qscale -= s->dquant;
540 // s->mb_skipped = 1;
545 cbp = get_b_cbp(s, block, motion_x, motion_y, mb_type);
547 if ((cbp | motion_x | motion_y | mb_type) == 0) {
548 /* direct MB with MV={0,0} */
549 assert(s->dquant == 0);
551 put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
553 if (interleaved_stats) {
561 put_bits(&s->pb, 1, 0); /* mb coded modb1=0 */
562 put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ // FIXME merge
563 put_bits(&s->pb, mb_type + 1, 1); // this table is so simple that we don't need it :)
565 put_bits(&s->pb, 6, cbp);
567 if (cbp && mb_type) {
569 put_bits(&s->pb, 2, (s->dquant >> 2) + 3);
571 put_bits(&s->pb, 1, 0);
573 s->qscale -= s->dquant;
575 if (!s->progressive_sequence) {
577 put_bits(&s->pb, 1, s->interlaced_dct);
578 if (mb_type) // not direct mode
579 put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
582 if (interleaved_stats)
583 s->misc_bits += get_bits_diff(s);
586 assert(s->mv_dir & MV_DIRECT);
587 ff_h263_encode_motion_vector(s, motion_x, motion_y, 1);
591 assert(mb_type > 0 && mb_type < 4);
592 if (s->mv_type != MV_TYPE_FIELD) {
593 if (s->mv_dir & MV_DIR_FORWARD) {
594 ff_h263_encode_motion_vector(s,
595 s->mv[0][0][0] - s->last_mv[0][0][0],
596 s->mv[0][0][1] - s->last_mv[0][0][1],
598 s->last_mv[0][0][0] =
599 s->last_mv[0][1][0] = s->mv[0][0][0];
600 s->last_mv[0][0][1] =
601 s->last_mv[0][1][1] = s->mv[0][0][1];
604 if (s->mv_dir & MV_DIR_BACKWARD) {
605 ff_h263_encode_motion_vector(s,
606 s->mv[1][0][0] - s->last_mv[1][0][0],
607 s->mv[1][0][1] - s->last_mv[1][0][1],
609 s->last_mv[1][0][0] =
610 s->last_mv[1][1][0] = s->mv[1][0][0];
611 s->last_mv[1][0][1] =
612 s->last_mv[1][1][1] = s->mv[1][0][1];
616 if (s->mv_dir & MV_DIR_FORWARD) {
617 put_bits(&s->pb, 1, s->field_select[0][0]);
618 put_bits(&s->pb, 1, s->field_select[0][1]);
620 if (s->mv_dir & MV_DIR_BACKWARD) {
621 put_bits(&s->pb, 1, s->field_select[1][0]);
622 put_bits(&s->pb, 1, s->field_select[1][1]);
624 if (s->mv_dir & MV_DIR_FORWARD) {
625 for (i = 0; i < 2; i++) {
626 ff_h263_encode_motion_vector(s,
627 s->mv[0][i][0] - s->last_mv[0][i][0],
628 s->mv[0][i][1] - s->last_mv[0][i][1] / 2,
630 s->last_mv[0][i][0] = s->mv[0][i][0];
631 s->last_mv[0][i][1] = s->mv[0][i][1] * 2;
635 if (s->mv_dir & MV_DIR_BACKWARD) {
636 for (i = 0; i < 2; i++) {
637 ff_h263_encode_motion_vector(s,
638 s->mv[1][i][0] - s->last_mv[1][i][0],
639 s->mv[1][i][1] - s->last_mv[1][i][1] / 2,
641 s->last_mv[1][i][0] = s->mv[1][i][0];
642 s->last_mv[1][i][1] = s->mv[1][i][1] * 2;
649 if (interleaved_stats)
650 s->mv_bits += get_bits_diff(s);
652 mpeg4_encode_blocks(s, block, NULL, NULL, NULL, &s->pb);
654 if (interleaved_stats)
655 s->p_tex_bits += get_bits_diff(s);
656 } else { /* s->pict_type==AV_PICTURE_TYPE_B */
657 cbp = get_p_cbp(s, block, motion_x, motion_y);
659 if ((cbp | motion_x | motion_y | s->dquant) == 0 &&
660 s->mv_type == MV_TYPE_16X16) {
661 /* check if the B frames can skip it too, as we must skip it
662 * if we skip here why didn't they just compress
663 * the skip-mb bits instead of reusing them ?! */
664 if (s->max_b_frames > 0) {
671 if (x + 16 > s->width)
673 if (y + 16 > s->height)
676 offset = x + y * s->linesize;
677 p_pic = s->new_picture.f.data[0] + offset;
680 for (i = 0; i < s->max_b_frames; i++) {
683 Picture *pic = s->reordered_input_picture[i + 1];
685 if (!pic || pic->f.pict_type != AV_PICTURE_TYPE_B)
688 b_pic = pic->f.data[0] + offset;
690 b_pic += INPLACE_OFFSET;
691 diff = s->dsp.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
692 if (diff > s->qscale * 70) { // FIXME check that 70 is optimal
700 if (s->mb_skipped == 1) {
701 /* skip macroblock */
702 put_bits(&s->pb, 1, 1);
704 if (interleaved_stats) {
714 put_bits(&s->pb, 1, 0); /* mb coded */
718 if (s->mv_type == MV_TYPE_16X16) {
722 ff_h263_inter_MCBPC_bits[cbpc],
723 ff_h263_inter_MCBPC_code[cbpc]);
725 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
727 put_bits(pb2, 2, dquant_code[s->dquant + 2]);
729 if (!s->progressive_sequence) {
731 put_bits(pb2, 1, s->interlaced_dct);
735 if (interleaved_stats)
736 s->misc_bits += get_bits_diff(s);
738 /* motion vectors: 16x16 mode */
739 ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
741 ff_h263_encode_motion_vector(s,
745 } else if (s->mv_type == MV_TYPE_FIELD) {
749 ff_h263_inter_MCBPC_bits[cbpc],
750 ff_h263_inter_MCBPC_code[cbpc]);
752 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
754 put_bits(pb2, 2, dquant_code[s->dquant + 2]);
756 assert(!s->progressive_sequence);
758 put_bits(pb2, 1, s->interlaced_dct);
761 if (interleaved_stats)
762 s->misc_bits += get_bits_diff(s);
764 /* motion vectors: 16x8 interlaced mode */
765 ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
768 put_bits(&s->pb, 1, s->field_select[0][0]);
769 put_bits(&s->pb, 1, s->field_select[0][1]);
771 ff_h263_encode_motion_vector(s,
772 s->mv[0][0][0] - pred_x,
773 s->mv[0][0][1] - pred_y,
775 ff_h263_encode_motion_vector(s,
776 s->mv[0][1][0] - pred_x,
777 s->mv[0][1][1] - pred_y,
780 assert(s->mv_type == MV_TYPE_8X8);
782 ff_h263_inter_MCBPC_bits[cbpc + 16],
783 ff_h263_inter_MCBPC_code[cbpc + 16]);
784 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
786 if (!s->progressive_sequence && cbp)
787 put_bits(pb2, 1, s->interlaced_dct);
789 if (interleaved_stats)
790 s->misc_bits += get_bits_diff(s);
792 for (i = 0; i < 4; i++) {
793 /* motion vectors: 8x8 mode*/
794 ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
796 ff_h263_encode_motion_vector(s,
797 s->current_picture.motion_val[0][s->block_index[i]][0] - pred_x,
798 s->current_picture.motion_val[0][s->block_index[i]][1] - pred_y,
803 if (interleaved_stats)
804 s->mv_bits += get_bits_diff(s);
806 mpeg4_encode_blocks(s, block, NULL, NULL, NULL, tex_pb);
808 if (interleaved_stats)
809 s->p_tex_bits += get_bits_diff(s);
815 int dc_diff[6]; // dc values with the dc prediction subtracted
816 int dir[6]; // prediction direction
817 int zigzag_last_index[6];
818 uint8_t *scan_table[6];
821 for (i = 0; i < 6; i++)
822 dc_diff[i] = ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
824 if (s->flags & CODEC_FLAG_AC_PRED) {
825 s->ac_pred = decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
827 for (i = 0; i < 6; i++)
828 scan_table[i] = s->intra_scantable.permutated;
833 for (i = 0; i < 6; i++)
834 if (s->block_last_index[i] >= 1)
838 if (s->pict_type == AV_PICTURE_TYPE_I) {
842 ff_h263_intra_MCBPC_bits[cbpc],
843 ff_h263_intra_MCBPC_code[cbpc]);
847 put_bits(&s->pb, 1, 0); /* mb coded */
849 ff_h263_inter_MCBPC_bits[cbpc + 4],
850 ff_h263_inter_MCBPC_code[cbpc + 4]);
852 put_bits(pb2, 1, s->ac_pred);
854 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
856 put_bits(dc_pb, 2, dquant_code[s->dquant + 2]);
858 if (!s->progressive_sequence)
859 put_bits(dc_pb, 1, s->interlaced_dct);
861 if (interleaved_stats)
862 s->misc_bits += get_bits_diff(s);
864 mpeg4_encode_blocks(s, block, dc_diff, scan_table, dc_pb, tex_pb);
866 if (interleaved_stats)
867 s->i_tex_bits += get_bits_diff(s);
870 /* restore ac coeffs & last_index stuff
871 * if we messed them up with the prediction */
873 restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
878 * add mpeg4 stuffing bits (01...1)
880 void ff_mpeg4_stuffing(PutBitContext *pbc)
884 length = (-put_bits_count(pbc)) & 7;
886 put_bits(pbc, length, (1 << length) - 1);
889 /* must be called before writing the header */
890 void ff_set_mpeg4_time(MpegEncContext *s)
892 if (s->pict_type == AV_PICTURE_TYPE_B) {
893 ff_mpeg4_init_direct_mv(s);
895 s->last_time_base = s->time_base;
896 s->time_base = s->time / s->avctx->time_base.den;
900 static void mpeg4_encode_gop_header(MpegEncContext *s)
902 int hours, minutes, seconds;
905 put_bits(&s->pb, 16, 0);
906 put_bits(&s->pb, 16, GOP_STARTCODE);
908 time = s->current_picture_ptr->f.pts;
909 if (s->reordered_input_picture[1])
910 time = FFMIN(time, s->reordered_input_picture[1]->f.pts);
911 time = time * s->avctx->time_base.num;
913 seconds = time / s->avctx->time_base.den;
914 minutes = seconds / 60;
916 hours = minutes / 60;
920 put_bits(&s->pb, 5, hours);
921 put_bits(&s->pb, 6, minutes);
922 put_bits(&s->pb, 1, 1);
923 put_bits(&s->pb, 6, seconds);
925 put_bits(&s->pb, 1, !!(s->flags & CODEC_FLAG_CLOSED_GOP));
926 put_bits(&s->pb, 1, 0); // broken link == NO
928 s->last_time_base = time / s->avctx->time_base.den;
930 ff_mpeg4_stuffing(&s->pb);
933 static void mpeg4_encode_visual_object_header(MpegEncContext *s)
935 int profile_and_level_indication;
938 if (s->avctx->profile != FF_PROFILE_UNKNOWN) {
939 profile_and_level_indication = s->avctx->profile << 4;
940 } else if (s->max_b_frames || s->quarter_sample) {
941 profile_and_level_indication = 0xF0; // adv simple
943 profile_and_level_indication = 0x00; // simple
946 if (s->avctx->level != FF_LEVEL_UNKNOWN)
947 profile_and_level_indication |= s->avctx->level;
949 profile_and_level_indication |= 1; // level 1
951 if (profile_and_level_indication >> 4 == 0xF)
958 put_bits(&s->pb, 16, 0);
959 put_bits(&s->pb, 16, VOS_STARTCODE);
961 put_bits(&s->pb, 8, profile_and_level_indication);
963 put_bits(&s->pb, 16, 0);
964 put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
966 put_bits(&s->pb, 1, 1);
967 put_bits(&s->pb, 4, vo_ver_id);
968 put_bits(&s->pb, 3, 1); // priority
970 put_bits(&s->pb, 4, 1); // visual obj type== video obj
972 put_bits(&s->pb, 1, 0); // video signal type == no clue // FIXME
974 ff_mpeg4_stuffing(&s->pb);
977 static void mpeg4_encode_vol_header(MpegEncContext *s,
983 if (!CONFIG_MPEG4_ENCODER)
986 if (s->max_b_frames || s->quarter_sample) {
988 s->vo_type = ADV_SIMPLE_VO_TYPE;
991 s->vo_type = SIMPLE_VO_TYPE;
994 put_bits(&s->pb, 16, 0);
995 put_bits(&s->pb, 16, 0x100 + vo_number); /* video obj */
996 put_bits(&s->pb, 16, 0);
997 put_bits(&s->pb, 16, 0x120 + vol_number); /* video obj layer */
999 put_bits(&s->pb, 1, 0); /* random access vol */
1000 put_bits(&s->pb, 8, s->vo_type); /* video obj type indication */
1001 if (s->workaround_bugs & FF_BUG_MS) {
1002 put_bits(&s->pb, 1, 0); /* is obj layer id= no */
1004 put_bits(&s->pb, 1, 1); /* is obj layer id= yes */
1005 put_bits(&s->pb, 4, vo_ver_id); /* is obj layer ver id */
1006 put_bits(&s->pb, 3, 1); /* is obj layer priority */
1009 s->aspect_ratio_info = ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio);
1011 put_bits(&s->pb, 4, s->aspect_ratio_info); /* aspect ratio info */
1012 if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
1013 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
1014 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
1017 if (s->workaround_bugs & FF_BUG_MS) {
1018 put_bits(&s->pb, 1, 0); /* vol control parameters= no @@@ */
1020 put_bits(&s->pb, 1, 1); /* vol control parameters= yes */
1021 put_bits(&s->pb, 2, 1); /* chroma format YUV 420/YV12 */
1022 put_bits(&s->pb, 1, s->low_delay);
1023 put_bits(&s->pb, 1, 0); /* vbv parameters= no */
1026 put_bits(&s->pb, 2, RECT_SHAPE); /* vol shape= rectangle */
1027 put_bits(&s->pb, 1, 1); /* marker bit */
1029 put_bits(&s->pb, 16, s->avctx->time_base.den);
1030 if (s->time_increment_bits < 1)
1031 s->time_increment_bits = 1;
1032 put_bits(&s->pb, 1, 1); /* marker bit */
1033 put_bits(&s->pb, 1, 0); /* fixed vop rate=no */
1034 put_bits(&s->pb, 1, 1); /* marker bit */
1035 put_bits(&s->pb, 13, s->width); /* vol width */
1036 put_bits(&s->pb, 1, 1); /* marker bit */
1037 put_bits(&s->pb, 13, s->height); /* vol height */
1038 put_bits(&s->pb, 1, 1); /* marker bit */
1039 put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1040 put_bits(&s->pb, 1, 1); /* obmc disable */
1042 put_bits(&s->pb, 1, 0); /* sprite enable */
1044 put_bits(&s->pb, 2, 0); /* sprite enable */
1046 put_bits(&s->pb, 1, 0); /* not 8 bit == false */
1047 put_bits(&s->pb, 1, s->mpeg_quant); /* quant type= (0=h263 style)*/
1049 if (s->mpeg_quant) {
1050 ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
1051 ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
1055 put_bits(&s->pb, 1, s->quarter_sample);
1056 put_bits(&s->pb, 1, 1); /* complexity estimation disable */
1057 put_bits(&s->pb, 1, s->rtp_mode ? 0 : 1); /* resync marker disable */
1058 put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1059 if (s->data_partitioning)
1060 put_bits(&s->pb, 1, 0); /* no rvlc */
1062 if (vo_ver_id != 1) {
1063 put_bits(&s->pb, 1, 0); /* newpred */
1064 put_bits(&s->pb, 1, 0); /* reduced res vop */
1066 put_bits(&s->pb, 1, 0); /* scalability */
1068 ff_mpeg4_stuffing(&s->pb);
1071 if (!(s->flags & CODEC_FLAG_BITEXACT)) {
1072 put_bits(&s->pb, 16, 0);
1073 put_bits(&s->pb, 16, 0x1B2); /* user_data */
1074 avpriv_put_string(&s->pb, LIBAVCODEC_IDENT, 0);
1078 /* write mpeg4 VOP header */
1079 void ff_mpeg4_encode_picture_header(MpegEncContext *s, int picture_number)
1082 int time_div, time_mod;
1084 if (s->pict_type == AV_PICTURE_TYPE_I) {
1085 if (!(s->flags & CODEC_FLAG_GLOBAL_HEADER)) {
1086 if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT) // HACK, the reference sw is buggy
1087 mpeg4_encode_visual_object_header(s);
1088 if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number == 0) // HACK, the reference sw is buggy
1089 mpeg4_encode_vol_header(s, 0, 0);
1091 if (!(s->workaround_bugs & FF_BUG_MS))
1092 mpeg4_encode_gop_header(s);
1095 s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
1097 put_bits(&s->pb, 16, 0); /* vop header */
1098 put_bits(&s->pb, 16, VOP_STARTCODE); /* vop header */
1099 put_bits(&s->pb, 2, s->pict_type - 1); /* pict type: I = 0 , P = 1 */
1101 assert(s->time >= 0);
1102 time_div = s->time / s->avctx->time_base.den;
1103 time_mod = s->time % s->avctx->time_base.den;
1104 time_incr = time_div - s->last_time_base;
1105 assert(time_incr >= 0);
1107 put_bits(&s->pb, 1, 1);
1109 put_bits(&s->pb, 1, 0);
1111 put_bits(&s->pb, 1, 1); /* marker */
1112 put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
1113 put_bits(&s->pb, 1, 1); /* marker */
1114 put_bits(&s->pb, 1, 1); /* vop coded */
1115 if (s->pict_type == AV_PICTURE_TYPE_P) {
1116 put_bits(&s->pb, 1, s->no_rounding); /* rounding type */
1118 put_bits(&s->pb, 3, 0); /* intra dc VLC threshold */
1119 if (!s->progressive_sequence) {
1120 put_bits(&s->pb, 1, s->current_picture_ptr->f.top_field_first);
1121 put_bits(&s->pb, 1, s->alternate_scan);
1123 // FIXME sprite stuff
1125 put_bits(&s->pb, 5, s->qscale);
1127 if (s->pict_type != AV_PICTURE_TYPE_I)
1128 put_bits(&s->pb, 3, s->f_code); /* fcode_for */
1129 if (s->pict_type == AV_PICTURE_TYPE_B)
1130 put_bits(&s->pb, 3, s->b_code); /* fcode_back */
1133 static av_cold void init_uni_dc_tab(void)
1135 int level, uni_code, uni_len;
1137 for (level = -256; level < 256; level++) {
1139 /* find number of bits */
1148 l = (-level) ^ ((1 << size) - 1);
1153 uni_code = ff_mpeg4_DCtab_lum[size][0];
1154 uni_len = ff_mpeg4_DCtab_lum[size][1];
1166 uni_DCtab_lum_bits[level + 256] = uni_code;
1167 uni_DCtab_lum_len[level + 256] = uni_len;
1170 uni_code = ff_mpeg4_DCtab_chrom[size][0];
1171 uni_len = ff_mpeg4_DCtab_chrom[size][1];
1183 uni_DCtab_chrom_bits[level + 256] = uni_code;
1184 uni_DCtab_chrom_len[level + 256] = uni_len;
1188 static av_cold void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab,
1191 int slevel, run, last;
1193 assert(MAX_LEVEL >= 64);
1194 assert(MAX_RUN >= 63);
1196 for (slevel = -64; slevel < 64; slevel++) {
1199 for (run = 0; run < 64; run++) {
1200 for (last = 0; last <= 1; last++) {
1201 const int index = UNI_MPEG4_ENC_INDEX(last, run, slevel + 64);
1202 int level = slevel < 0 ? -slevel : slevel;
1203 int sign = slevel < 0 ? 1 : 0;
1204 int bits, len, code;
1207 len_tab[index] = 100;
1210 code = get_rl_index(rl, last, run, level);
1211 bits = rl->table_vlc[code][0];
1212 len = rl->table_vlc[code][1];
1213 bits = bits * 2 + sign;
1216 if (code != rl->n && len < len_tab[index]) {
1217 bits_tab[index] = bits;
1218 len_tab[index] = len;
1221 bits = rl->table_vlc[rl->n][0];
1222 len = rl->table_vlc[rl->n][1];
1225 level1 = level - rl->max_level[last][run];
1227 code = get_rl_index(rl, last, run, level1);
1228 bits <<= rl->table_vlc[code][1];
1229 len += rl->table_vlc[code][1];
1230 bits += rl->table_vlc[code][0];
1231 bits = bits * 2 + sign;
1234 if (code != rl->n && len < len_tab[index]) {
1235 bits_tab[index] = bits;
1236 len_tab[index] = len;
1240 bits = rl->table_vlc[rl->n][0];
1241 len = rl->table_vlc[rl->n][1];
1242 bits = bits * 4 + 2;
1244 run1 = run - rl->max_run[last][level] - 1;
1246 code = get_rl_index(rl, last, run1, level);
1247 bits <<= rl->table_vlc[code][1];
1248 len += rl->table_vlc[code][1];
1249 bits += rl->table_vlc[code][0];
1250 bits = bits * 2 + sign;
1253 if (code != rl->n && len < len_tab[index]) {
1254 bits_tab[index] = bits;
1255 len_tab[index] = len;
1259 bits = rl->table_vlc[rl->n][0];
1260 len = rl->table_vlc[rl->n][1];
1261 bits = bits * 4 + 3;
1263 bits = bits * 2 + last;
1265 bits = bits * 64 + run;
1267 bits = bits * 2 + 1;
1269 bits = bits * 4096 + (slevel & 0xfff);
1271 bits = bits * 2 + 1;
1274 if (len < len_tab[index]) {
1275 bits_tab[index] = bits;
1276 len_tab[index] = len;
1283 static av_cold int encode_init(AVCodecContext *avctx)
1285 MpegEncContext *s = avctx->priv_data;
1287 static int done = 0;
1289 if ((ret = ff_MPV_encode_init(avctx)) < 0)
1297 ff_init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
1299 init_uni_mpeg4_rl_tab(&ff_mpeg4_rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1300 init_uni_mpeg4_rl_tab(&ff_h263_rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1303 s->min_qcoeff = -2048;
1304 s->max_qcoeff = 2047;
1305 s->intra_ac_vlc_length = uni_mpeg4_intra_rl_len;
1306 s->intra_ac_vlc_last_length = uni_mpeg4_intra_rl_len + 128 * 64;
1307 s->inter_ac_vlc_length = uni_mpeg4_inter_rl_len;
1308 s->inter_ac_vlc_last_length = uni_mpeg4_inter_rl_len + 128 * 64;
1309 s->luma_dc_vlc_length = uni_DCtab_lum_len;
1310 s->ac_esc_length = 7 + 2 + 1 + 6 + 1 + 12 + 1;
1311 s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
1312 s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
1314 if (s->flags & CODEC_FLAG_GLOBAL_HEADER) {
1315 s->avctx->extradata = av_malloc(1024);
1316 init_put_bits(&s->pb, s->avctx->extradata, 1024);
1318 if (!(s->workaround_bugs & FF_BUG_MS))
1319 mpeg4_encode_visual_object_header(s);
1320 mpeg4_encode_vol_header(s, 0, 0);
1322 // ff_mpeg4_stuffing(&s->pb); ?
1323 flush_put_bits(&s->pb);
1324 s->avctx->extradata_size = (put_bits_count(&s->pb) + 7) >> 3;
1329 void ff_mpeg4_init_partitions(MpegEncContext *s)
1331 uint8_t *start = put_bits_ptr(&s->pb);
1332 uint8_t *end = s->pb.buf_end;
1333 int size = end - start;
1334 int pb_size = (((intptr_t)start + size / 3) & (~3)) - (intptr_t)start;
1335 int tex_size = (size - 2 * pb_size) & (~3);
1337 set_put_bits_buffer_size(&s->pb, pb_size);
1338 init_put_bits(&s->tex_pb, start + pb_size, tex_size);
1339 init_put_bits(&s->pb2, start + pb_size + tex_size, pb_size);
1342 void ff_mpeg4_merge_partitions(MpegEncContext *s)
1344 const int pb2_len = put_bits_count(&s->pb2);
1345 const int tex_pb_len = put_bits_count(&s->tex_pb);
1346 const int bits = put_bits_count(&s->pb);
1348 if (s->pict_type == AV_PICTURE_TYPE_I) {
1349 put_bits(&s->pb, 19, DC_MARKER);
1350 s->misc_bits += 19 + pb2_len + bits - s->last_bits;
1351 s->i_tex_bits += tex_pb_len;
1353 put_bits(&s->pb, 17, MOTION_MARKER);
1354 s->misc_bits += 17 + pb2_len;
1355 s->mv_bits += bits - s->last_bits;
1356 s->p_tex_bits += tex_pb_len;
1359 flush_put_bits(&s->pb2);
1360 flush_put_bits(&s->tex_pb);
1362 set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
1363 avpriv_copy_bits(&s->pb, s->pb2.buf, pb2_len);
1364 avpriv_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
1365 s->last_bits = put_bits_count(&s->pb);
1368 void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
1370 int mb_num_bits = av_log2(s->mb_num - 1) + 1;
1372 put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
1373 put_bits(&s->pb, 1, 1);
1375 put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y * s->mb_width);
1376 put_bits(&s->pb, s->quant_precision, s->qscale);
1377 put_bits(&s->pb, 1, 0); /* no HEC */
1380 #define OFFSET(x) offsetof(MpegEncContext, x)
1381 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1382 static const AVOption options[] = {
1383 { "data_partitioning", "Use data partitioning.", OFFSET(data_partitioning), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1384 { "alternate_scan", "Enable alternate scantable.", OFFSET(alternate_scan), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1389 static const AVClass mpeg4enc_class = {
1390 .class_name = "MPEG4 encoder",
1391 .item_name = av_default_item_name,
1393 .version = LIBAVUTIL_VERSION_INT,
1396 AVCodec ff_mpeg4_encoder = {
1398 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
1399 .type = AVMEDIA_TYPE_VIDEO,
1400 .id = AV_CODEC_ID_MPEG4,
1401 .priv_data_size = sizeof(MpegEncContext),
1402 .init = encode_init,
1403 .encode2 = ff_MPV_encode_picture,
1404 .close = ff_MPV_encode_end,
1405 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
1406 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
1407 .priv_class = &mpeg4enc_class,