3 * Copyright (c) 2000,2001 Fabrice Bellard
4 * Copyright (c) 2002-2004 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
30 #include "libavutil/attributes.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/log.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/timecode.h"
35 #include "libavutil/stereo3d.h"
38 #include "bytestream.h"
41 #include "mpeg12data.h"
42 #include "mpegutils.h"
43 #include "mpegvideo.h"
45 static const uint8_t svcd_scan_offset_placeholder[] = {
46 0x10, 0x0E, 0x00, 0x80, 0x81, 0x00, 0x80,
47 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
50 static uint8_t mv_penalty[MAX_FCODE + 1][MAX_MV * 2 + 1];
51 static uint8_t fcode_tab[MAX_MV * 2 + 1];
53 static uint8_t uni_mpeg1_ac_vlc_len[64 * 64 * 2];
54 static uint8_t uni_mpeg2_ac_vlc_len[64 * 64 * 2];
56 /* simple include everything table for dc, first byte is bits
57 * number next 3 are code */
58 static uint32_t mpeg1_lum_dc_uni[512];
59 static uint32_t mpeg1_chr_dc_uni[512];
61 static uint8_t mpeg1_index_run[2][64];
62 static int8_t mpeg1_max_level[2][64];
64 static av_cold void init_uni_ac_vlc(RLTable *rl, uint8_t *uni_ac_vlc_len)
68 for (i = 0; i < 128; i++) {
73 for (run = 0; run < 64; run++) {
75 int alevel = FFABS(level);
77 if (alevel > rl->max_level[0][run])
78 code = 111; /* rl->n */
80 code = rl->index_run[0][run] + alevel - 1;
82 if (code < 111) { /* rl->n */
83 /* length of VLC and sign */
84 len = rl->table_vlc[code][1] + 1;
86 len = rl->table_vlc[111 /* rl->n */][1] + 6;
94 uni_ac_vlc_len[UNI_AC_ENC_INDEX(run, i)] = len;
99 static int find_frame_rate_index(MpegEncContext *s)
102 AVRational bestq = (AVRational) {0, 0};
104 AVRational target = av_inv_q(s->avctx->time_base);
106 for (i = 1; i < 14; i++) {
107 if (s->avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL &&
111 for (ext.num=1; ext.num <= 4; ext.num++) {
112 for (ext.den=1; ext.den <= 32; ext.den++) {
113 AVRational q = av_mul_q(ext, ff_mpeg12_frame_rate_tab[i]);
115 if (s->codec_id != AV_CODEC_ID_MPEG2VIDEO && (ext.den!=1 || ext.num!=1))
117 if (av_gcd(ext.den, ext.num) != 1)
121 || av_nearer_q(target, bestq, q) < 0
122 || ext.num==1 && ext.den==1 && av_nearer_q(target, bestq, q) == 0) {
124 s->frame_rate_index = i;
125 s->mpeg2_frame_rate_ext.num = ext.num;
126 s->mpeg2_frame_rate_ext.den = ext.den;
132 if (av_cmp_q(target, bestq))
138 static av_cold int encode_init(AVCodecContext *avctx)
140 MpegEncContext *s = avctx->priv_data;
142 if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO && avctx->height > 2800)
143 avctx->thread_count = 1;
145 if (ff_mpv_encode_init(avctx) < 0)
148 if (find_frame_rate_index(s) < 0) {
149 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
150 av_log(avctx, AV_LOG_ERROR, "MPEG1/2 does not support %d/%d fps\n",
151 avctx->time_base.den, avctx->time_base.num);
154 av_log(avctx, AV_LOG_INFO,
155 "MPEG1/2 does not support %d/%d fps, there may be AV sync issues\n",
156 avctx->time_base.den, avctx->time_base.num);
160 if (avctx->profile == FF_PROFILE_UNKNOWN) {
161 if (avctx->level != FF_LEVEL_UNKNOWN) {
162 av_log(avctx, AV_LOG_ERROR, "Set profile and level\n");
166 avctx->profile = s->chroma_format == CHROMA_420 ? 4 : 0;
169 if (avctx->level == FF_LEVEL_UNKNOWN) {
170 if (avctx->profile == 0) { /* 4:2:2 */
171 if (avctx->width <= 720 && avctx->height <= 608)
172 avctx->level = 5; /* Main */
174 avctx->level = 2; /* High */
176 if (avctx->profile != 1 && s->chroma_format != CHROMA_420) {
177 av_log(avctx, AV_LOG_ERROR,
178 "Only High(1) and 4:2:2(0) profiles support 4:2:2 color sampling\n");
181 if (avctx->width <= 720 && avctx->height <= 576)
182 avctx->level = 8; /* Main */
183 else if (avctx->width <= 1440)
184 avctx->level = 6; /* High 1440 */
186 avctx->level = 4; /* High */
190 if ((avctx->width & 0xFFF) == 0 && (avctx->height & 0xFFF) == 1) {
191 av_log(avctx, AV_LOG_ERROR, "Width / Height is invalid for MPEG2\n");
192 return AVERROR(EINVAL);
195 if (s->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL) {
196 if ((avctx->width & 0xFFF) == 0 || (avctx->height & 0xFFF) == 0) {
197 av_log(avctx, AV_LOG_ERROR, "Width or Height are not allowed to be multiples of 4096\n"
198 "add '-strict %d' if you want to use them anyway.\n", FF_COMPLIANCE_UNOFFICIAL);
199 return AVERROR(EINVAL);
203 s->drop_frame_timecode = s->drop_frame_timecode || !!(avctx->flags2 & AV_CODEC_FLAG2_DROP_FRAME_TIMECODE);
204 if (s->drop_frame_timecode)
205 s->tc.flags |= AV_TIMECODE_FLAG_DROPFRAME;
206 if (s->drop_frame_timecode && s->frame_rate_index != 4) {
207 av_log(avctx, AV_LOG_ERROR,
208 "Drop frame time code only allowed with 1001/30000 fps\n");
213 AVRational rate = ff_mpeg12_frame_rate_tab[s->frame_rate_index];
214 int ret = av_timecode_init_from_string(&s->tc, rate, s->tc_opt_str, s);
217 s->drop_frame_timecode = !!(s->tc.flags & AV_TIMECODE_FLAG_DROPFRAME);
218 s->avctx->timecode_frame_start = s->tc.start;
220 s->avctx->timecode_frame_start = 0; // default is -1
225 static void put_header(MpegEncContext *s, int header)
227 avpriv_align_put_bits(&s->pb);
228 put_bits(&s->pb, 16, header >> 16);
229 put_sbits(&s->pb, 16, header);
232 /* put sequence header if needed */
233 static void mpeg1_encode_sequence_header(MpegEncContext *s)
235 unsigned int vbv_buffer_size, fps, v;
236 int i, constraint_parameter_flag;
238 int64_t best_aspect_error = INT64_MAX;
239 AVRational aspect_ratio = s->avctx->sample_aspect_ratio;
241 if (aspect_ratio.num == 0 || aspect_ratio.den == 0)
242 aspect_ratio = (AVRational){1,1}; // pixel aspect 1.1 (VGA)
244 if (s->current_picture.f->key_frame) {
245 AVRational framerate = ff_mpeg12_frame_rate_tab[s->frame_rate_index];
247 /* mpeg1 header repeated every gop */
248 put_header(s, SEQ_START_CODE);
250 put_sbits(&s->pb, 12, s->width & 0xFFF);
251 put_sbits(&s->pb, 12, s->height & 0xFFF);
253 for (i = 1; i < 15; i++) {
254 int64_t error = aspect_ratio.num * (1LL<<32) / aspect_ratio.den;
255 if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO || i <= 1)
256 error -= (1LL<<32) / ff_mpeg1_aspect[i];
258 error -= (1LL<<32)*ff_mpeg2_aspect[i].num * s->height / s->width / ff_mpeg2_aspect[i].den;
260 error = FFABS(error);
262 if (error - 2 <= best_aspect_error) {
263 best_aspect_error = error;
264 s->aspect_ratio_info = i;
268 put_bits(&s->pb, 4, s->aspect_ratio_info);
269 put_bits(&s->pb, 4, s->frame_rate_index);
271 if (s->avctx->rc_max_rate) {
272 v = (s->avctx->rc_max_rate + 399) / 400;
273 if (v > 0x3ffff && s->codec_id == AV_CODEC_ID_MPEG1VIDEO)
279 if (s->avctx->rc_buffer_size)
280 vbv_buffer_size = s->avctx->rc_buffer_size;
282 /* VBV calculation: Scaled so that a VCD has the proper
283 * VBV size of 40 kilobytes */
284 vbv_buffer_size = ((20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;
285 vbv_buffer_size = (vbv_buffer_size + 16383) / 16384;
287 put_sbits(&s->pb, 18, v);
288 put_bits(&s->pb, 1, 1); // marker
289 put_sbits(&s->pb, 10, vbv_buffer_size);
291 constraint_parameter_flag =
294 s->mb_width * s->mb_height <= 396 &&
295 s->mb_width * s->mb_height * framerate.num <= 396 * 25 * framerate.den &&
296 framerate.num <= framerate.den * 30 &&
297 s->avctx->me_range &&
298 s->avctx->me_range < 128 &&
299 vbv_buffer_size <= 20 &&
300 v <= 1856000 / 400 &&
301 s->codec_id == AV_CODEC_ID_MPEG1VIDEO;
303 put_bits(&s->pb, 1, constraint_parameter_flag);
305 ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
306 ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
308 if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
309 AVFrameSideData *side_data;
310 int width = s->width;
311 int height = s->height;
312 int use_seq_disp_ext;
314 put_header(s, EXT_START_CODE);
315 put_bits(&s->pb, 4, 1); // seq ext
317 put_bits(&s->pb, 1, s->avctx->profile == 0); // escx 1 for 4:2:2 profile
319 put_bits(&s->pb, 3, s->avctx->profile); // profile
320 put_bits(&s->pb, 4, s->avctx->level); // level
322 put_bits(&s->pb, 1, s->progressive_sequence);
323 put_bits(&s->pb, 2, s->chroma_format);
324 put_bits(&s->pb, 2, s->width >> 12);
325 put_bits(&s->pb, 2, s->height >> 12);
326 put_bits(&s->pb, 12, v >> 18); // bitrate ext
327 put_bits(&s->pb, 1, 1); // marker
328 put_bits(&s->pb, 8, vbv_buffer_size >> 10); // vbv buffer ext
329 put_bits(&s->pb, 1, s->low_delay);
330 put_bits(&s->pb, 2, s->mpeg2_frame_rate_ext.num-1); // frame_rate_ext_n
331 put_bits(&s->pb, 5, s->mpeg2_frame_rate_ext.den-1); // frame_rate_ext_d
333 side_data = av_frame_get_side_data(s->current_picture_ptr->f, AV_FRAME_DATA_PANSCAN);
335 AVPanScan *pan_scan = (AVPanScan *)side_data->data;
336 if (pan_scan->width && pan_scan->height) {
337 width = pan_scan->width >> 4;
338 height = pan_scan->height >> 4;
342 use_seq_disp_ext = (width != s->width ||
343 height != s->height ||
344 s->avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
345 s->avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
346 s->avctx->colorspace != AVCOL_SPC_UNSPECIFIED);
348 if (s->seq_disp_ext == 1 || (s->seq_disp_ext == -1 && use_seq_disp_ext)) {
349 put_header(s, EXT_START_CODE);
350 put_bits(&s->pb, 4, 2); // sequence display extension
351 put_bits(&s->pb, 3, 0); // video_format: 0 is components
352 put_bits(&s->pb, 1, 1); // colour_description
353 put_bits(&s->pb, 8, s->avctx->color_primaries); // colour_primaries
354 put_bits(&s->pb, 8, s->avctx->color_trc); // transfer_characteristics
355 put_bits(&s->pb, 8, s->avctx->colorspace); // matrix_coefficients
356 put_bits(&s->pb, 14, width); // display_horizontal_size
357 put_bits(&s->pb, 1, 1); // marker_bit
358 put_bits(&s->pb, 14, height); // display_vertical_size
359 put_bits(&s->pb, 3, 0); // remaining 3 bits are zero padding
363 put_header(s, GOP_START_CODE);
364 put_bits(&s->pb, 1, s->drop_frame_timecode); // drop frame flag
365 /* time code: we must convert from the real frame rate to a
366 * fake MPEG frame rate in case of low frame rate */
367 fps = (framerate.num + framerate.den / 2) / framerate.den;
368 time_code = s->current_picture_ptr->f->coded_picture_number +
369 s->avctx->timecode_frame_start;
371 s->gop_picture_number = s->current_picture_ptr->f->coded_picture_number;
373 av_assert0(s->drop_frame_timecode == !!(s->tc.flags & AV_TIMECODE_FLAG_DROPFRAME));
374 if (s->drop_frame_timecode)
375 time_code = av_timecode_adjust_ntsc_framenum2(time_code, fps);
377 put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));
378 put_bits(&s->pb, 6, (uint32_t)((time_code / (fps * 60)) % 60));
379 put_bits(&s->pb, 1, 1);
380 put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));
381 put_bits(&s->pb, 6, (uint32_t)((time_code % fps)));
382 put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP) || s->intra_only || !s->gop_picture_number);
383 put_bits(&s->pb, 1, 0); // broken link
387 static inline void encode_mb_skip_run(MpegEncContext *s, int run)
390 put_bits(&s->pb, 11, 0x008);
393 put_bits(&s->pb, ff_mpeg12_mbAddrIncrTable[run][1],
394 ff_mpeg12_mbAddrIncrTable[run][0]);
397 static av_always_inline void put_qscale(MpegEncContext *s)
399 put_bits(&s->pb, 5, s->qscale);
402 void ff_mpeg1_encode_slice_header(MpegEncContext *s)
404 if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && s->height > 2800) {
405 put_header(s, SLICE_MIN_START_CODE + (s->mb_y & 127));
406 /* slice_vertical_position_extension */
407 put_bits(&s->pb, 3, s->mb_y >> 7);
409 put_header(s, SLICE_MIN_START_CODE + s->mb_y);
412 /* slice extra information */
413 put_bits(&s->pb, 1, 0);
416 void ff_mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
418 AVFrameSideData *side_data;
419 mpeg1_encode_sequence_header(s);
421 /* mpeg1 picture header */
422 put_header(s, PICTURE_START_CODE);
423 /* temporal reference */
425 // RAL: s->picture_number instead of s->fake_picture_number
427 (s->picture_number - s->gop_picture_number) & 0x3ff);
428 put_bits(&s->pb, 3, s->pict_type);
430 s->vbv_delay_ptr = s->pb.buf + put_bits_count(&s->pb) / 8;
431 put_bits(&s->pb, 16, 0xFFFF); /* vbv_delay */
433 // RAL: Forward f_code also needed for B-frames
434 if (s->pict_type == AV_PICTURE_TYPE_P ||
435 s->pict_type == AV_PICTURE_TYPE_B) {
436 put_bits(&s->pb, 1, 0); /* half pel coordinates */
437 if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO)
438 put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
440 put_bits(&s->pb, 3, 7); /* forward_f_code */
443 // RAL: Backward f_code necessary for B-frames
444 if (s->pict_type == AV_PICTURE_TYPE_B) {
445 put_bits(&s->pb, 1, 0); /* half pel coordinates */
446 if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO)
447 put_bits(&s->pb, 3, s->b_code); /* backward_f_code */
449 put_bits(&s->pb, 3, 7); /* backward_f_code */
452 put_bits(&s->pb, 1, 0); /* extra bit picture */
454 s->frame_pred_frame_dct = 1;
455 if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
456 put_header(s, EXT_START_CODE);
457 put_bits(&s->pb, 4, 8); /* pic ext */
458 if (s->pict_type == AV_PICTURE_TYPE_P ||
459 s->pict_type == AV_PICTURE_TYPE_B) {
460 put_bits(&s->pb, 4, s->f_code);
461 put_bits(&s->pb, 4, s->f_code);
463 put_bits(&s->pb, 8, 255);
465 if (s->pict_type == AV_PICTURE_TYPE_B) {
466 put_bits(&s->pb, 4, s->b_code);
467 put_bits(&s->pb, 4, s->b_code);
469 put_bits(&s->pb, 8, 255);
471 put_bits(&s->pb, 2, s->intra_dc_precision);
473 av_assert0(s->picture_structure == PICT_FRAME);
474 put_bits(&s->pb, 2, s->picture_structure);
475 if (s->progressive_sequence)
476 put_bits(&s->pb, 1, 0); /* no repeat */
478 put_bits(&s->pb, 1, s->current_picture_ptr->f->top_field_first);
479 /* XXX: optimize the generation of this flag with entropy measures */
480 s->frame_pred_frame_dct = s->progressive_sequence;
482 put_bits(&s->pb, 1, s->frame_pred_frame_dct);
483 put_bits(&s->pb, 1, s->concealment_motion_vectors);
484 put_bits(&s->pb, 1, s->q_scale_type);
485 put_bits(&s->pb, 1, s->intra_vlc_format);
486 put_bits(&s->pb, 1, s->alternate_scan);
487 put_bits(&s->pb, 1, s->repeat_first_field);
488 s->progressive_frame = s->progressive_sequence;
489 /* chroma_420_type */
490 put_bits(&s->pb, 1, s->chroma_format ==
491 CHROMA_420 ? s->progressive_frame : 0);
492 put_bits(&s->pb, 1, s->progressive_frame);
493 put_bits(&s->pb, 1, 0); /* composite_display_flag */
495 if (s->scan_offset) {
498 put_header(s, USER_START_CODE);
499 for (i = 0; i < sizeof(svcd_scan_offset_placeholder); i++)
500 put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);
502 side_data = av_frame_get_side_data(s->current_picture_ptr->f,
503 AV_FRAME_DATA_STEREO3D);
505 AVStereo3D *stereo = (AVStereo3D *)side_data->data;
508 switch (stereo->type) {
509 case AV_STEREO3D_SIDEBYSIDE:
512 case AV_STEREO3D_TOPBOTTOM:
518 case AV_STEREO3D_SIDEBYSIDE_QUINCUNX:
527 put_header(s, USER_START_CODE);
528 put_bits(&s->pb, 8, 'J'); // S3D_video_format_signaling_identifier
529 put_bits(&s->pb, 8, 'P');
530 put_bits(&s->pb, 8, '3');
531 put_bits(&s->pb, 8, 'D');
532 put_bits(&s->pb, 8, 0x03); // S3D_video_format_length
534 put_bits(&s->pb, 1, 1); // reserved_bit
535 put_bits(&s->pb, 7, fpa_type); // S3D_video_format_type
536 put_bits(&s->pb, 8, 0x04); // reserved_data[0]
537 put_bits(&s->pb, 8, 0xFF); // reserved_data[1]
542 ff_mpeg1_encode_slice_header(s);
545 static inline void put_mb_modes(MpegEncContext *s, int n, int bits,
546 int has_mv, int field_motion)
548 put_bits(&s->pb, n, bits);
549 if (!s->frame_pred_frame_dct) {
551 /* motion_type: frame/field */
552 put_bits(&s->pb, 2, 2 - field_motion);
553 put_bits(&s->pb, 1, s->interlaced_dct);
557 // RAL: Parameter added: f_or_b_code
558 static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code)
563 ff_mpeg12_mbMotionVectorTable[0][1],
564 ff_mpeg12_mbMotionVectorTable[0][0]);
566 int code, sign, bits;
567 int bit_size = f_or_b_code - 1;
568 int range = 1 << bit_size;
569 /* modulo encoding */
570 val = sign_extend(val, 5 + bit_size);
574 code = (val >> bit_size) + 1;
575 bits = val & (range - 1);
580 code = (val >> bit_size) + 1;
581 bits = val & (range - 1);
585 av_assert2(code > 0 && code <= 16);
588 ff_mpeg12_mbMotionVectorTable[code][1],
589 ff_mpeg12_mbMotionVectorTable[code][0]);
591 put_bits(&s->pb, 1, sign);
593 put_bits(&s->pb, bit_size, bits);
597 static inline void encode_dc(MpegEncContext *s, int diff, int component)
599 unsigned int diff_u = diff + 255;
604 index = av_log2_16bit(-2 * diff);
607 index = av_log2_16bit(2 * diff);
611 ff_mpeg12_vlc_dc_lum_bits[index] + index,
612 (ff_mpeg12_vlc_dc_lum_code[index] << index) +
613 av_mod_uintp2(diff, index));
616 ff_mpeg12_vlc_dc_chroma_bits[index] + index,
617 (ff_mpeg12_vlc_dc_chroma_code[index] << index) +
618 av_mod_uintp2(diff, index));
622 mpeg1_lum_dc_uni[diff + 255] & 0xFF,
623 mpeg1_lum_dc_uni[diff + 255] >> 8);
626 mpeg1_chr_dc_uni[diff + 255] & 0xFF,
627 mpeg1_chr_dc_uni[diff + 255] >> 8);
631 static void mpeg1_encode_block(MpegEncContext *s, int16_t *block, int n)
633 int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
635 const uint16_t (*table_vlc)[2] = ff_rl_mpeg1.table_vlc;
637 last_index = s->block_last_index[n];
641 component = (n <= 3 ? 0 : (n & 1) + 1);
642 dc = block[0]; /* overflow is impossible */
643 diff = dc - s->last_dc[component];
644 encode_dc(s, diff, component);
645 s->last_dc[component] = dc;
647 if (s->intra_vlc_format)
648 table_vlc = ff_rl_mpeg2.table_vlc;
650 /* encode the first coefficient: needs to be done here because
651 * it is handled slightly differently */
653 if (abs(level) == 1) {
654 code = ((uint32_t)level >> 31); /* the sign bit */
655 put_bits(&s->pb, 2, code | 0x02);
664 /* now quantify & encode AC coefs */
665 last_non_zero = i - 1;
667 for (; i <= last_index; i++) {
668 j = s->intra_scantable.permutated[i];
672 /* encode using VLC */
674 run = i - last_non_zero - 1;
677 MASK_ABS(sign, alevel);
680 if (alevel <= mpeg1_max_level[0][run]) {
681 code = mpeg1_index_run[0][run] + alevel - 1;
682 /* store the VLC & sign at once */
683 put_bits(&s->pb, table_vlc[code][1] + 1,
684 (table_vlc[code][0] << 1) + sign);
686 /* escape seems to be pretty rare <5% so I do not optimize it */
687 put_bits(&s->pb, table_vlc[111][1], table_vlc[111][0]);
688 /* escape: only clip in this case */
689 put_bits(&s->pb, 6, run);
690 if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
692 put_sbits(&s->pb, 8, level);
695 put_bits(&s->pb, 16, 0x8001 + level + 255);
697 put_sbits(&s->pb, 16, level);
700 put_sbits(&s->pb, 12, level);
707 put_bits(&s->pb, table_vlc[112][1], table_vlc[112][0]);
710 static av_always_inline void mpeg1_encode_mb_internal(MpegEncContext *s,
711 int16_t block[8][64],
712 int motion_x, int motion_y,
716 const int mb_x = s->mb_x;
717 const int mb_y = s->mb_y;
718 const int first_mb = mb_x == s->resync_mb_x && mb_y == s->resync_mb_y;
722 for (i = 0; i < mb_block_count; i++)
723 if (s->block_last_index[i] >= 0)
724 cbp |= 1 << (mb_block_count - 1 - i);
726 if (cbp == 0 && !first_mb && s->mv_type == MV_TYPE_16X16 &&
727 (mb_x != s->mb_width - 1 ||
728 (mb_y != s->end_mb_y - 1 && s->codec_id == AV_CODEC_ID_MPEG1VIDEO)) &&
729 ((s->pict_type == AV_PICTURE_TYPE_P && (motion_x | motion_y) == 0) ||
730 (s->pict_type == AV_PICTURE_TYPE_B && s->mv_dir == s->last_mv_dir &&
731 (((s->mv_dir & MV_DIR_FORWARD)
732 ? ((s->mv[0][0][0] - s->last_mv[0][0][0]) |
733 (s->mv[0][0][1] - s->last_mv[0][0][1])) : 0) |
734 ((s->mv_dir & MV_DIR_BACKWARD)
735 ? ((s->mv[1][0][0] - s->last_mv[1][0][0]) |
736 (s->mv[1][0][1] - s->last_mv[1][0][1])) : 0)) == 0))) {
738 s->qscale -= s->dquant;
742 if (s->pict_type == AV_PICTURE_TYPE_P) {
743 s->last_mv[0][0][0] =
744 s->last_mv[0][0][1] =
745 s->last_mv[0][1][0] =
746 s->last_mv[0][1][1] = 0;
750 av_assert0(s->mb_skip_run == 0);
751 encode_mb_skip_run(s, s->mb_x);
753 encode_mb_skip_run(s, s->mb_skip_run);
756 if (s->pict_type == AV_PICTURE_TYPE_I) {
757 if (s->dquant && cbp) {
758 /* macroblock_type: macroblock_quant = 1 */
759 put_mb_modes(s, 2, 1, 0, 0);
762 /* macroblock_type: macroblock_quant = 0 */
763 put_mb_modes(s, 1, 1, 0, 0);
764 s->qscale -= s->dquant;
766 s->misc_bits += get_bits_diff(s);
768 } else if (s->mb_intra) {
769 if (s->dquant && cbp) {
770 put_mb_modes(s, 6, 0x01, 0, 0);
773 put_mb_modes(s, 5, 0x03, 0, 0);
774 s->qscale -= s->dquant;
776 s->misc_bits += get_bits_diff(s);
778 memset(s->last_mv, 0, sizeof(s->last_mv));
779 } else if (s->pict_type == AV_PICTURE_TYPE_P) {
780 if (s->mv_type == MV_TYPE_16X16) {
782 if ((motion_x | motion_y) == 0) {
784 /* macroblock_pattern & quant */
785 put_mb_modes(s, 5, 1, 0, 0);
788 /* macroblock_pattern only */
789 put_mb_modes(s, 2, 1, 0, 0);
791 s->misc_bits += get_bits_diff(s);
794 put_mb_modes(s, 5, 2, 1, 0); /* motion + cbp */
797 put_mb_modes(s, 1, 1, 1, 0); /* motion + cbp */
799 s->misc_bits += get_bits_diff(s);
800 // RAL: f_code parameter added
801 mpeg1_encode_motion(s,
802 motion_x - s->last_mv[0][0][0],
804 // RAL: f_code parameter added
805 mpeg1_encode_motion(s,
806 motion_y - s->last_mv[0][0][1],
808 s->mv_bits += get_bits_diff(s);
811 put_bits(&s->pb, 3, 1); /* motion only */
812 if (!s->frame_pred_frame_dct)
813 put_bits(&s->pb, 2, 2); /* motion_type: frame */
814 s->misc_bits += get_bits_diff(s);
815 // RAL: f_code parameter added
816 mpeg1_encode_motion(s,
817 motion_x - s->last_mv[0][0][0],
819 // RAL: f_code parameter added
820 mpeg1_encode_motion(s,
821 motion_y - s->last_mv[0][0][1],
823 s->qscale -= s->dquant;
824 s->mv_bits += get_bits_diff(s);
826 s->last_mv[0][1][0] = s->last_mv[0][0][0] = motion_x;
827 s->last_mv[0][1][1] = s->last_mv[0][0][1] = motion_y;
829 av_assert2(!s->frame_pred_frame_dct && s->mv_type == MV_TYPE_FIELD);
833 put_mb_modes(s, 5, 2, 1, 1); /* motion + cbp */
836 put_mb_modes(s, 1, 1, 1, 1); /* motion + cbp */
839 put_bits(&s->pb, 3, 1); /* motion only */
840 put_bits(&s->pb, 2, 1); /* motion_type: field */
841 s->qscale -= s->dquant;
843 s->misc_bits += get_bits_diff(s);
844 for (i = 0; i < 2; i++) {
845 put_bits(&s->pb, 1, s->field_select[0][i]);
846 mpeg1_encode_motion(s,
847 s->mv[0][i][0] - s->last_mv[0][i][0],
849 mpeg1_encode_motion(s,
850 s->mv[0][i][1] - (s->last_mv[0][i][1] >> 1),
852 s->last_mv[0][i][0] = s->mv[0][i][0];
853 s->last_mv[0][i][1] = 2 * s->mv[0][i][1];
855 s->mv_bits += get_bits_diff(s);
858 if (s->chroma_y_shift) {
860 ff_mpeg12_mbPatTable[cbp][1],
861 ff_mpeg12_mbPatTable[cbp][0]);
864 ff_mpeg12_mbPatTable[cbp >> 2][1],
865 ff_mpeg12_mbPatTable[cbp >> 2][0]);
866 put_sbits(&s->pb, 2, cbp);
871 if (s->mv_type == MV_TYPE_16X16) {
872 if (cbp) { // With coded bloc pattern
874 if (s->mv_dir == MV_DIR_FORWARD)
875 put_mb_modes(s, 6, 3, 1, 0);
877 put_mb_modes(s, 8 - s->mv_dir, 2, 1, 0);
880 put_mb_modes(s, 5 - s->mv_dir, 3, 1, 0);
882 } else { // No coded bloc pattern
883 put_bits(&s->pb, 5 - s->mv_dir, 2);
884 if (!s->frame_pred_frame_dct)
885 put_bits(&s->pb, 2, 2); /* motion_type: frame */
886 s->qscale -= s->dquant;
888 s->misc_bits += get_bits_diff(s);
889 if (s->mv_dir & MV_DIR_FORWARD) {
890 mpeg1_encode_motion(s,
891 s->mv[0][0][0] - s->last_mv[0][0][0],
893 mpeg1_encode_motion(s,
894 s->mv[0][0][1] - s->last_mv[0][0][1],
896 s->last_mv[0][0][0] =
897 s->last_mv[0][1][0] = s->mv[0][0][0];
898 s->last_mv[0][0][1] =
899 s->last_mv[0][1][1] = s->mv[0][0][1];
902 if (s->mv_dir & MV_DIR_BACKWARD) {
903 mpeg1_encode_motion(s,
904 s->mv[1][0][0] - s->last_mv[1][0][0],
906 mpeg1_encode_motion(s,
907 s->mv[1][0][1] - s->last_mv[1][0][1],
909 s->last_mv[1][0][0] =
910 s->last_mv[1][1][0] = s->mv[1][0][0];
911 s->last_mv[1][0][1] =
912 s->last_mv[1][1][1] = s->mv[1][0][1];
916 av_assert2(s->mv_type == MV_TYPE_FIELD);
917 av_assert2(!s->frame_pred_frame_dct);
918 if (cbp) { // With coded bloc pattern
920 if (s->mv_dir == MV_DIR_FORWARD)
921 put_mb_modes(s, 6, 3, 1, 1);
923 put_mb_modes(s, 8 - s->mv_dir, 2, 1, 1);
926 put_mb_modes(s, 5 - s->mv_dir, 3, 1, 1);
928 } else { // No coded bloc pattern
929 put_bits(&s->pb, 5 - s->mv_dir, 2);
930 put_bits(&s->pb, 2, 1); /* motion_type: field */
931 s->qscale -= s->dquant;
933 s->misc_bits += get_bits_diff(s);
934 if (s->mv_dir & MV_DIR_FORWARD) {
935 for (i = 0; i < 2; i++) {
936 put_bits(&s->pb, 1, s->field_select[0][i]);
937 mpeg1_encode_motion(s,
938 s->mv[0][i][0] - s->last_mv[0][i][0],
940 mpeg1_encode_motion(s,
941 s->mv[0][i][1] - (s->last_mv[0][i][1] >> 1),
943 s->last_mv[0][i][0] = s->mv[0][i][0];
944 s->last_mv[0][i][1] = s->mv[0][i][1] * 2;
948 if (s->mv_dir & MV_DIR_BACKWARD) {
949 for (i = 0; i < 2; i++) {
950 put_bits(&s->pb, 1, s->field_select[1][i]);
951 mpeg1_encode_motion(s,
952 s->mv[1][i][0] - s->last_mv[1][i][0],
954 mpeg1_encode_motion(s,
955 s->mv[1][i][1] - (s->last_mv[1][i][1] >> 1),
957 s->last_mv[1][i][0] = s->mv[1][i][0];
958 s->last_mv[1][i][1] = s->mv[1][i][1] * 2;
963 s->mv_bits += get_bits_diff(s);
965 if (s->chroma_y_shift) {
967 ff_mpeg12_mbPatTable[cbp][1],
968 ff_mpeg12_mbPatTable[cbp][0]);
971 ff_mpeg12_mbPatTable[cbp >> 2][1],
972 ff_mpeg12_mbPatTable[cbp >> 2][0]);
973 put_sbits(&s->pb, 2, cbp);
977 for (i = 0; i < mb_block_count; i++)
978 if (cbp & (1 << (mb_block_count - 1 - i)))
979 mpeg1_encode_block(s, block[i], i);
982 s->i_tex_bits += get_bits_diff(s);
984 s->p_tex_bits += get_bits_diff(s);
988 void ff_mpeg1_encode_mb(MpegEncContext *s, int16_t block[8][64],
989 int motion_x, int motion_y)
991 if (s->chroma_format == CHROMA_420)
992 mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 6);
994 mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 8);
997 av_cold void ff_mpeg1_encode_init(MpegEncContext *s)
1001 ff_mpeg12_common_init(s);
1009 ff_rl_init(&ff_rl_mpeg1, ff_mpeg12_static_rl_table_store[0]);
1010 ff_rl_init(&ff_rl_mpeg2, ff_mpeg12_static_rl_table_store[1]);
1012 for (i = 0; i < 64; i++) {
1013 mpeg1_max_level[0][i] = ff_rl_mpeg1.max_level[0][i];
1014 mpeg1_index_run[0][i] = ff_rl_mpeg1.index_run[0][i];
1017 init_uni_ac_vlc(&ff_rl_mpeg1, uni_mpeg1_ac_vlc_len);
1018 if (s->intra_vlc_format)
1019 init_uni_ac_vlc(&ff_rl_mpeg2, uni_mpeg2_ac_vlc_len);
1021 /* build unified dc encoding tables */
1022 for (i = -255; i < 256; i++) {
1027 adiff = FFABS(diff);
1030 index = av_log2(2 * adiff);
1032 bits = ff_mpeg12_vlc_dc_lum_bits[index] + index;
1033 code = (ff_mpeg12_vlc_dc_lum_code[index] << index) +
1034 av_mod_uintp2(diff, index);
1035 mpeg1_lum_dc_uni[i + 255] = bits + (code << 8);
1037 bits = ff_mpeg12_vlc_dc_chroma_bits[index] + index;
1038 code = (ff_mpeg12_vlc_dc_chroma_code[index] << index) +
1039 av_mod_uintp2(diff, index);
1040 mpeg1_chr_dc_uni[i + 255] = bits + (code << 8);
1043 for (f_code = 1; f_code <= MAX_FCODE; f_code++)
1044 for (mv = -MAX_MV; mv <= MAX_MV; mv++) {
1048 len = ff_mpeg12_mbMotionVectorTable[0][1];
1050 int val, bit_size, code;
1052 bit_size = f_code - 1;
1058 code = (val >> bit_size) + 1;
1060 len = ff_mpeg12_mbMotionVectorTable[code][1] +
1063 len = ff_mpeg12_mbMotionVectorTable[16][1] +
1067 mv_penalty[f_code][mv + MAX_MV] = len;
1071 for (f_code = MAX_FCODE; f_code > 0; f_code--)
1072 for (mv = -(8 << f_code); mv < (8 << f_code); mv++)
1073 fcode_tab[mv + MAX_MV] = f_code;
1075 s->me.mv_penalty = mv_penalty;
1076 s->fcode_tab = fcode_tab;
1077 if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
1078 s->min_qcoeff = -255;
1079 s->max_qcoeff = 255;
1081 s->min_qcoeff = -2047;
1082 s->max_qcoeff = 2047;
1084 if (s->intra_vlc_format) {
1085 s->intra_ac_vlc_length =
1086 s->intra_ac_vlc_last_length = uni_mpeg2_ac_vlc_len;
1088 s->intra_ac_vlc_length =
1089 s->intra_ac_vlc_last_length = uni_mpeg1_ac_vlc_len;
1091 s->inter_ac_vlc_length =
1092 s->inter_ac_vlc_last_length = uni_mpeg1_ac_vlc_len;
1095 #define OFFSET(x) offsetof(MpegEncContext, x)
1096 #define VE AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
1097 #define COMMON_OPTS \
1098 { "gop_timecode", "MPEG GOP Timecode in hh:mm:ss[:;.]ff format", \
1099 OFFSET(tc_opt_str), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, VE },\
1100 { "intra_vlc", "Use MPEG-2 intra VLC table.", \
1101 OFFSET(intra_vlc_format), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE }, \
1102 { "drop_frame_timecode", "Timecode is in drop frame format.", \
1103 OFFSET(drop_frame_timecode), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE }, \
1104 { "scan_offset", "Reserve space for SVCD scan offset user data.", \
1105 OFFSET(scan_offset), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1107 static const AVOption mpeg1_options[] = {
1113 static const AVOption mpeg2_options[] = {
1115 { "non_linear_quant", "Use nonlinear quantizer.", OFFSET(q_scale_type), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1116 { "alternate_scan", "Enable alternate scantable.", OFFSET(alternate_scan), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1117 { "seq_disp_ext", "Write sequence_display_extension blocks.", OFFSET(seq_disp_ext), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE, "seq_disp_ext" },
1118 { "auto", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = -1}, 0, 0, VE, "seq_disp_ext" },
1119 { "never", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, 0, 0, VE, "seq_disp_ext" },
1120 { "always", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, VE, "seq_disp_ext" },
1125 #define mpeg12_class(x) \
1126 static const AVClass mpeg ## x ## _class = { \
1127 .class_name = "mpeg" # x "video encoder", \
1128 .item_name = av_default_item_name, \
1129 .option = mpeg ## x ## _options, \
1130 .version = LIBAVUTIL_VERSION_INT, \
1136 AVCodec ff_mpeg1video_encoder = {
1137 .name = "mpeg1video",
1138 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
1139 .type = AVMEDIA_TYPE_VIDEO,
1140 .id = AV_CODEC_ID_MPEG1VIDEO,
1141 .priv_data_size = sizeof(MpegEncContext),
1142 .init = encode_init,
1143 .encode2 = ff_mpv_encode_picture,
1144 .close = ff_mpv_encode_end,
1145 .supported_framerates = ff_mpeg12_frame_rate_tab + 1,
1146 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P,
1148 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
1149 .priv_class = &mpeg1_class,
1152 AVCodec ff_mpeg2video_encoder = {
1153 .name = "mpeg2video",
1154 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
1155 .type = AVMEDIA_TYPE_VIDEO,
1156 .id = AV_CODEC_ID_MPEG2VIDEO,
1157 .priv_data_size = sizeof(MpegEncContext),
1158 .init = encode_init,
1159 .encode2 = ff_mpv_encode_picture,
1160 .close = ff_mpv_encode_end,
1161 .supported_framerates = ff_mpeg2_frame_rate_tab,
1162 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P,
1165 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
1166 .priv_class = &mpeg2_class,