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_DMV * 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 #define A53_MAX_CC_COUNT 0x1f
66 static av_cold void init_uni_ac_vlc(RLTable *rl, uint8_t *uni_ac_vlc_len)
70 for (i = 0; i < 128; i++) {
75 for (run = 0; run < 64; run++) {
77 int alevel = FFABS(level);
79 if (alevel > rl->max_level[0][run])
80 code = 111; /* rl->n */
82 code = rl->index_run[0][run] + alevel - 1;
84 if (code < 111) { /* rl->n */
85 /* length of VLC and sign */
86 len = rl->table_vlc[code][1] + 1;
88 len = rl->table_vlc[111 /* rl->n */][1] + 6;
96 uni_ac_vlc_len[UNI_AC_ENC_INDEX(run, i)] = len;
101 static int find_frame_rate_index(MpegEncContext *s)
104 AVRational bestq = (AVRational) {0, 0};
106 AVRational target = av_inv_q(s->avctx->time_base);
108 for (i = 1; i < 14; i++) {
109 if (s->avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL &&
113 for (ext.num=1; ext.num <= 4; ext.num++) {
114 for (ext.den=1; ext.den <= 32; ext.den++) {
115 AVRational q = av_mul_q(ext, ff_mpeg12_frame_rate_tab[i]);
117 if (s->codec_id != AV_CODEC_ID_MPEG2VIDEO && (ext.den!=1 || ext.num!=1))
119 if (av_gcd(ext.den, ext.num) != 1)
123 || av_nearer_q(target, bestq, q) < 0
124 || ext.num==1 && ext.den==1 && av_nearer_q(target, bestq, q) == 0) {
126 s->frame_rate_index = i;
127 s->mpeg2_frame_rate_ext.num = ext.num;
128 s->mpeg2_frame_rate_ext.den = ext.den;
134 if (av_cmp_q(target, bestq))
140 static av_cold int encode_init(AVCodecContext *avctx)
143 MpegEncContext *s = avctx->priv_data;
145 if ((ret = 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, "MPEG-1/2 does not support %d/%d fps\n",
151 avctx->time_base.den, avctx->time_base.num);
152 return AVERROR(EINVAL);
154 av_log(avctx, AV_LOG_INFO,
155 "MPEG-1/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");
163 return AVERROR(EINVAL);
166 avctx->profile = s->chroma_format == CHROMA_420 ? FF_PROFILE_MPEG2_MAIN : FF_PROFILE_MPEG2_422;
169 if (avctx->level == FF_LEVEL_UNKNOWN) {
170 if (avctx->profile == FF_PROFILE_MPEG2_422) { /* 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 != FF_PROFILE_MPEG2_HIGH && 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");
179 return AVERROR(EINVAL);
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");
209 return AVERROR(EINVAL);
212 #if FF_API_PRIVATE_OPT
213 FF_DISABLE_DEPRECATION_WARNINGS
214 if (avctx->timecode_frame_start)
215 s->timecode_frame_start = avctx->timecode_frame_start;
216 FF_ENABLE_DEPRECATION_WARNINGS
220 AVRational rate = ff_mpeg12_frame_rate_tab[s->frame_rate_index];
221 int ret = av_timecode_init_from_string(&s->tc, rate, s->tc_opt_str, s);
224 s->drop_frame_timecode = !!(s->tc.flags & AV_TIMECODE_FLAG_DROPFRAME);
225 s->timecode_frame_start = s->tc.start;
227 s->timecode_frame_start = 0; // default is -1
233 static void put_header(MpegEncContext *s, int header)
235 avpriv_align_put_bits(&s->pb);
236 put_bits(&s->pb, 16, header >> 16);
237 put_sbits(&s->pb, 16, header);
240 /* put sequence header if needed */
241 static void mpeg1_encode_sequence_header(MpegEncContext *s)
243 unsigned int vbv_buffer_size, fps, v;
244 int i, constraint_parameter_flag;
246 int64_t best_aspect_error = INT64_MAX;
247 AVRational aspect_ratio = s->avctx->sample_aspect_ratio;
249 if (aspect_ratio.num == 0 || aspect_ratio.den == 0)
250 aspect_ratio = (AVRational){1,1}; // pixel aspect 1.1 (VGA)
252 if (s->current_picture.f->key_frame) {
253 AVRational framerate = ff_mpeg12_frame_rate_tab[s->frame_rate_index];
255 /* MPEG-1 header repeated every GOP */
256 put_header(s, SEQ_START_CODE);
258 put_sbits(&s->pb, 12, s->width & 0xFFF);
259 put_sbits(&s->pb, 12, s->height & 0xFFF);
261 for (i = 1; i < 15; i++) {
262 int64_t error = aspect_ratio.num * (1LL<<32) / aspect_ratio.den;
263 if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO || i <= 1)
264 error -= (1LL<<32) / ff_mpeg1_aspect[i];
266 error -= (1LL<<32)*ff_mpeg2_aspect[i].num * s->height / s->width / ff_mpeg2_aspect[i].den;
268 error = FFABS(error);
270 if (error - 2 <= best_aspect_error) {
271 best_aspect_error = error;
272 s->aspect_ratio_info = i;
276 put_bits(&s->pb, 4, s->aspect_ratio_info);
277 put_bits(&s->pb, 4, s->frame_rate_index);
279 if (s->avctx->rc_max_rate) {
280 v = (s->avctx->rc_max_rate + 399) / 400;
281 if (v > 0x3ffff && s->codec_id == AV_CODEC_ID_MPEG1VIDEO)
287 if (s->avctx->rc_buffer_size)
288 vbv_buffer_size = s->avctx->rc_buffer_size;
290 /* VBV calculation: Scaled so that a VCD has the proper
291 * VBV size of 40 kilobytes */
292 vbv_buffer_size = ((20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;
293 vbv_buffer_size = (vbv_buffer_size + 16383) / 16384;
295 put_sbits(&s->pb, 18, v);
296 put_bits(&s->pb, 1, 1); // marker
297 put_sbits(&s->pb, 10, vbv_buffer_size);
299 constraint_parameter_flag =
302 s->mb_width * s->mb_height <= 396 &&
303 s->mb_width * s->mb_height * framerate.num <= 396 * 25 * framerate.den &&
304 framerate.num <= framerate.den * 30 &&
305 s->avctx->me_range &&
306 s->avctx->me_range < 128 &&
307 vbv_buffer_size <= 20 &&
308 v <= 1856000 / 400 &&
309 s->codec_id == AV_CODEC_ID_MPEG1VIDEO;
311 put_bits(&s->pb, 1, constraint_parameter_flag);
313 ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
314 ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
316 if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
317 AVFrameSideData *side_data;
318 int width = s->width;
319 int height = s->height;
320 int use_seq_disp_ext;
322 put_header(s, EXT_START_CODE);
323 put_bits(&s->pb, 4, 1); // seq ext
325 put_bits(&s->pb, 1, s->avctx->profile == FF_PROFILE_MPEG2_422); // escx 1 for 4:2:2 profile
327 put_bits(&s->pb, 3, s->avctx->profile); // profile
328 put_bits(&s->pb, 4, s->avctx->level); // level
330 put_bits(&s->pb, 1, s->progressive_sequence);
331 put_bits(&s->pb, 2, s->chroma_format);
332 put_bits(&s->pb, 2, s->width >> 12);
333 put_bits(&s->pb, 2, s->height >> 12);
334 put_bits(&s->pb, 12, v >> 18); // bitrate ext
335 put_bits(&s->pb, 1, 1); // marker
336 put_bits(&s->pb, 8, vbv_buffer_size >> 10); // vbv buffer ext
337 put_bits(&s->pb, 1, s->low_delay);
338 put_bits(&s->pb, 2, s->mpeg2_frame_rate_ext.num-1); // frame_rate_ext_n
339 put_bits(&s->pb, 5, s->mpeg2_frame_rate_ext.den-1); // frame_rate_ext_d
341 side_data = av_frame_get_side_data(s->current_picture_ptr->f, AV_FRAME_DATA_PANSCAN);
343 AVPanScan *pan_scan = (AVPanScan *)side_data->data;
344 if (pan_scan->width && pan_scan->height) {
345 width = pan_scan->width >> 4;
346 height = pan_scan->height >> 4;
350 use_seq_disp_ext = (width != s->width ||
351 height != s->height ||
352 s->avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
353 s->avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
354 s->avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
355 s->video_format != VIDEO_FORMAT_UNSPECIFIED);
357 if (s->seq_disp_ext == 1 || (s->seq_disp_ext == -1 && use_seq_disp_ext)) {
358 put_header(s, EXT_START_CODE);
359 put_bits(&s->pb, 4, 2); // sequence display extension
360 put_bits(&s->pb, 3, s->video_format); // video_format
361 put_bits(&s->pb, 1, 1); // colour_description
362 put_bits(&s->pb, 8, s->avctx->color_primaries); // colour_primaries
363 put_bits(&s->pb, 8, s->avctx->color_trc); // transfer_characteristics
364 put_bits(&s->pb, 8, s->avctx->colorspace); // matrix_coefficients
365 put_bits(&s->pb, 14, width); // display_horizontal_size
366 put_bits(&s->pb, 1, 1); // marker_bit
367 put_bits(&s->pb, 14, height); // display_vertical_size
368 put_bits(&s->pb, 3, 0); // remaining 3 bits are zero padding
372 put_header(s, GOP_START_CODE);
373 put_bits(&s->pb, 1, s->drop_frame_timecode); // drop frame flag
374 /* time code: we must convert from the real frame rate to a
375 * fake MPEG frame rate in case of low frame rate */
376 fps = (framerate.num + framerate.den / 2) / framerate.den;
377 time_code = s->current_picture_ptr->f->coded_picture_number +
378 s->timecode_frame_start;
380 s->gop_picture_number = s->current_picture_ptr->f->coded_picture_number;
382 av_assert0(s->drop_frame_timecode == !!(s->tc.flags & AV_TIMECODE_FLAG_DROPFRAME));
383 if (s->drop_frame_timecode)
384 time_code = av_timecode_adjust_ntsc_framenum2(time_code, fps);
386 put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));
387 put_bits(&s->pb, 6, (uint32_t)((time_code / (fps * 60)) % 60));
388 put_bits(&s->pb, 1, 1);
389 put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));
390 put_bits(&s->pb, 6, (uint32_t)((time_code % fps)));
391 put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP) || s->intra_only || !s->gop_picture_number);
392 put_bits(&s->pb, 1, 0); // broken link
396 static inline void encode_mb_skip_run(MpegEncContext *s, int run)
399 put_bits(&s->pb, 11, 0x008);
402 put_bits(&s->pb, ff_mpeg12_mbAddrIncrTable[run][1],
403 ff_mpeg12_mbAddrIncrTable[run][0]);
406 static av_always_inline void put_qscale(MpegEncContext *s)
408 put_bits(&s->pb, 5, s->qscale);
411 void ff_mpeg1_encode_slice_header(MpegEncContext *s)
413 if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && s->height > 2800) {
414 put_header(s, SLICE_MIN_START_CODE + (s->mb_y & 127));
415 /* slice_vertical_position_extension */
416 put_bits(&s->pb, 3, s->mb_y >> 7);
418 put_header(s, SLICE_MIN_START_CODE + s->mb_y);
421 /* slice extra information */
422 put_bits(&s->pb, 1, 0);
425 void ff_mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
427 AVFrameSideData *side_data;
428 mpeg1_encode_sequence_header(s);
430 /* MPEG-1 picture header */
431 put_header(s, PICTURE_START_CODE);
432 /* temporal reference */
434 // RAL: s->picture_number instead of s->fake_picture_number
436 (s->picture_number - s->gop_picture_number) & 0x3ff);
437 put_bits(&s->pb, 3, s->pict_type);
439 s->vbv_delay_ptr = s->pb.buf + put_bits_count(&s->pb) / 8;
440 put_bits(&s->pb, 16, 0xFFFF); /* vbv_delay */
442 // RAL: Forward f_code also needed for B-frames
443 if (s->pict_type == AV_PICTURE_TYPE_P ||
444 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->f_code); /* forward_f_code */
449 put_bits(&s->pb, 3, 7); /* forward_f_code */
452 // RAL: Backward f_code necessary for B-frames
453 if (s->pict_type == AV_PICTURE_TYPE_B) {
454 put_bits(&s->pb, 1, 0); /* half pel coordinates */
455 if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO)
456 put_bits(&s->pb, 3, s->b_code); /* backward_f_code */
458 put_bits(&s->pb, 3, 7); /* backward_f_code */
461 put_bits(&s->pb, 1, 0); /* extra bit picture */
463 s->frame_pred_frame_dct = 1;
464 if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
465 put_header(s, EXT_START_CODE);
466 put_bits(&s->pb, 4, 8); /* pic ext */
467 if (s->pict_type == AV_PICTURE_TYPE_P ||
468 s->pict_type == AV_PICTURE_TYPE_B) {
469 put_bits(&s->pb, 4, s->f_code);
470 put_bits(&s->pb, 4, s->f_code);
472 put_bits(&s->pb, 8, 255);
474 if (s->pict_type == AV_PICTURE_TYPE_B) {
475 put_bits(&s->pb, 4, s->b_code);
476 put_bits(&s->pb, 4, s->b_code);
478 put_bits(&s->pb, 8, 255);
480 put_bits(&s->pb, 2, s->intra_dc_precision);
482 av_assert0(s->picture_structure == PICT_FRAME);
483 put_bits(&s->pb, 2, s->picture_structure);
484 if (s->progressive_sequence)
485 put_bits(&s->pb, 1, 0); /* no repeat */
487 put_bits(&s->pb, 1, s->current_picture_ptr->f->top_field_first);
488 /* XXX: optimize the generation of this flag with entropy measures */
489 s->frame_pred_frame_dct = s->progressive_sequence;
491 put_bits(&s->pb, 1, s->frame_pred_frame_dct);
492 put_bits(&s->pb, 1, s->concealment_motion_vectors);
493 put_bits(&s->pb, 1, s->q_scale_type);
494 put_bits(&s->pb, 1, s->intra_vlc_format);
495 put_bits(&s->pb, 1, s->alternate_scan);
496 put_bits(&s->pb, 1, s->repeat_first_field);
497 s->progressive_frame = s->progressive_sequence;
498 /* chroma_420_type */
499 put_bits(&s->pb, 1, s->chroma_format ==
500 CHROMA_420 ? s->progressive_frame : 0);
501 put_bits(&s->pb, 1, s->progressive_frame);
502 put_bits(&s->pb, 1, 0); /* composite_display_flag */
504 if (s->scan_offset) {
507 put_header(s, USER_START_CODE);
508 for (i = 0; i < sizeof(svcd_scan_offset_placeholder); i++)
509 put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);
511 side_data = av_frame_get_side_data(s->current_picture_ptr->f,
512 AV_FRAME_DATA_STEREO3D);
514 AVStereo3D *stereo = (AVStereo3D *)side_data->data;
517 switch (stereo->type) {
518 case AV_STEREO3D_SIDEBYSIDE:
521 case AV_STEREO3D_TOPBOTTOM:
527 case AV_STEREO3D_SIDEBYSIDE_QUINCUNX:
536 put_header(s, USER_START_CODE);
537 put_bits(&s->pb, 8, 'J'); // S3D_video_format_signaling_identifier
538 put_bits(&s->pb, 8, 'P');
539 put_bits(&s->pb, 8, '3');
540 put_bits(&s->pb, 8, 'D');
541 put_bits(&s->pb, 8, 0x03); // S3D_video_format_length
543 put_bits(&s->pb, 1, 1); // reserved_bit
544 put_bits(&s->pb, 7, fpa_type); // S3D_video_format_type
545 put_bits(&s->pb, 8, 0x04); // reserved_data[0]
546 put_bits(&s->pb, 8, 0xFF); // reserved_data[1]
550 if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && s->a53_cc) {
551 side_data = av_frame_get_side_data(s->current_picture_ptr->f,
552 AV_FRAME_DATA_A53_CC);
554 if (side_data->size <= A53_MAX_CC_COUNT * 3 && side_data->size % 3 == 0) {
557 put_header (s, USER_START_CODE);
559 put_bits(&s->pb, 8, 'G'); // user_identifier
560 put_bits(&s->pb, 8, 'A');
561 put_bits(&s->pb, 8, '9');
562 put_bits(&s->pb, 8, '4');
563 put_bits(&s->pb, 8, 3); // user_data_type_code
565 (side_data->size / 3 & A53_MAX_CC_COUNT) | 0x40); // flags, cc_count
566 put_bits(&s->pb, 8, 0xff); // em_data
568 for (i = 0; i < side_data->size; i++)
569 put_bits(&s->pb, 8, side_data->data[i]);
571 put_bits(&s->pb, 8, 0xff); // marker_bits
573 av_log(s->avctx, AV_LOG_WARNING,
574 "Warning Closed Caption size (%d) can not exceed 93 bytes "
575 "and must be a multiple of 3\n", side_data->size);
581 ff_mpeg1_encode_slice_header(s);
584 static inline void put_mb_modes(MpegEncContext *s, int n, int bits,
585 int has_mv, int field_motion)
587 put_bits(&s->pb, n, bits);
588 if (!s->frame_pred_frame_dct) {
590 /* motion_type: frame/field */
591 put_bits(&s->pb, 2, 2 - field_motion);
592 put_bits(&s->pb, 1, s->interlaced_dct);
596 // RAL: Parameter added: f_or_b_code
597 static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code)
602 ff_mpeg12_mbMotionVectorTable[0][1],
603 ff_mpeg12_mbMotionVectorTable[0][0]);
605 int code, sign, bits;
606 int bit_size = f_or_b_code - 1;
607 int range = 1 << bit_size;
608 /* modulo encoding */
609 val = sign_extend(val, 5 + bit_size);
613 code = (val >> bit_size) + 1;
614 bits = val & (range - 1);
619 code = (val >> bit_size) + 1;
620 bits = val & (range - 1);
624 av_assert2(code > 0 && code <= 16);
627 ff_mpeg12_mbMotionVectorTable[code][1],
628 ff_mpeg12_mbMotionVectorTable[code][0]);
630 put_bits(&s->pb, 1, sign);
632 put_bits(&s->pb, bit_size, bits);
636 static inline void encode_dc(MpegEncContext *s, int diff, int component)
638 unsigned int diff_u = diff + 255;
643 index = av_log2_16bit(-2 * diff);
646 index = av_log2_16bit(2 * diff);
650 ff_mpeg12_vlc_dc_lum_bits[index] + index,
651 (ff_mpeg12_vlc_dc_lum_code[index] << index) +
652 av_mod_uintp2(diff, index));
655 ff_mpeg12_vlc_dc_chroma_bits[index] + index,
656 (ff_mpeg12_vlc_dc_chroma_code[index] << index) +
657 av_mod_uintp2(diff, index));
661 mpeg1_lum_dc_uni[diff + 255] & 0xFF,
662 mpeg1_lum_dc_uni[diff + 255] >> 8);
665 mpeg1_chr_dc_uni[diff + 255] & 0xFF,
666 mpeg1_chr_dc_uni[diff + 255] >> 8);
670 static void mpeg1_encode_block(MpegEncContext *s, int16_t *block, int n)
672 int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
674 const uint16_t (*table_vlc)[2] = ff_rl_mpeg1.table_vlc;
676 last_index = s->block_last_index[n];
680 component = (n <= 3 ? 0 : (n & 1) + 1);
681 dc = block[0]; /* overflow is impossible */
682 diff = dc - s->last_dc[component];
683 encode_dc(s, diff, component);
684 s->last_dc[component] = dc;
686 if (s->intra_vlc_format)
687 table_vlc = ff_rl_mpeg2.table_vlc;
689 /* encode the first coefficient: needs to be done here because
690 * it is handled slightly differently */
692 if (abs(level) == 1) {
693 code = ((uint32_t)level >> 31); /* the sign bit */
694 put_bits(&s->pb, 2, code | 0x02);
703 /* now quantify & encode AC coefs */
704 last_non_zero = i - 1;
706 for (; i <= last_index; i++) {
707 j = s->intra_scantable.permutated[i];
711 /* encode using VLC */
713 run = i - last_non_zero - 1;
716 MASK_ABS(sign, alevel);
719 if (alevel <= mpeg1_max_level[0][run]) {
720 code = mpeg1_index_run[0][run] + alevel - 1;
721 /* store the VLC & sign at once */
722 put_bits(&s->pb, table_vlc[code][1] + 1,
723 (table_vlc[code][0] << 1) + sign);
725 /* escape seems to be pretty rare <5% so I do not optimize it */
726 put_bits(&s->pb, table_vlc[111][1], table_vlc[111][0]);
727 /* escape: only clip in this case */
728 put_bits(&s->pb, 6, run);
729 if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
731 put_sbits(&s->pb, 8, level);
734 put_bits(&s->pb, 16, 0x8001 + level + 255);
736 put_sbits(&s->pb, 16, level);
739 put_sbits(&s->pb, 12, level);
746 put_bits(&s->pb, table_vlc[112][1], table_vlc[112][0]);
749 static av_always_inline void mpeg1_encode_mb_internal(MpegEncContext *s,
750 int16_t block[8][64],
751 int motion_x, int motion_y,
755 const int mb_x = s->mb_x;
756 const int mb_y = s->mb_y;
757 const int first_mb = mb_x == s->resync_mb_x && mb_y == s->resync_mb_y;
761 for (i = 0; i < mb_block_count; i++)
762 if (s->block_last_index[i] >= 0)
763 cbp |= 1 << (mb_block_count - 1 - i);
765 if (cbp == 0 && !first_mb && s->mv_type == MV_TYPE_16X16 &&
766 (mb_x != s->mb_width - 1 ||
767 (mb_y != s->end_mb_y - 1 && s->codec_id == AV_CODEC_ID_MPEG1VIDEO)) &&
768 ((s->pict_type == AV_PICTURE_TYPE_P && (motion_x | motion_y) == 0) ||
769 (s->pict_type == AV_PICTURE_TYPE_B && s->mv_dir == s->last_mv_dir &&
770 (((s->mv_dir & MV_DIR_FORWARD)
771 ? ((s->mv[0][0][0] - s->last_mv[0][0][0]) |
772 (s->mv[0][0][1] - s->last_mv[0][0][1])) : 0) |
773 ((s->mv_dir & MV_DIR_BACKWARD)
774 ? ((s->mv[1][0][0] - s->last_mv[1][0][0]) |
775 (s->mv[1][0][1] - s->last_mv[1][0][1])) : 0)) == 0))) {
777 s->qscale -= s->dquant;
781 if (s->pict_type == AV_PICTURE_TYPE_P) {
782 s->last_mv[0][0][0] =
783 s->last_mv[0][0][1] =
784 s->last_mv[0][1][0] =
785 s->last_mv[0][1][1] = 0;
789 av_assert0(s->mb_skip_run == 0);
790 encode_mb_skip_run(s, s->mb_x);
792 encode_mb_skip_run(s, s->mb_skip_run);
795 if (s->pict_type == AV_PICTURE_TYPE_I) {
796 if (s->dquant && cbp) {
797 /* macroblock_type: macroblock_quant = 1 */
798 put_mb_modes(s, 2, 1, 0, 0);
801 /* macroblock_type: macroblock_quant = 0 */
802 put_mb_modes(s, 1, 1, 0, 0);
803 s->qscale -= s->dquant;
805 s->misc_bits += get_bits_diff(s);
807 } else if (s->mb_intra) {
808 if (s->dquant && cbp) {
809 put_mb_modes(s, 6, 0x01, 0, 0);
812 put_mb_modes(s, 5, 0x03, 0, 0);
813 s->qscale -= s->dquant;
815 s->misc_bits += get_bits_diff(s);
817 memset(s->last_mv, 0, sizeof(s->last_mv));
818 } else if (s->pict_type == AV_PICTURE_TYPE_P) {
819 if (s->mv_type == MV_TYPE_16X16) {
821 if ((motion_x | motion_y) == 0) {
823 /* macroblock_pattern & quant */
824 put_mb_modes(s, 5, 1, 0, 0);
827 /* macroblock_pattern only */
828 put_mb_modes(s, 2, 1, 0, 0);
830 s->misc_bits += get_bits_diff(s);
833 put_mb_modes(s, 5, 2, 1, 0); /* motion + cbp */
836 put_mb_modes(s, 1, 1, 1, 0); /* motion + cbp */
838 s->misc_bits += get_bits_diff(s);
839 // RAL: f_code parameter added
840 mpeg1_encode_motion(s,
841 motion_x - s->last_mv[0][0][0],
843 // RAL: f_code parameter added
844 mpeg1_encode_motion(s,
845 motion_y - s->last_mv[0][0][1],
847 s->mv_bits += get_bits_diff(s);
850 put_bits(&s->pb, 3, 1); /* motion only */
851 if (!s->frame_pred_frame_dct)
852 put_bits(&s->pb, 2, 2); /* motion_type: frame */
853 s->misc_bits += get_bits_diff(s);
854 // RAL: f_code parameter added
855 mpeg1_encode_motion(s,
856 motion_x - s->last_mv[0][0][0],
858 // RAL: f_code parameter added
859 mpeg1_encode_motion(s,
860 motion_y - s->last_mv[0][0][1],
862 s->qscale -= s->dquant;
863 s->mv_bits += get_bits_diff(s);
865 s->last_mv[0][1][0] = s->last_mv[0][0][0] = motion_x;
866 s->last_mv[0][1][1] = s->last_mv[0][0][1] = motion_y;
868 av_assert2(!s->frame_pred_frame_dct && s->mv_type == MV_TYPE_FIELD);
872 put_mb_modes(s, 5, 2, 1, 1); /* motion + cbp */
875 put_mb_modes(s, 1, 1, 1, 1); /* motion + cbp */
878 put_bits(&s->pb, 3, 1); /* motion only */
879 put_bits(&s->pb, 2, 1); /* motion_type: field */
880 s->qscale -= s->dquant;
882 s->misc_bits += get_bits_diff(s);
883 for (i = 0; i < 2; i++) {
884 put_bits(&s->pb, 1, s->field_select[0][i]);
885 mpeg1_encode_motion(s,
886 s->mv[0][i][0] - s->last_mv[0][i][0],
888 mpeg1_encode_motion(s,
889 s->mv[0][i][1] - (s->last_mv[0][i][1] >> 1),
891 s->last_mv[0][i][0] = s->mv[0][i][0];
892 s->last_mv[0][i][1] = 2 * s->mv[0][i][1];
894 s->mv_bits += get_bits_diff(s);
897 if (s->chroma_y_shift) {
899 ff_mpeg12_mbPatTable[cbp][1],
900 ff_mpeg12_mbPatTable[cbp][0]);
903 ff_mpeg12_mbPatTable[cbp >> 2][1],
904 ff_mpeg12_mbPatTable[cbp >> 2][0]);
905 put_sbits(&s->pb, 2, cbp);
910 if (s->mv_type == MV_TYPE_16X16) {
911 if (cbp) { // With coded bloc pattern
913 if (s->mv_dir == MV_DIR_FORWARD)
914 put_mb_modes(s, 6, 3, 1, 0);
916 put_mb_modes(s, 8 - s->mv_dir, 2, 1, 0);
919 put_mb_modes(s, 5 - s->mv_dir, 3, 1, 0);
921 } else { // No coded bloc pattern
922 put_bits(&s->pb, 5 - s->mv_dir, 2);
923 if (!s->frame_pred_frame_dct)
924 put_bits(&s->pb, 2, 2); /* motion_type: frame */
925 s->qscale -= s->dquant;
927 s->misc_bits += get_bits_diff(s);
928 if (s->mv_dir & MV_DIR_FORWARD) {
929 mpeg1_encode_motion(s,
930 s->mv[0][0][0] - s->last_mv[0][0][0],
932 mpeg1_encode_motion(s,
933 s->mv[0][0][1] - s->last_mv[0][0][1],
935 s->last_mv[0][0][0] =
936 s->last_mv[0][1][0] = s->mv[0][0][0];
937 s->last_mv[0][0][1] =
938 s->last_mv[0][1][1] = s->mv[0][0][1];
941 if (s->mv_dir & MV_DIR_BACKWARD) {
942 mpeg1_encode_motion(s,
943 s->mv[1][0][0] - s->last_mv[1][0][0],
945 mpeg1_encode_motion(s,
946 s->mv[1][0][1] - s->last_mv[1][0][1],
948 s->last_mv[1][0][0] =
949 s->last_mv[1][1][0] = s->mv[1][0][0];
950 s->last_mv[1][0][1] =
951 s->last_mv[1][1][1] = s->mv[1][0][1];
955 av_assert2(s->mv_type == MV_TYPE_FIELD);
956 av_assert2(!s->frame_pred_frame_dct);
957 if (cbp) { // With coded bloc pattern
959 if (s->mv_dir == MV_DIR_FORWARD)
960 put_mb_modes(s, 6, 3, 1, 1);
962 put_mb_modes(s, 8 - s->mv_dir, 2, 1, 1);
965 put_mb_modes(s, 5 - s->mv_dir, 3, 1, 1);
967 } else { // No coded bloc pattern
968 put_bits(&s->pb, 5 - s->mv_dir, 2);
969 put_bits(&s->pb, 2, 1); /* motion_type: field */
970 s->qscale -= s->dquant;
972 s->misc_bits += get_bits_diff(s);
973 if (s->mv_dir & MV_DIR_FORWARD) {
974 for (i = 0; i < 2; i++) {
975 put_bits(&s->pb, 1, s->field_select[0][i]);
976 mpeg1_encode_motion(s,
977 s->mv[0][i][0] - s->last_mv[0][i][0],
979 mpeg1_encode_motion(s,
980 s->mv[0][i][1] - (s->last_mv[0][i][1] >> 1),
982 s->last_mv[0][i][0] = s->mv[0][i][0];
983 s->last_mv[0][i][1] = s->mv[0][i][1] * 2;
987 if (s->mv_dir & MV_DIR_BACKWARD) {
988 for (i = 0; i < 2; i++) {
989 put_bits(&s->pb, 1, s->field_select[1][i]);
990 mpeg1_encode_motion(s,
991 s->mv[1][i][0] - s->last_mv[1][i][0],
993 mpeg1_encode_motion(s,
994 s->mv[1][i][1] - (s->last_mv[1][i][1] >> 1),
996 s->last_mv[1][i][0] = s->mv[1][i][0];
997 s->last_mv[1][i][1] = s->mv[1][i][1] * 2;
1002 s->mv_bits += get_bits_diff(s);
1004 if (s->chroma_y_shift) {
1006 ff_mpeg12_mbPatTable[cbp][1],
1007 ff_mpeg12_mbPatTable[cbp][0]);
1010 ff_mpeg12_mbPatTable[cbp >> 2][1],
1011 ff_mpeg12_mbPatTable[cbp >> 2][0]);
1012 put_sbits(&s->pb, 2, cbp);
1016 for (i = 0; i < mb_block_count; i++)
1017 if (cbp & (1 << (mb_block_count - 1 - i)))
1018 mpeg1_encode_block(s, block[i], i);
1021 s->i_tex_bits += get_bits_diff(s);
1023 s->p_tex_bits += get_bits_diff(s);
1027 void ff_mpeg1_encode_mb(MpegEncContext *s, int16_t block[8][64],
1028 int motion_x, int motion_y)
1030 if (s->chroma_format == CHROMA_420)
1031 mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 6);
1033 mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 8);
1036 av_cold void ff_mpeg1_encode_init(MpegEncContext *s)
1038 static int done = 0;
1040 ff_mpeg12_common_init(s);
1048 ff_rl_init(&ff_rl_mpeg1, ff_mpeg12_static_rl_table_store[0]);
1049 ff_rl_init(&ff_rl_mpeg2, ff_mpeg12_static_rl_table_store[1]);
1051 for (i = 0; i < 64; i++) {
1052 mpeg1_max_level[0][i] = ff_rl_mpeg1.max_level[0][i];
1053 mpeg1_index_run[0][i] = ff_rl_mpeg1.index_run[0][i];
1056 init_uni_ac_vlc(&ff_rl_mpeg1, uni_mpeg1_ac_vlc_len);
1057 if (s->intra_vlc_format)
1058 init_uni_ac_vlc(&ff_rl_mpeg2, uni_mpeg2_ac_vlc_len);
1060 /* build unified dc encoding tables */
1061 for (i = -255; i < 256; i++) {
1066 adiff = FFABS(diff);
1069 index = av_log2(2 * adiff);
1071 bits = ff_mpeg12_vlc_dc_lum_bits[index] + index;
1072 code = (ff_mpeg12_vlc_dc_lum_code[index] << index) +
1073 av_mod_uintp2(diff, index);
1074 mpeg1_lum_dc_uni[i + 255] = bits + (code << 8);
1076 bits = ff_mpeg12_vlc_dc_chroma_bits[index] + index;
1077 code = (ff_mpeg12_vlc_dc_chroma_code[index] << index) +
1078 av_mod_uintp2(diff, index);
1079 mpeg1_chr_dc_uni[i + 255] = bits + (code << 8);
1082 for (f_code = 1; f_code <= MAX_FCODE; f_code++)
1083 for (mv = -MAX_DMV; mv <= MAX_DMV; mv++) {
1087 len = ff_mpeg12_mbMotionVectorTable[0][1];
1089 int val, bit_size, code;
1091 bit_size = f_code - 1;
1097 code = (val >> bit_size) + 1;
1099 len = ff_mpeg12_mbMotionVectorTable[code][1] +
1102 len = ff_mpeg12_mbMotionVectorTable[16][1] +
1106 mv_penalty[f_code][mv + MAX_DMV] = len;
1110 for (f_code = MAX_FCODE; f_code > 0; f_code--)
1111 for (mv = -(8 << f_code); mv < (8 << f_code); mv++)
1112 fcode_tab[mv + MAX_MV] = f_code;
1114 s->me.mv_penalty = mv_penalty;
1115 s->fcode_tab = fcode_tab;
1116 if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
1117 s->min_qcoeff = -255;
1118 s->max_qcoeff = 255;
1120 s->min_qcoeff = -2047;
1121 s->max_qcoeff = 2047;
1123 if (s->intra_vlc_format) {
1124 s->intra_ac_vlc_length =
1125 s->intra_ac_vlc_last_length = uni_mpeg2_ac_vlc_len;
1127 s->intra_ac_vlc_length =
1128 s->intra_ac_vlc_last_length = uni_mpeg1_ac_vlc_len;
1130 s->inter_ac_vlc_length =
1131 s->inter_ac_vlc_last_length = uni_mpeg1_ac_vlc_len;
1134 #define OFFSET(x) offsetof(MpegEncContext, x)
1135 #define VE AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
1136 #define COMMON_OPTS \
1137 { "gop_timecode", "MPEG GOP Timecode in hh:mm:ss[:;.]ff format. Overrides timecode_frame_start.", \
1138 OFFSET(tc_opt_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE },\
1139 { "intra_vlc", "Use MPEG-2 intra VLC table.", \
1140 OFFSET(intra_vlc_format), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
1141 { "drop_frame_timecode", "Timecode is in drop frame format.", \
1142 OFFSET(drop_frame_timecode), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
1143 { "scan_offset", "Reserve space for SVCD scan offset user data.", \
1144 OFFSET(scan_offset), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
1145 { "timecode_frame_start", "GOP timecode frame start number, in non-drop-frame format", \
1146 OFFSET(timecode_frame_start), AV_OPT_TYPE_INT64, {.i64 = -1 }, -1, INT64_MAX, VE}, \
1148 static const AVOption mpeg1_options[] = {
1154 static const AVOption mpeg2_options[] = {
1156 { "non_linear_quant", "Use nonlinear quantizer.", OFFSET(q_scale_type), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1157 { "alternate_scan", "Enable alternate scantable.", OFFSET(alternate_scan), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1158 { "seq_disp_ext", "Write sequence_display_extension blocks.", OFFSET(seq_disp_ext), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE, "seq_disp_ext" },
1159 { "auto", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = -1}, 0, 0, VE, "seq_disp_ext" },
1160 { "never", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, 0, 0, VE, "seq_disp_ext" },
1161 { "always", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, VE, "seq_disp_ext" },
1162 { "video_format", "Video_format in the sequence_display_extension indicating the source of the video.", OFFSET(video_format), AV_OPT_TYPE_INT, { .i64 = VIDEO_FORMAT_UNSPECIFIED }, 0, 7, VE, "video_format" },
1163 { "component", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VIDEO_FORMAT_COMPONENT }, 0, 0, VE, "video_format" },
1164 { "pal", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VIDEO_FORMAT_PAL }, 0, 0, VE, "video_format" },
1165 { "ntsc", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VIDEO_FORMAT_NTSC }, 0, 0, VE, "video_format" },
1166 { "secam", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VIDEO_FORMAT_SECAM }, 0, 0, VE, "video_format" },
1167 { "mac", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VIDEO_FORMAT_MAC }, 0, 0, VE, "video_format" },
1168 { "unspecified", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VIDEO_FORMAT_UNSPECIFIED}, 0, 0, VE, "video_format" },
1173 #define mpeg12_class(x) \
1174 static const AVClass mpeg ## x ## _class = { \
1175 .class_name = "mpeg" # x "video encoder", \
1176 .item_name = av_default_item_name, \
1177 .option = mpeg ## x ## _options, \
1178 .version = LIBAVUTIL_VERSION_INT, \
1184 AVCodec ff_mpeg1video_encoder = {
1185 .name = "mpeg1video",
1186 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
1187 .type = AVMEDIA_TYPE_VIDEO,
1188 .id = AV_CODEC_ID_MPEG1VIDEO,
1189 .priv_data_size = sizeof(MpegEncContext),
1190 .init = encode_init,
1191 .encode2 = ff_mpv_encode_picture,
1192 .close = ff_mpv_encode_end,
1193 .supported_framerates = ff_mpeg12_frame_rate_tab + 1,
1194 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P,
1196 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
1197 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
1198 .priv_class = &mpeg1_class,
1201 AVCodec ff_mpeg2video_encoder = {
1202 .name = "mpeg2video",
1203 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
1204 .type = AVMEDIA_TYPE_VIDEO,
1205 .id = AV_CODEC_ID_MPEG2VIDEO,
1206 .priv_data_size = sizeof(MpegEncContext),
1207 .init = encode_init,
1208 .encode2 = ff_mpv_encode_picture,
1209 .close = ff_mpv_encode_end,
1210 .supported_framerates = ff_mpeg2_frame_rate_tab,
1211 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P,
1214 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
1215 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
1216 .priv_class = &mpeg2_class,