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"
31 /* The uni_DCtab_* tables below contain unified bits+length tables to encode DC
32 * differences in MPEG-4. Unified in the sense that the specification specifies
33 * this encoding in several steps. */
34 static uint8_t uni_DCtab_lum_len[512];
35 static uint8_t uni_DCtab_chrom_len[512];
36 static uint16_t uni_DCtab_lum_bits[512];
37 static uint16_t uni_DCtab_chrom_bits[512];
39 /* Unified encoding tables for run length encoding of coefficients.
40 * Unified in the sense that the specification specifies the encoding in several steps. */
41 static uint32_t uni_mpeg4_intra_rl_bits[64 * 64 * 2 * 2];
42 static uint8_t uni_mpeg4_intra_rl_len[64 * 64 * 2 * 2];
43 static uint32_t uni_mpeg4_inter_rl_bits[64 * 64 * 2 * 2];
44 static uint8_t uni_mpeg4_inter_rl_len[64 * 64 * 2 * 2];
46 //#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 + (run) * 256 + (level))
47 //#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 * 64 + (run) + (level) * 64)
48 #define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 * 64 + (run) * 128 + (level))
61 * Return the number of bits that encoding the 8x8 block in block would need.
62 * @param[in] block_last_index last index in scantable order that refers to a non zero element in block.
64 static inline int get_block_rate(MpegEncContext *s, int16_t block[64],
65 int block_last_index, uint8_t scantable[64])
71 for (j = 1; j <= block_last_index; j++) {
72 const int index = scantable[j];
73 int level = block[index];
76 if ((level & (~127)) == 0) {
77 if (j < block_last_index)
78 rate += s->intra_ac_vlc_length[UNI_AC_ENC_INDEX(j - last - 1, level)];
80 rate += s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j - last - 1, level)];
82 rate += s->ac_esc_length;
92 * Restore the ac coefficients in block that have been changed by decide_ac_pred().
93 * This function also restores s->block_last_index.
94 * @param[in,out] block MB coefficients, these will be restored
95 * @param[in] dir ac prediction direction for each 8x8 block
96 * @param[out] st scantable for each 8x8 block
97 * @param[in] zigzag_last_index index referring to the last non zero coefficient in zigzag order
99 static inline void restore_ac_coeffs(MpegEncContext *s, int16_t block[6][64],
100 const int dir[6], uint8_t *st[6],
101 const int zigzag_last_index[6])
104 memcpy(s->block_last_index, zigzag_last_index, sizeof(int) * 6);
106 for (n = 0; n < 6; n++) {
107 int16_t *ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
109 st[n] = s->intra_scantable.permutated;
112 for (i = 1; i < 8; i++)
113 block[n][s->idsp.idct_permutation[i]] = ac_val[i + 8];
115 /* left prediction */
116 for (i = 1; i < 8; i++)
117 block[n][s->idsp.idct_permutation[i << 3]] = ac_val[i];
123 * Return the optimal value (0 or 1) for the ac_pred element for the given MB in MPEG-4.
124 * This function will also update s->block_last_index and s->ac_val.
125 * @param[in,out] block MB coefficients, these will be updated if 1 is returned
126 * @param[in] dir ac prediction direction for each 8x8 block
127 * @param[out] st scantable for each 8x8 block
128 * @param[out] zigzag_last_index index referring to the last non zero coefficient in zigzag order
130 static inline int decide_ac_pred(MpegEncContext *s, int16_t block[6][64],
131 const int dir[6], uint8_t *st[6],
132 int zigzag_last_index[6])
136 int8_t *const qscale_table = s->current_picture.qscale_table;
138 memcpy(zigzag_last_index, s->block_last_index, sizeof(int) * 6);
140 for (n = 0; n < 6; n++) {
141 int16_t *ac_val, *ac_val1;
143 score -= get_block_rate(s, block[n], s->block_last_index[n],
144 s->intra_scantable.permutated);
146 ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
149 const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
151 ac_val -= s->block_wrap[n] * 16;
152 if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) {
154 for (i = 1; i < 8; i++) {
155 const int level = block[n][s->idsp.idct_permutation[i]];
156 block[n][s->idsp.idct_permutation[i]] = level - ac_val[i + 8];
157 ac_val1[i] = block[n][s->idsp.idct_permutation[i << 3]];
158 ac_val1[i + 8] = level;
161 /* different qscale, we must rescale */
162 for (i = 1; i < 8; i++) {
163 const int level = block[n][s->idsp.idct_permutation[i]];
164 block[n][s->idsp.idct_permutation[i]] = level - ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
165 ac_val1[i] = block[n][s->idsp.idct_permutation[i << 3]];
166 ac_val1[i + 8] = level;
169 st[n] = s->intra_h_scantable.permutated;
171 const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
172 /* left prediction */
174 if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) {
176 for (i = 1; i < 8; i++) {
177 const int level = block[n][s->idsp.idct_permutation[i << 3]];
178 block[n][s->idsp.idct_permutation[i << 3]] = level - ac_val[i];
180 ac_val1[i + 8] = block[n][s->idsp.idct_permutation[i]];
183 /* different qscale, we must rescale */
184 for (i = 1; i < 8; i++) {
185 const int level = block[n][s->idsp.idct_permutation[i << 3]];
186 block[n][s->idsp.idct_permutation[i << 3]] = level - ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
188 ac_val1[i + 8] = block[n][s->idsp.idct_permutation[i]];
191 st[n] = s->intra_v_scantable.permutated;
194 for (i = 63; i > 0; i--) // FIXME optimize
195 if (block[n][st[n][i]])
197 s->block_last_index[n] = i;
199 score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
205 restore_ac_coeffs(s, block, dir, st, zigzag_last_index);
211 * modify mb_type & qscale so that encoding is actually possible in MPEG-4
213 void ff_clean_mpeg4_qscales(MpegEncContext *s)
216 int8_t *const qscale_table = s->current_picture.qscale_table;
218 ff_clean_h263_qscales(s);
220 if (s->pict_type == AV_PICTURE_TYPE_B) {
222 /* ok, come on, this isn't funny anymore, there's more code for
223 * handling this MPEG-4 mess than for the actual adaptive quantization */
225 for (i = 0; i < s->mb_num; i++) {
226 int mb_xy = s->mb_index2xy[i];
227 odd += qscale_table[mb_xy] & 1;
230 if (2 * odd > s->mb_num)
235 for (i = 0; i < s->mb_num; i++) {
236 int mb_xy = s->mb_index2xy[i];
237 if ((qscale_table[mb_xy] & 1) != odd)
238 qscale_table[mb_xy]++;
239 if (qscale_table[mb_xy] > 31)
240 qscale_table[mb_xy] = 31;
243 for (i = 1; i < s->mb_num; i++) {
244 int mb_xy = s->mb_index2xy[i];
245 if (qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i - 1]] &&
246 (s->mb_type[mb_xy] & CANDIDATE_MB_TYPE_DIRECT)) {
247 s->mb_type[mb_xy] |= CANDIDATE_MB_TYPE_BIDIR;
254 * Encode the dc value.
255 * @param n block index (0-3 are luma, 4-5 are chroma)
257 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 static inline int mpeg4_get_dc_length(int level, int n)
273 return uni_DCtab_lum_len[level + 256];
275 return uni_DCtab_chrom_len[level + 256];
279 * Encode an 8x8 block.
280 * @param n block index (0-3 are luma, 4-5 are chroma)
282 static inline void mpeg4_encode_block(MpegEncContext *s,
283 int16_t *block, int n, int intra_dc,
284 uint8_t *scan_table, PutBitContext *dc_pb,
285 PutBitContext *ac_pb)
287 int i, last_non_zero;
290 const int last_index = s->block_last_index[n];
292 if (s->mb_intra) { // Note gcc (3.2.1 at least) will optimize this away
293 /* MPEG-4 based DC predictor */
294 mpeg4_encode_dc(dc_pb, intra_dc, n);
298 bits_tab = uni_mpeg4_intra_rl_bits;
299 len_tab = uni_mpeg4_intra_rl_len;
304 bits_tab = uni_mpeg4_inter_rl_bits;
305 len_tab = uni_mpeg4_inter_rl_len;
309 last_non_zero = i - 1;
310 for (; i < last_index; i++) {
311 int level = block[scan_table[i]];
313 int run = i - last_non_zero - 1;
315 if ((level & (~127)) == 0) {
316 const int index = UNI_MPEG4_ENC_INDEX(0, run, level);
317 put_bits(ac_pb, len_tab[index], bits_tab[index]);
320 7 + 2 + 1 + 6 + 1 + 12 + 1,
321 (3 << 23) + (3 << 21) + (0 << 20) + (run << 14) +
322 (1 << 13) + (((level - 64) & 0xfff) << 1) + 1);
327 /* if (i <= last_index) */ {
328 int level = block[scan_table[i]];
329 int run = i - last_non_zero - 1;
331 if ((level & (~127)) == 0) {
332 const int index = UNI_MPEG4_ENC_INDEX(1, run, level);
333 put_bits(ac_pb, len_tab[index], bits_tab[index]);
336 7 + 2 + 1 + 6 + 1 + 12 + 1,
337 (3 << 23) + (3 << 21) + (1 << 20) + (run << 14) +
338 (1 << 13) + (((level - 64) & 0xfff) << 1) + 1);
343 static int mpeg4_get_block_length(MpegEncContext *s,
344 int16_t *block, int n,
345 int intra_dc, uint8_t *scan_table)
347 int i, last_non_zero;
349 const int last_index = s->block_last_index[n];
352 if (s->mb_intra) { // Note gcc (3.2.1 at least) will optimize this away
353 /* MPEG-4 based DC predictor */
354 len += mpeg4_get_dc_length(intra_dc, n);
358 len_tab = uni_mpeg4_intra_rl_len;
363 len_tab = uni_mpeg4_inter_rl_len;
367 last_non_zero = i - 1;
368 for (; i < last_index; i++) {
369 int level = block[scan_table[i]];
371 int run = i - last_non_zero - 1;
373 if ((level & (~127)) == 0) {
374 const int index = UNI_MPEG4_ENC_INDEX(0, run, level);
375 len += len_tab[index];
377 len += 7 + 2 + 1 + 6 + 1 + 12 + 1;
382 /* if (i <= last_index) */ {
383 int level = block[scan_table[i]];
384 int run = i - last_non_zero - 1;
386 if ((level & (~127)) == 0) {
387 const int index = UNI_MPEG4_ENC_INDEX(1, run, level);
388 len += len_tab[index];
390 len += 7 + 2 + 1 + 6 + 1 + 12 + 1;
397 static inline void mpeg4_encode_blocks(MpegEncContext *s, int16_t block[6][64],
398 int intra_dc[6], uint8_t **scan_table,
399 PutBitContext *dc_pb,
400 PutBitContext *ac_pb)
405 if (s->avctx->flags2 & AV_CODEC_FLAG2_NO_OUTPUT) {
406 for (i = 0; i < 6; i++)
407 skip_put_bits(&s->pb,
408 mpeg4_get_block_length(s, block[i], i,
409 intra_dc[i], scan_table[i]));
411 /* encode each block */
412 for (i = 0; i < 6; i++)
413 mpeg4_encode_block(s, block[i], i,
414 intra_dc[i], scan_table[i], dc_pb, ac_pb);
417 if (s->avctx->flags2 & AV_CODEC_FLAG2_NO_OUTPUT) {
418 for (i = 0; i < 6; i++)
419 skip_put_bits(&s->pb,
420 mpeg4_get_block_length(s, block[i], i, 0,
421 s->intra_scantable.permutated));
423 /* encode each block */
424 for (i = 0; i < 6; i++)
425 mpeg4_encode_block(s, block[i], i, 0,
426 s->intra_scantable.permutated, dc_pb, ac_pb);
431 static inline int get_b_cbp(MpegEncContext *s, int16_t block[6][64],
432 int motion_x, int motion_y, int mb_type)
436 if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {
438 const int lambda = s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
440 for (i = 0; i < 6; i++) {
441 if (s->coded_score[i] < 0) {
442 score += s->coded_score[i];
449 if ((motion_x | motion_y | s->dquant | mb_type) == 0)
450 zero_score -= 4; // 2 * MV + mb_type + cbp bit
452 zero_score *= lambda;
453 if (zero_score <= score)
457 for (i = 0; i < 6; i++) {
458 if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i)) & 1) == 0) {
459 s->block_last_index[i] = -1;
460 s->bdsp.clear_block(s->block[i]);
464 for (i = 0; i < 6; i++) {
465 if (s->block_last_index[i] >= 0)
472 // FIXME this is duplicated to h263.c
473 static const int dquant_code[5] = { 1, 0, 9, 2, 3 };
475 void ff_mpeg4_encode_mb(MpegEncContext *s, int16_t block[6][64],
476 int motion_x, int motion_y)
478 int cbpc, cbpy, pred_x, pred_y;
479 PutBitContext *const pb2 = s->data_partitioning ? &s->pb2 : &s->pb;
480 PutBitContext *const tex_pb = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B ? &s->tex_pb : &s->pb;
481 PutBitContext *const dc_pb = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_I ? &s->pb2 : &s->pb;
482 const int interleaved_stats = (s->avctx->flags & AV_CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
487 if (s->pict_type == AV_PICTURE_TYPE_B) {
488 /* convert from mv_dir to type */
489 static const int mb_type_table[8] = { -1, 3, 2, 1, -1, -1, -1, 0 };
490 int mb_type = mb_type_table[s->mv_dir];
493 for (i = 0; i < 2; i++)
494 s->last_mv[i][0][0] =
495 s->last_mv[i][0][1] =
496 s->last_mv[i][1][0] =
497 s->last_mv[i][1][1] = 0;
500 av_assert2(s->dquant >= -2 && s->dquant <= 2);
501 av_assert2((s->dquant & 1) == 0);
502 av_assert2(mb_type >= 0);
504 /* nothing to do if this MB was skipped in the next P-frame */
505 if (s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]) { // FIXME avoid DCT & ...
511 s->mv_dir = MV_DIR_FORWARD; // doesn't matter
512 s->qscale -= s->dquant;
513 // s->mb_skipped = 1;
518 cbp = get_b_cbp(s, block, motion_x, motion_y, mb_type);
520 if ((cbp | motion_x | motion_y | mb_type) == 0) {
521 /* direct MB with MV={0,0} */
522 av_assert2(s->dquant == 0);
524 put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
526 if (interleaved_stats) {
534 put_bits(&s->pb, 1, 0); /* mb coded modb1=0 */
535 put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ // FIXME merge
536 put_bits(&s->pb, mb_type + 1, 1); // this table is so simple that we don't need it :)
538 put_bits(&s->pb, 6, cbp);
540 if (cbp && mb_type) {
542 put_bits(&s->pb, 2, (s->dquant >> 2) + 3);
544 put_bits(&s->pb, 1, 0);
546 s->qscale -= s->dquant;
548 if (!s->progressive_sequence) {
550 put_bits(&s->pb, 1, s->interlaced_dct);
551 if (mb_type) // not direct mode
552 put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
555 if (interleaved_stats)
556 s->misc_bits += get_bits_diff(s);
559 av_assert2(s->mv_dir & MV_DIRECT);
560 ff_h263_encode_motion_vector(s, motion_x, motion_y, 1);
564 av_assert2(mb_type > 0 && mb_type < 4);
565 if (s->mv_type != MV_TYPE_FIELD) {
566 if (s->mv_dir & MV_DIR_FORWARD) {
567 ff_h263_encode_motion_vector(s,
568 s->mv[0][0][0] - s->last_mv[0][0][0],
569 s->mv[0][0][1] - s->last_mv[0][0][1],
571 s->last_mv[0][0][0] =
572 s->last_mv[0][1][0] = s->mv[0][0][0];
573 s->last_mv[0][0][1] =
574 s->last_mv[0][1][1] = s->mv[0][0][1];
577 if (s->mv_dir & MV_DIR_BACKWARD) {
578 ff_h263_encode_motion_vector(s,
579 s->mv[1][0][0] - s->last_mv[1][0][0],
580 s->mv[1][0][1] - s->last_mv[1][0][1],
582 s->last_mv[1][0][0] =
583 s->last_mv[1][1][0] = s->mv[1][0][0];
584 s->last_mv[1][0][1] =
585 s->last_mv[1][1][1] = s->mv[1][0][1];
589 if (s->mv_dir & MV_DIR_FORWARD) {
590 put_bits(&s->pb, 1, s->field_select[0][0]);
591 put_bits(&s->pb, 1, s->field_select[0][1]);
593 if (s->mv_dir & MV_DIR_BACKWARD) {
594 put_bits(&s->pb, 1, s->field_select[1][0]);
595 put_bits(&s->pb, 1, s->field_select[1][1]);
597 if (s->mv_dir & MV_DIR_FORWARD) {
598 for (i = 0; i < 2; i++) {
599 ff_h263_encode_motion_vector(s,
600 s->mv[0][i][0] - s->last_mv[0][i][0],
601 s->mv[0][i][1] - s->last_mv[0][i][1] / 2,
603 s->last_mv[0][i][0] = s->mv[0][i][0];
604 s->last_mv[0][i][1] = s->mv[0][i][1] * 2;
608 if (s->mv_dir & MV_DIR_BACKWARD) {
609 for (i = 0; i < 2; i++) {
610 ff_h263_encode_motion_vector(s,
611 s->mv[1][i][0] - s->last_mv[1][i][0],
612 s->mv[1][i][1] - s->last_mv[1][i][1] / 2,
614 s->last_mv[1][i][0] = s->mv[1][i][0];
615 s->last_mv[1][i][1] = s->mv[1][i][1] * 2;
622 if (interleaved_stats)
623 s->mv_bits += get_bits_diff(s);
625 mpeg4_encode_blocks(s, block, NULL, NULL, NULL, &s->pb);
627 if (interleaved_stats)
628 s->p_tex_bits += get_bits_diff(s);
629 } else { /* s->pict_type==AV_PICTURE_TYPE_B */
630 cbp = get_p_cbp(s, block, motion_x, motion_y);
632 if ((cbp | motion_x | motion_y | s->dquant) == 0 &&
633 s->mv_type == MV_TYPE_16X16) {
634 /* Check if the B-frames can skip it too, as we must skip it
635 * if we skip here why didn't they just compress
636 * the skip-mb bits instead of reusing them ?! */
637 if (s->max_b_frames > 0) {
645 offset = x + y * s->linesize;
646 p_pic = s->new_picture.f->data[0] + offset;
649 for (i = 0; i < s->max_b_frames; i++) {
652 Picture *pic = s->reordered_input_picture[i + 1];
654 if (!pic || pic->f->pict_type != AV_PICTURE_TYPE_B)
657 b_pic = pic->f->data[0] + offset;
659 b_pic += INPLACE_OFFSET;
661 if (x + 16 > s->width || y + 16 > s->height) {
663 int xe = FFMIN(16, s->width - x);
664 int ye = FFMIN(16, s->height - y);
666 for (y1 = 0; y1 < ye; y1++) {
667 for (x1 = 0; x1 < xe; x1++) {
668 diff += FFABS(p_pic[x1 + y1 * s->linesize] - b_pic[x1 + y1 * s->linesize]);
671 diff = diff * 256 / (xe * ye);
673 diff = s->mecc.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
675 if (diff > s->qscale * 70) { // FIXME check that 70 is optimal
683 if (s->mb_skipped == 1) {
684 /* skip macroblock */
685 put_bits(&s->pb, 1, 1);
687 if (interleaved_stats) {
697 put_bits(&s->pb, 1, 0); /* mb coded */
701 if (s->mv_type == MV_TYPE_16X16) {
705 ff_h263_inter_MCBPC_bits[cbpc],
706 ff_h263_inter_MCBPC_code[cbpc]);
708 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
710 put_bits(pb2, 2, dquant_code[s->dquant + 2]);
712 if (!s->progressive_sequence) {
714 put_bits(pb2, 1, s->interlaced_dct);
718 if (interleaved_stats)
719 s->misc_bits += get_bits_diff(s);
721 /* motion vectors: 16x16 mode */
722 ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
724 ff_h263_encode_motion_vector(s,
728 } else if (s->mv_type == MV_TYPE_FIELD) {
732 ff_h263_inter_MCBPC_bits[cbpc],
733 ff_h263_inter_MCBPC_code[cbpc]);
735 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
737 put_bits(pb2, 2, dquant_code[s->dquant + 2]);
739 av_assert2(!s->progressive_sequence);
741 put_bits(pb2, 1, s->interlaced_dct);
744 if (interleaved_stats)
745 s->misc_bits += get_bits_diff(s);
747 /* motion vectors: 16x8 interlaced mode */
748 ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
751 put_bits(&s->pb, 1, s->field_select[0][0]);
752 put_bits(&s->pb, 1, s->field_select[0][1]);
754 ff_h263_encode_motion_vector(s,
755 s->mv[0][0][0] - pred_x,
756 s->mv[0][0][1] - pred_y,
758 ff_h263_encode_motion_vector(s,
759 s->mv[0][1][0] - pred_x,
760 s->mv[0][1][1] - pred_y,
763 av_assert2(s->mv_type == MV_TYPE_8X8);
765 ff_h263_inter_MCBPC_bits[cbpc + 16],
766 ff_h263_inter_MCBPC_code[cbpc + 16]);
767 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
769 if (!s->progressive_sequence && cbp)
770 put_bits(pb2, 1, s->interlaced_dct);
772 if (interleaved_stats)
773 s->misc_bits += get_bits_diff(s);
775 for (i = 0; i < 4; i++) {
776 /* motion vectors: 8x8 mode*/
777 ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
779 ff_h263_encode_motion_vector(s,
780 s->current_picture.motion_val[0][s->block_index[i]][0] - pred_x,
781 s->current_picture.motion_val[0][s->block_index[i]][1] - pred_y,
786 if (interleaved_stats)
787 s->mv_bits += get_bits_diff(s);
789 mpeg4_encode_blocks(s, block, NULL, NULL, NULL, tex_pb);
791 if (interleaved_stats)
792 s->p_tex_bits += get_bits_diff(s);
798 int dc_diff[6]; // dc values with the dc prediction subtracted
799 int dir[6]; // prediction direction
800 int zigzag_last_index[6];
801 uint8_t *scan_table[6];
804 for (i = 0; i < 6; i++)
805 dc_diff[i] = ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
807 if (s->avctx->flags & AV_CODEC_FLAG_AC_PRED) {
808 s->ac_pred = decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
810 for (i = 0; i < 6; i++)
811 scan_table[i] = s->intra_scantable.permutated;
816 for (i = 0; i < 6; i++)
817 if (s->block_last_index[i] >= 1)
821 if (s->pict_type == AV_PICTURE_TYPE_I) {
825 ff_h263_intra_MCBPC_bits[cbpc],
826 ff_h263_intra_MCBPC_code[cbpc]);
830 put_bits(&s->pb, 1, 0); /* mb coded */
832 ff_h263_inter_MCBPC_bits[cbpc + 4],
833 ff_h263_inter_MCBPC_code[cbpc + 4]);
835 put_bits(pb2, 1, s->ac_pred);
837 put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
839 put_bits(dc_pb, 2, dquant_code[s->dquant + 2]);
841 if (!s->progressive_sequence)
842 put_bits(dc_pb, 1, s->interlaced_dct);
844 if (interleaved_stats)
845 s->misc_bits += get_bits_diff(s);
847 mpeg4_encode_blocks(s, block, dc_diff, scan_table, dc_pb, tex_pb);
849 if (interleaved_stats)
850 s->i_tex_bits += get_bits_diff(s);
853 /* restore ac coeffs & last_index stuff
854 * if we messed them up with the prediction */
856 restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
861 * add MPEG-4 stuffing bits (01...1)
863 void ff_mpeg4_stuffing(PutBitContext *pbc)
867 length = (-put_bits_count(pbc)) & 7;
869 put_bits(pbc, length, (1 << length) - 1);
872 /* must be called before writing the header */
873 void ff_set_mpeg4_time(MpegEncContext *s)
875 if (s->pict_type == AV_PICTURE_TYPE_B) {
876 ff_mpeg4_init_direct_mv(s);
878 s->last_time_base = s->time_base;
879 s->time_base = FFUDIV(s->time, s->avctx->time_base.den);
883 static void mpeg4_encode_gop_header(MpegEncContext *s)
885 int hours, minutes, seconds;
888 put_bits(&s->pb, 16, 0);
889 put_bits(&s->pb, 16, GOP_STARTCODE);
891 time = s->current_picture_ptr->f->pts;
892 if (s->reordered_input_picture[1])
893 time = FFMIN(time, s->reordered_input_picture[1]->f->pts);
894 time = time * s->avctx->time_base.num;
895 s->last_time_base = FFUDIV(time, s->avctx->time_base.den);
897 seconds = FFUDIV(time, s->avctx->time_base.den);
898 minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60);
899 hours = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60);
900 hours = FFUMOD(hours , 24);
902 put_bits(&s->pb, 5, hours);
903 put_bits(&s->pb, 6, minutes);
904 put_bits(&s->pb, 1, 1);
905 put_bits(&s->pb, 6, seconds);
907 put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
908 put_bits(&s->pb, 1, 0); // broken link == NO
910 ff_mpeg4_stuffing(&s->pb);
913 static void mpeg4_encode_visual_object_header(MpegEncContext *s)
915 int profile_and_level_indication;
918 if (s->avctx->profile != FF_PROFILE_UNKNOWN) {
919 profile_and_level_indication = s->avctx->profile << 4;
920 } else if (s->max_b_frames || s->quarter_sample) {
921 profile_and_level_indication = 0xF0; // adv simple
923 profile_and_level_indication = 0x00; // simple
926 if (s->avctx->level != FF_LEVEL_UNKNOWN)
927 profile_and_level_indication |= s->avctx->level;
929 profile_and_level_indication |= 1; // level 1
931 if (profile_and_level_indication >> 4 == 0xF)
938 put_bits(&s->pb, 16, 0);
939 put_bits(&s->pb, 16, VOS_STARTCODE);
941 put_bits(&s->pb, 8, profile_and_level_indication);
943 put_bits(&s->pb, 16, 0);
944 put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
946 put_bits(&s->pb, 1, 1);
947 put_bits(&s->pb, 4, vo_ver_id);
948 put_bits(&s->pb, 3, 1); // priority
950 put_bits(&s->pb, 4, 1); // visual obj type== video obj
952 put_bits(&s->pb, 1, 0); // video signal type == no clue // FIXME
954 ff_mpeg4_stuffing(&s->pb);
957 static void mpeg4_encode_vol_header(MpegEncContext *s,
963 if (!CONFIG_MPEG4_ENCODER)
966 if (s->max_b_frames || s->quarter_sample) {
968 s->vo_type = ADV_SIMPLE_VO_TYPE;
971 s->vo_type = SIMPLE_VO_TYPE;
974 put_bits(&s->pb, 16, 0);
975 put_bits(&s->pb, 16, 0x100 + vo_number); /* video obj */
976 put_bits(&s->pb, 16, 0);
977 put_bits(&s->pb, 16, 0x120 + vol_number); /* video obj layer */
979 put_bits(&s->pb, 1, 0); /* random access vol */
980 put_bits(&s->pb, 8, s->vo_type); /* video obj type indication */
981 if (s->workaround_bugs & FF_BUG_MS) {
982 put_bits(&s->pb, 1, 0); /* is obj layer id= no */
984 put_bits(&s->pb, 1, 1); /* is obj layer id= yes */
985 put_bits(&s->pb, 4, vo_ver_id); /* is obj layer ver id */
986 put_bits(&s->pb, 3, 1); /* is obj layer priority */
989 s->aspect_ratio_info = ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio);
991 put_bits(&s->pb, 4, s->aspect_ratio_info); /* aspect ratio info */
992 if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
993 av_reduce(&s->avctx->sample_aspect_ratio.num, &s->avctx->sample_aspect_ratio.den,
994 s->avctx->sample_aspect_ratio.num, s->avctx->sample_aspect_ratio.den, 255);
995 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
996 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
999 if (s->workaround_bugs & FF_BUG_MS) {
1000 put_bits(&s->pb, 1, 0); /* vol control parameters= no @@@ */
1002 put_bits(&s->pb, 1, 1); /* vol control parameters= yes */
1003 put_bits(&s->pb, 2, 1); /* chroma format YUV 420/YV12 */
1004 put_bits(&s->pb, 1, s->low_delay);
1005 put_bits(&s->pb, 1, 0); /* vbv parameters= no */
1008 put_bits(&s->pb, 2, RECT_SHAPE); /* vol shape= rectangle */
1009 put_bits(&s->pb, 1, 1); /* marker bit */
1011 put_bits(&s->pb, 16, s->avctx->time_base.den);
1012 if (s->time_increment_bits < 1)
1013 s->time_increment_bits = 1;
1014 put_bits(&s->pb, 1, 1); /* marker bit */
1015 put_bits(&s->pb, 1, 0); /* fixed vop rate=no */
1016 put_bits(&s->pb, 1, 1); /* marker bit */
1017 put_bits(&s->pb, 13, s->width); /* vol width */
1018 put_bits(&s->pb, 1, 1); /* marker bit */
1019 put_bits(&s->pb, 13, s->height); /* vol height */
1020 put_bits(&s->pb, 1, 1); /* marker bit */
1021 put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1022 put_bits(&s->pb, 1, 1); /* obmc disable */
1024 put_bits(&s->pb, 1, 0); /* sprite enable */
1026 put_bits(&s->pb, 2, 0); /* sprite enable */
1028 put_bits(&s->pb, 1, 0); /* not 8 bit == false */
1029 put_bits(&s->pb, 1, s->mpeg_quant); /* quant type = (0 = H.263 style) */
1031 if (s->mpeg_quant) {
1032 ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
1033 ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
1037 put_bits(&s->pb, 1, s->quarter_sample);
1038 put_bits(&s->pb, 1, 1); /* complexity estimation disable */
1039 put_bits(&s->pb, 1, s->rtp_mode ? 0 : 1); /* resync marker disable */
1040 put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1041 if (s->data_partitioning)
1042 put_bits(&s->pb, 1, 0); /* no rvlc */
1044 if (vo_ver_id != 1) {
1045 put_bits(&s->pb, 1, 0); /* newpred */
1046 put_bits(&s->pb, 1, 0); /* reduced res vop */
1048 put_bits(&s->pb, 1, 0); /* scalability */
1050 ff_mpeg4_stuffing(&s->pb);
1053 if (!(s->avctx->flags & AV_CODEC_FLAG_BITEXACT)) {
1054 put_bits(&s->pb, 16, 0);
1055 put_bits(&s->pb, 16, 0x1B2); /* user_data */
1056 avpriv_put_string(&s->pb, LIBAVCODEC_IDENT, 0);
1060 /* write MPEG-4 VOP header */
1061 int ff_mpeg4_encode_picture_header(MpegEncContext *s, int picture_number)
1064 int64_t time_div, time_mod;
1066 if (s->pict_type == AV_PICTURE_TYPE_I) {
1067 if (!(s->avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1068 if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT) // HACK, the reference sw is buggy
1069 mpeg4_encode_visual_object_header(s);
1070 if (s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number == 0) // HACK, the reference sw is buggy
1071 mpeg4_encode_vol_header(s, 0, 0);
1073 if (!(s->workaround_bugs & FF_BUG_MS))
1074 mpeg4_encode_gop_header(s);
1077 s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
1079 put_bits(&s->pb, 16, 0); /* vop header */
1080 put_bits(&s->pb, 16, VOP_STARTCODE); /* vop header */
1081 put_bits(&s->pb, 2, s->pict_type - 1); /* pict type: I = 0 , P = 1 */
1083 time_div = FFUDIV(s->time, s->avctx->time_base.den);
1084 time_mod = FFUMOD(s->time, s->avctx->time_base.den);
1085 time_incr = time_div - s->last_time_base;
1087 // This limits the frame duration to max 1 hour
1088 if (time_incr > 3600) {
1089 av_log(s->avctx, AV_LOG_ERROR, "time_incr %"PRIu64" too large\n", time_incr);
1090 return AVERROR(EINVAL);
1093 put_bits(&s->pb, 1, 1);
1095 put_bits(&s->pb, 1, 0);
1097 put_bits(&s->pb, 1, 1); /* marker */
1098 put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
1099 put_bits(&s->pb, 1, 1); /* marker */
1100 put_bits(&s->pb, 1, 1); /* vop coded */
1101 if (s->pict_type == AV_PICTURE_TYPE_P) {
1102 put_bits(&s->pb, 1, s->no_rounding); /* rounding type */
1104 put_bits(&s->pb, 3, 0); /* intra dc VLC threshold */
1105 if (!s->progressive_sequence) {
1106 put_bits(&s->pb, 1, s->current_picture_ptr->f->top_field_first);
1107 put_bits(&s->pb, 1, s->alternate_scan);
1109 // FIXME sprite stuff
1111 put_bits(&s->pb, 5, s->qscale);
1113 if (s->pict_type != AV_PICTURE_TYPE_I)
1114 put_bits(&s->pb, 3, s->f_code); /* fcode_for */
1115 if (s->pict_type == AV_PICTURE_TYPE_B)
1116 put_bits(&s->pb, 3, s->b_code); /* fcode_back */
1121 static av_cold void init_uni_dc_tab(void)
1123 int level, uni_code, uni_len;
1125 for (level = -256; level < 256; level++) {
1127 /* find number of bits */
1136 l = (-level) ^ ((1 << size) - 1);
1141 uni_code = ff_mpeg4_DCtab_lum[size][0];
1142 uni_len = ff_mpeg4_DCtab_lum[size][1];
1154 uni_DCtab_lum_bits[level + 256] = uni_code;
1155 uni_DCtab_lum_len[level + 256] = uni_len;
1158 uni_code = ff_mpeg4_DCtab_chrom[size][0];
1159 uni_len = ff_mpeg4_DCtab_chrom[size][1];
1171 uni_DCtab_chrom_bits[level + 256] = uni_code;
1172 uni_DCtab_chrom_len[level + 256] = uni_len;
1176 static av_cold void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab,
1179 int slevel, run, last;
1181 av_assert0(MAX_LEVEL >= 64);
1182 av_assert0(MAX_RUN >= 63);
1184 for (slevel = -64; slevel < 64; slevel++) {
1187 for (run = 0; run < 64; run++) {
1188 for (last = 0; last <= 1; last++) {
1189 const int index = UNI_MPEG4_ENC_INDEX(last, run, slevel + 64);
1190 int level = slevel < 0 ? -slevel : slevel;
1191 int sign = slevel < 0 ? 1 : 0;
1192 int bits, len, code;
1195 len_tab[index] = 100;
1198 code = get_rl_index(rl, last, run, level);
1199 bits = rl->table_vlc[code][0];
1200 len = rl->table_vlc[code][1];
1201 bits = bits * 2 + sign;
1204 if (code != rl->n && len < len_tab[index]) {
1205 bits_tab[index] = bits;
1206 len_tab[index] = len;
1209 bits = rl->table_vlc[rl->n][0];
1210 len = rl->table_vlc[rl->n][1];
1213 level1 = level - rl->max_level[last][run];
1215 code = get_rl_index(rl, last, run, level1);
1216 bits <<= rl->table_vlc[code][1];
1217 len += rl->table_vlc[code][1];
1218 bits += rl->table_vlc[code][0];
1219 bits = bits * 2 + sign;
1222 if (code != rl->n && len < len_tab[index]) {
1223 bits_tab[index] = bits;
1224 len_tab[index] = len;
1228 bits = rl->table_vlc[rl->n][0];
1229 len = rl->table_vlc[rl->n][1];
1230 bits = bits * 4 + 2;
1232 run1 = run - rl->max_run[last][level] - 1;
1234 code = get_rl_index(rl, last, run1, level);
1235 bits <<= rl->table_vlc[code][1];
1236 len += rl->table_vlc[code][1];
1237 bits += rl->table_vlc[code][0];
1238 bits = bits * 2 + sign;
1241 if (code != rl->n && len < len_tab[index]) {
1242 bits_tab[index] = bits;
1243 len_tab[index] = len;
1247 bits = rl->table_vlc[rl->n][0];
1248 len = rl->table_vlc[rl->n][1];
1249 bits = bits * 4 + 3;
1251 bits = bits * 2 + last;
1253 bits = bits * 64 + run;
1255 bits = bits * 2 + 1;
1257 bits = bits * 4096 + (slevel & 0xfff);
1259 bits = bits * 2 + 1;
1262 if (len < len_tab[index]) {
1263 bits_tab[index] = bits;
1264 len_tab[index] = len;
1271 static av_cold int encode_init(AVCodecContext *avctx)
1273 MpegEncContext *s = avctx->priv_data;
1275 static int done = 0;
1277 if (avctx->width >= (1<<13) || avctx->height >= (1<<13)) {
1278 av_log(avctx, AV_LOG_ERROR, "dimensions too large for MPEG-4\n");
1279 return AVERROR(EINVAL);
1282 if ((ret = ff_mpv_encode_init(avctx)) < 0)
1290 ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
1292 init_uni_mpeg4_rl_tab(&ff_mpeg4_rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1293 init_uni_mpeg4_rl_tab(&ff_h263_rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1296 s->min_qcoeff = -2048;
1297 s->max_qcoeff = 2047;
1298 s->intra_ac_vlc_length = uni_mpeg4_intra_rl_len;
1299 s->intra_ac_vlc_last_length = uni_mpeg4_intra_rl_len + 128 * 64;
1300 s->inter_ac_vlc_length = uni_mpeg4_inter_rl_len;
1301 s->inter_ac_vlc_last_length = uni_mpeg4_inter_rl_len + 128 * 64;
1302 s->luma_dc_vlc_length = uni_DCtab_lum_len;
1303 s->ac_esc_length = 7 + 2 + 1 + 6 + 1 + 12 + 1;
1304 s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
1305 s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
1307 if (s->avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1308 s->avctx->extradata = av_malloc(1024);
1309 init_put_bits(&s->pb, s->avctx->extradata, 1024);
1311 if (!(s->workaround_bugs & FF_BUG_MS))
1312 mpeg4_encode_visual_object_header(s);
1313 mpeg4_encode_vol_header(s, 0, 0);
1315 // ff_mpeg4_stuffing(&s->pb); ?
1316 flush_put_bits(&s->pb);
1317 s->avctx->extradata_size = (put_bits_count(&s->pb) + 7) >> 3;
1322 void ff_mpeg4_init_partitions(MpegEncContext *s)
1324 uint8_t *start = put_bits_ptr(&s->pb);
1325 uint8_t *end = s->pb.buf_end;
1326 int size = end - start;
1327 int pb_size = (((intptr_t)start + size / 3) & (~3)) - (intptr_t)start;
1328 int tex_size = (size - 2 * pb_size) & (~3);
1330 set_put_bits_buffer_size(&s->pb, pb_size);
1331 init_put_bits(&s->tex_pb, start + pb_size, tex_size);
1332 init_put_bits(&s->pb2, start + pb_size + tex_size, pb_size);
1335 void ff_mpeg4_merge_partitions(MpegEncContext *s)
1337 const int pb2_len = put_bits_count(&s->pb2);
1338 const int tex_pb_len = put_bits_count(&s->tex_pb);
1339 const int bits = put_bits_count(&s->pb);
1341 if (s->pict_type == AV_PICTURE_TYPE_I) {
1342 put_bits(&s->pb, 19, DC_MARKER);
1343 s->misc_bits += 19 + pb2_len + bits - s->last_bits;
1344 s->i_tex_bits += tex_pb_len;
1346 put_bits(&s->pb, 17, MOTION_MARKER);
1347 s->misc_bits += 17 + pb2_len;
1348 s->mv_bits += bits - s->last_bits;
1349 s->p_tex_bits += tex_pb_len;
1352 flush_put_bits(&s->pb2);
1353 flush_put_bits(&s->tex_pb);
1355 set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
1356 avpriv_copy_bits(&s->pb, s->pb2.buf, pb2_len);
1357 avpriv_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
1358 s->last_bits = put_bits_count(&s->pb);
1361 void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
1363 int mb_num_bits = av_log2(s->mb_num - 1) + 1;
1365 put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
1366 put_bits(&s->pb, 1, 1);
1368 put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y * s->mb_width);
1369 put_bits(&s->pb, s->quant_precision, s->qscale);
1370 put_bits(&s->pb, 1, 0); /* no HEC */
1373 #define OFFSET(x) offsetof(MpegEncContext, x)
1374 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1375 static const AVOption options[] = {
1376 { "data_partitioning", "Use data partitioning.", OFFSET(data_partitioning), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1377 { "alternate_scan", "Enable alternate scantable.", OFFSET(alternate_scan), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1382 static const AVClass mpeg4enc_class = {
1383 .class_name = "MPEG4 encoder",
1384 .item_name = av_default_item_name,
1386 .version = LIBAVUTIL_VERSION_INT,
1389 AVCodec ff_mpeg4_encoder = {
1391 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
1392 .type = AVMEDIA_TYPE_VIDEO,
1393 .id = AV_CODEC_ID_MPEG4,
1394 .priv_data_size = sizeof(MpegEncContext),
1395 .init = encode_init,
1396 .encode2 = ff_mpv_encode_picture,
1397 .close = ff_mpv_encode_end,
1398 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
1399 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
1400 .priv_class = &mpeg4enc_class,