2 * H.264 encoding using the x264 library
3 * Copyright (C) 2005 Mans Rullgard <mans@mansr.com>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "config_components.h"
24 #include "libavutil/buffer.h"
25 #include "libavutil/eval.h"
26 #include "libavutil/internal.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/mem.h"
29 #include "libavutil/pixdesc.h"
30 #include "libavutil/stereo3d.h"
31 #include "libavutil/time.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/video_hint.h"
35 #include "codec_internal.h"
38 #include "packet_internal.h"
49 // from x264.h, for quant_offsets, Macroblocks are 16x16
50 // blocks of pixels (with respect to the luma plane)
53 #define MB_FLOOR(x) ((x) >> (MB_LSIZE))
54 #define MB_CEIL(x) MB_FLOOR((x) + (MB_SIZE - 1))
56 typedef struct X264Opaque {
57 #if FF_API_REORDERED_OPAQUE
58 int64_t reordered_opaque;
64 AVBufferRef *frame_opaque_ref;
67 typedef struct X264Context {
114 int b_frame_strategy;
116 int scenechange_threshold;
120 AVDictionary *x264_params;
122 int nb_reordered_opaque, next_reordered_opaque;
123 X264Opaque *reordered_opaque;
126 * If the encoder does not support ROI then warn the first time we
127 * encounter a frame with ROI side data.
134 static void X264_log(void *p, int level, const char *fmt, va_list args)
136 static const int level_map[] = {
137 [X264_LOG_ERROR] = AV_LOG_ERROR,
138 [X264_LOG_WARNING] = AV_LOG_WARNING,
139 [X264_LOG_INFO] = AV_LOG_INFO,
140 [X264_LOG_DEBUG] = AV_LOG_DEBUG
143 if (level < 0 || level > X264_LOG_DEBUG)
146 av_vlog(p, level_map[level], fmt, args);
149 static void opaque_uninit(X264Opaque *o)
151 av_buffer_unref(&o->frame_opaque_ref);
152 memset(o, 0, sizeof(*o));
155 static int encode_nals(AVCodecContext *ctx, AVPacket *pkt,
156 const x264_nal_t *nals, int nnal)
158 X264Context *x4 = ctx->priv_data;
160 uint64_t size = FFMAX(x4->sei_size, 0);
166 for (int i = 0; i < nnal; i++) {
167 size += nals[i].i_payload;
168 /* ff_get_encode_buffer() accepts an int64_t and
169 * so we need to make sure that no overflow happens before
170 * that. With 32bit ints this is automatically true. */
171 #if INT_MAX > INT64_MAX / INT_MAX - 1
172 if ((int64_t)size < 0)
173 return AVERROR(ERANGE);
177 if ((ret = ff_get_encode_buffer(ctx, pkt, size, 0)) < 0)
182 /* Write the SEI as part of the first frame. */
183 if (x4->sei_size > 0) {
184 memcpy(p, x4->sei, x4->sei_size);
186 size -= x4->sei_size;
187 /* Keep the value around in case of flush */
188 x4->sei_size = -x4->sei_size;
191 /* x264 guarantees the payloads of the NALs
192 * to be sequential in memory. */
193 memcpy(p, nals[0].p_payload, size);
198 static void reconfig_encoder(AVCodecContext *ctx, const AVFrame *frame)
200 X264Context *x4 = ctx->priv_data;
201 AVFrameSideData *side_data;
204 if (x4->avcintra_class < 0) {
205 if (x4->params.b_interlaced && x4->params.b_tff != !!(frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST)) {
207 x4->params.b_tff = !!(frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST);
208 x264_encoder_reconfig(x4->enc, &x4->params);
210 if (x4->params.vui.i_sar_height*ctx->sample_aspect_ratio.num != ctx->sample_aspect_ratio.den * x4->params.vui.i_sar_width) {
211 x4->params.vui.i_sar_height = ctx->sample_aspect_ratio.den;
212 x4->params.vui.i_sar_width = ctx->sample_aspect_ratio.num;
213 x264_encoder_reconfig(x4->enc, &x4->params);
216 if (x4->params.rc.i_vbv_buffer_size != ctx->rc_buffer_size / 1000 ||
217 x4->params.rc.i_vbv_max_bitrate != ctx->rc_max_rate / 1000) {
218 x4->params.rc.i_vbv_buffer_size = ctx->rc_buffer_size / 1000;
219 x4->params.rc.i_vbv_max_bitrate = ctx->rc_max_rate / 1000;
220 x264_encoder_reconfig(x4->enc, &x4->params);
223 if (x4->params.rc.i_rc_method == X264_RC_ABR &&
224 x4->params.rc.i_bitrate != ctx->bit_rate / 1000) {
225 x4->params.rc.i_bitrate = ctx->bit_rate / 1000;
226 x264_encoder_reconfig(x4->enc, &x4->params);
230 x4->params.rc.i_rc_method == X264_RC_CRF &&
231 x4->params.rc.f_rf_constant != x4->crf) {
232 x4->params.rc.f_rf_constant = x4->crf;
233 x264_encoder_reconfig(x4->enc, &x4->params);
236 if (x4->params.rc.i_rc_method == X264_RC_CQP &&
238 x4->params.rc.i_qp_constant != x4->cqp) {
239 x4->params.rc.i_qp_constant = x4->cqp;
240 x264_encoder_reconfig(x4->enc, &x4->params);
243 if (x4->crf_max >= 0 &&
244 x4->params.rc.f_rf_constant_max != x4->crf_max) {
245 x4->params.rc.f_rf_constant_max = x4->crf_max;
246 x264_encoder_reconfig(x4->enc, &x4->params);
250 side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_STEREO3D);
252 AVStereo3D *stereo = (AVStereo3D *)side_data->data;
255 switch (stereo->type) {
256 case AV_STEREO3D_CHECKERBOARD:
259 case AV_STEREO3D_COLUMNS:
262 case AV_STEREO3D_LINES:
265 case AV_STEREO3D_SIDEBYSIDE:
268 case AV_STEREO3D_TOPBOTTOM:
271 case AV_STEREO3D_FRAMESEQUENCE:
274 #if X264_BUILD >= 145
284 /* Inverted mode is not supported by x264 */
285 if (stereo->flags & AV_STEREO3D_FLAG_INVERT) {
286 av_log(ctx, AV_LOG_WARNING,
287 "Ignoring unsupported inverted stereo value %d\n", fpa_type);
291 if (fpa_type != x4->params.i_frame_packing) {
292 x4->params.i_frame_packing = fpa_type;
293 x264_encoder_reconfig(x4->enc, &x4->params);
298 static void free_picture(x264_picture_t *pic)
300 for (int i = 0; i < pic->extra_sei.num_payloads; i++)
301 av_free(pic->extra_sei.payloads[i].payload);
302 av_freep(&pic->extra_sei.payloads);
303 av_freep(&pic->prop.quant_offsets);
304 av_freep(&pic->prop.mb_info);
305 pic->extra_sei.num_payloads = 0;
308 static enum AVPixelFormat csp_to_pixfmt(int csp)
312 case X264_CSP_I400: return AV_PIX_FMT_GRAY8;
313 case X264_CSP_I400 | X264_CSP_HIGH_DEPTH: return AV_PIX_FMT_GRAY10;
315 case X264_CSP_I420: return AV_PIX_FMT_YUV420P;
316 case X264_CSP_I420 | X264_CSP_HIGH_DEPTH: return AV_PIX_FMT_YUV420P10;
317 case X264_CSP_I422: return AV_PIX_FMT_YUV422P;
318 case X264_CSP_I422 | X264_CSP_HIGH_DEPTH: return AV_PIX_FMT_YUV422P10;
319 case X264_CSP_I444: return AV_PIX_FMT_YUV444P;
320 case X264_CSP_I444 | X264_CSP_HIGH_DEPTH: return AV_PIX_FMT_YUV444P10;
321 case X264_CSP_NV12: return AV_PIX_FMT_NV12;
323 case X264_CSP_NV21: return AV_PIX_FMT_NV21;
325 case X264_CSP_NV16: return AV_PIX_FMT_NV16;
327 return AV_PIX_FMT_NONE;
330 static void av_always_inline mbinfo_compute_changed_coords(const AVVideoRect *rect,
336 *min_y = MB_FLOOR(rect->y);
337 *max_y = MB_CEIL(rect->y + rect->height);
338 *min_x = MB_FLOOR(rect->x);
339 *max_x = MB_CEIL(rect->x + rect->width);
342 static void av_always_inline mbinfo_compute_constant_coords(const AVVideoRect *rect,
348 *min_y = MB_CEIL(rect->y);
349 *max_y = MB_FLOOR(rect->y + rect->height);
350 *min_x = MB_CEIL(rect->x);
351 *max_x = MB_FLOOR(rect->x + rect->width);
354 static int setup_mb_info(AVCodecContext *ctx, x264_picture_t *pic,
355 const AVFrame *frame,
356 const AVVideoHint *info)
358 int mb_width = (frame->width + MB_SIZE - 1) / MB_SIZE;
359 int mb_height = (frame->height + MB_SIZE - 1) / MB_SIZE;
361 const AVVideoRect *mbinfo_rects;
365 mbinfo_rects = (const AVVideoRect *)av_video_hint_rects(info);
366 nb_rects = info->nb_rects;
368 mbinfo = av_calloc(mb_width * mb_height, sizeof(*mbinfo));
370 return AVERROR(ENOMEM);
372 #define COMPUTE_MBINFO(mbinfo_filler_, mbinfo_marker_, compute_coords_fn_) \
373 memset(mbinfo, mbinfo_filler_, sizeof(*mbinfo) * mb_width * mb_height); \
375 for (int i = 0; i < nb_rects; i++) { \
376 int min_x, max_x, min_y, max_y; \
378 compute_coords_fn_(mbinfo_rects, &min_x, &max_x, &min_y, &max_y); \
379 for (int mb_y = min_y; mb_y < max_y; ++mb_y) { \
380 memset(mbinfo + mb_y * mb_width + min_x, mbinfo_marker_, max_x - min_x); \
386 if (info->type == AV_VIDEO_HINT_TYPE_CHANGED) {
387 COMPUTE_MBINFO(X264_MBINFO_CONSTANT, 0, mbinfo_compute_changed_coords);
388 } else /* if (info->type == AV_VIDEO_HINT_TYPE_CHANGED) */ {
389 COMPUTE_MBINFO(0, X264_MBINFO_CONSTANT, mbinfo_compute_constant_coords);
392 pic->prop.mb_info = mbinfo;
393 pic->prop.mb_info_free = av_free;
398 static int setup_roi(AVCodecContext *ctx, x264_picture_t *pic, int bit_depth,
399 const AVFrame *frame, const uint8_t *data, size_t size)
401 X264Context *x4 = ctx->priv_data;
403 int mbx = (frame->width + MB_SIZE - 1) / MB_SIZE;
404 int mby = (frame->height + MB_SIZE - 1) / MB_SIZE;
405 int qp_range = 51 + 6 * (bit_depth - 8);
407 const AVRegionOfInterest *roi;
411 if (x4->params.rc.i_aq_mode == X264_AQ_NONE) {
412 if (!x4->roi_warned) {
414 av_log(ctx, AV_LOG_WARNING, "Adaptive quantization must be enabled to use ROI encoding, skipping ROI.\n");
417 } else if (frame->flags & AV_FRAME_FLAG_INTERLACED) {
418 if (!x4->roi_warned) {
420 av_log(ctx, AV_LOG_WARNING, "interlaced_frame not supported for ROI encoding yet, skipping ROI.\n");
425 roi = (const AVRegionOfInterest*)data;
426 roi_size = roi->self_size;
427 if (!roi_size || size % roi_size != 0) {
428 av_log(ctx, AV_LOG_ERROR, "Invalid AVRegionOfInterest.self_size.\n");
429 return AVERROR(EINVAL);
431 nb_rois = size / roi_size;
433 qoffsets = av_calloc(mbx * mby, sizeof(*qoffsets));
435 return AVERROR(ENOMEM);
437 // This list must be iterated in reverse because the first
438 // region in the list applies when regions overlap.
439 for (int i = nb_rois - 1; i >= 0; i--) {
440 int startx, endx, starty, endy;
443 roi = (const AVRegionOfInterest*)(data + roi_size * i);
445 starty = FFMIN(mby, roi->top / MB_SIZE);
446 endy = FFMIN(mby, (roi->bottom + MB_SIZE - 1)/ MB_SIZE);
447 startx = FFMIN(mbx, roi->left / MB_SIZE);
448 endx = FFMIN(mbx, (roi->right + MB_SIZE - 1)/ MB_SIZE);
450 if (roi->qoffset.den == 0) {
452 av_log(ctx, AV_LOG_ERROR, "AVRegionOfInterest.qoffset.den must not be zero.\n");
453 return AVERROR(EINVAL);
455 qoffset = roi->qoffset.num * 1.0f / roi->qoffset.den;
456 qoffset = av_clipf(qoffset * qp_range, -qp_range, +qp_range);
458 for (int y = starty; y < endy; y++) {
459 for (int x = startx; x < endx; x++) {
460 qoffsets[x + y*mbx] = qoffset;
465 pic->prop.quant_offsets = qoffsets;
466 pic->prop.quant_offsets_free = av_free;
471 static int setup_frame(AVCodecContext *ctx, const AVFrame *frame,
472 x264_picture_t **ppic)
474 X264Context *x4 = ctx->priv_data;
475 X264Opaque *opaque = &x4->reordered_opaque[x4->next_reordered_opaque];
476 x264_picture_t *pic = &x4->pic;
477 x264_sei_t *sei = &pic->extra_sei;
478 unsigned int sei_data_size = 0;
479 int64_t wallclock = 0;
482 AVFrameSideData *mbinfo_sd;
488 x264_picture_init(pic);
489 pic->img.i_csp = x4->params.i_csp;
490 #if X264_BUILD >= 153
491 bit_depth = x4->params.i_bitdepth;
493 bit_depth = x264_bit_depth;
496 pic->img.i_csp |= X264_CSP_HIGH_DEPTH;
497 pic->img.i_plane = av_pix_fmt_count_planes(ctx->pix_fmt);
499 for (int i = 0; i < pic->img.i_plane; i++) {
500 pic->img.plane[i] = frame->data[i];
501 pic->img.i_stride[i] = frame->linesize[i];
504 pic->i_pts = frame->pts;
506 opaque_uninit(opaque);
508 if (ctx->flags & AV_CODEC_FLAG_COPY_OPAQUE) {
509 opaque->frame_opaque = frame->opaque;
510 ret = av_buffer_replace(&opaque->frame_opaque_ref, frame->opaque_ref);
515 #if FF_API_REORDERED_OPAQUE
516 FF_DISABLE_DEPRECATION_WARNINGS
517 opaque->reordered_opaque = frame->reordered_opaque;
518 FF_ENABLE_DEPRECATION_WARNINGS
520 opaque->duration = frame->duration;
521 opaque->wallclock = wallclock;
522 if (ctx->export_side_data & AV_CODEC_EXPORT_DATA_PRFT)
523 opaque->wallclock = av_gettime();
525 pic->opaque = opaque;
527 x4->next_reordered_opaque++;
528 x4->next_reordered_opaque %= x4->nb_reordered_opaque;
530 switch (frame->pict_type) {
531 case AV_PICTURE_TYPE_I:
532 pic->i_type = x4->forced_idr > 0 ? X264_TYPE_IDR : X264_TYPE_KEYFRAME;
534 case AV_PICTURE_TYPE_P:
535 pic->i_type = X264_TYPE_P;
537 case AV_PICTURE_TYPE_B:
538 pic->i_type = X264_TYPE_B;
541 pic->i_type = X264_TYPE_AUTO;
544 reconfig_encoder(ctx, frame);
550 ret = ff_alloc_a53_sei(frame, 0, &sei_data, &sei_size);
555 sei->payloads = av_mallocz(sizeof(sei->payloads[0]));
556 if (!sei->payloads) {
558 ret = AVERROR(ENOMEM);
562 sei->sei_free = av_free;
564 sei->payloads[0].payload_size = sei_size;
565 sei->payloads[0].payload = sei_data;
566 sei->payloads[0].payload_type = SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35;
567 sei->num_payloads = 1;
571 sd = av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
573 ret = setup_roi(ctx, pic, bit_depth, frame, sd->data, sd->size);
578 mbinfo_sd = av_frame_get_side_data(frame, AV_FRAME_DATA_VIDEO_HINT);
580 int ret = setup_mb_info(ctx, pic, frame, (const AVVideoHint *)mbinfo_sd->data);
582 /* No need to fail here, this is not fatal. We just proceed with no
583 * mb_info and log a message */
585 av_log(ctx, AV_LOG_WARNING, "setup_mb_info failed with error: %s\n", av_err2str(ret));
590 for (int j = 0; j < frame->nb_side_data; j++) {
591 AVFrameSideData *side_data = frame->side_data[j];
593 x264_sei_payload_t *sei_payload;
594 if (side_data->type != AV_FRAME_DATA_SEI_UNREGISTERED)
596 tmp = av_fast_realloc(sei->payloads, &sei_data_size, (sei->num_payloads + 1) * sizeof(*sei_payload));
598 ret = AVERROR(ENOMEM);
602 sei->sei_free = av_free;
603 sei_payload = &sei->payloads[sei->num_payloads];
604 sei_payload->payload = av_memdup(side_data->data, side_data->size);
605 if (!sei_payload->payload) {
606 ret = AVERROR(ENOMEM);
609 sei_payload->payload_size = side_data->size;
610 sei_payload->payload_type = SEI_TYPE_USER_DATA_UNREGISTERED;
624 static int X264_frame(AVCodecContext *ctx, AVPacket *pkt, const AVFrame *frame,
627 X264Context *x4 = ctx->priv_data;
630 x264_picture_t pic_out = {0}, *pic_in;
632 int64_t wallclock = 0;
633 X264Opaque *out_opaque;
635 ret = setup_frame(ctx, frame, &pic_in);
640 if (x264_encoder_encode(x4->enc, &nal, &nnal, pic_in, &pic_out) < 0)
641 return AVERROR_EXTERNAL;
643 if (nnal && (ctx->flags & AV_CODEC_FLAG_RECON_FRAME)) {
644 AVCodecInternal *avci = ctx->internal;
646 av_frame_unref(avci->recon_frame);
648 avci->recon_frame->format = csp_to_pixfmt(pic_out.img.i_csp);
649 if (avci->recon_frame->format == AV_PIX_FMT_NONE) {
650 av_log(ctx, AV_LOG_ERROR,
651 "Unhandled reconstructed frame colorspace: %d\n",
653 return AVERROR(ENOSYS);
656 avci->recon_frame->width = ctx->width;
657 avci->recon_frame->height = ctx->height;
658 for (int i = 0; i < pic_out.img.i_plane; i++) {
659 avci->recon_frame->data[i] = pic_out.img.plane[i];
660 avci->recon_frame->linesize[i] = pic_out.img.i_stride[i];
663 ret = av_frame_make_writable(avci->recon_frame);
665 av_frame_unref(avci->recon_frame);
670 ret = encode_nals(ctx, pkt, nal, nnal);
673 } while (!ret && !frame && x264_encoder_delayed_frames(x4->enc));
678 pkt->pts = pic_out.i_pts;
679 pkt->dts = pic_out.i_dts;
681 out_opaque = pic_out.opaque;
682 if (out_opaque >= x4->reordered_opaque &&
683 out_opaque < &x4->reordered_opaque[x4->nb_reordered_opaque]) {
684 #if FF_API_REORDERED_OPAQUE
685 FF_DISABLE_DEPRECATION_WARNINGS
686 ctx->reordered_opaque = out_opaque->reordered_opaque;
687 FF_ENABLE_DEPRECATION_WARNINGS
689 wallclock = out_opaque->wallclock;
690 pkt->duration = out_opaque->duration;
692 if (ctx->flags & AV_CODEC_FLAG_COPY_OPAQUE) {
693 pkt->opaque = out_opaque->frame_opaque;
694 pkt->opaque_ref = out_opaque->frame_opaque_ref;
695 out_opaque->frame_opaque_ref = NULL;
698 opaque_uninit(out_opaque);
700 // Unexpected opaque pointer on picture output
701 av_log(ctx, AV_LOG_ERROR, "Unexpected opaque pointer; "
702 "this is a bug, please report it.\n");
703 #if FF_API_REORDERED_OPAQUE
704 FF_DISABLE_DEPRECATION_WARNINGS
705 ctx->reordered_opaque = 0;
706 FF_ENABLE_DEPRECATION_WARNINGS
710 switch (pic_out.i_type) {
713 pict_type = AV_PICTURE_TYPE_I;
716 pict_type = AV_PICTURE_TYPE_P;
720 pict_type = AV_PICTURE_TYPE_B;
723 av_log(ctx, AV_LOG_ERROR, "Unknown picture type encountered.\n");
724 return AVERROR_EXTERNAL;
727 pkt->flags |= AV_PKT_FLAG_KEY*pic_out.b_keyframe;
730 int64_t *errors = NULL;
731 int64_t sse[3] = {0};
733 if (ctx->flags & AV_CODEC_FLAG_PSNR) {
734 const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(ctx->pix_fmt);
735 double scale[3] = { 1,
736 (double)(1 << pix_desc->log2_chroma_h) * (1 << pix_desc->log2_chroma_w),
737 (double)(1 << pix_desc->log2_chroma_h) * (1 << pix_desc->log2_chroma_w),
740 error_count = pix_desc->nb_components;
742 for (int i = 0; i < pix_desc->nb_components; ++i) {
743 double max_value = (double)(1 << pix_desc->comp[i].depth) - 1.0;
744 double plane_size = ctx->width * (double)ctx->height / scale[i];
746 /* psnr = 10 * log10(max_value * max_value / mse) */
747 double mse = (max_value * max_value) / pow(10, pic_out.prop.f_psnr[i] / 10.0);
749 /* SSE = MSE * width * height / scale -> because of possible chroma downsampling */
750 sse[i] = (int64_t)floor(mse * plane_size + .5);
756 ff_side_data_set_encoder_stats(pkt, (pic_out.i_qpplus1 - 1) * FF_QP2LAMBDA,
757 errors, error_count, pict_type);
760 ff_side_data_set_prft(pkt, wallclock);
767 static void X264_flush(AVCodecContext *avctx)
769 X264Context *x4 = avctx->priv_data;
772 x264_picture_t pic_out = {0};
775 ret = x264_encoder_encode(x4->enc, &nal, &nnal, NULL, &pic_out);
776 } while (ret > 0 && x264_encoder_delayed_frames(x4->enc));
778 for (int i = 0; i < x4->nb_reordered_opaque; i++)
779 opaque_uninit(&x4->reordered_opaque[i]);
781 if (x4->sei_size < 0)
782 x4->sei_size = -x4->sei_size;
785 static av_cold int X264_close(AVCodecContext *avctx)
787 X264Context *x4 = avctx->priv_data;
791 for (int i = 0; i < x4->nb_reordered_opaque; i++)
792 opaque_uninit(&x4->reordered_opaque[i]);
793 av_freep(&x4->reordered_opaque);
795 #if X264_BUILD >= 161
796 x264_param_cleanup(&x4->params);
800 x264_encoder_close(x4->enc);
807 static int parse_opts(AVCodecContext *avctx, const char *opt, const char *param)
809 X264Context *x4 = avctx->priv_data;
812 if ((ret = x264_param_parse(&x4->params, opt, param)) < 0) {
813 if (ret == X264_PARAM_BAD_NAME) {
814 av_log(avctx, AV_LOG_ERROR,
815 "bad option '%s': '%s'\n", opt, param);
816 ret = AVERROR(EINVAL);
817 #if X264_BUILD >= 161
818 } else if (ret == X264_PARAM_ALLOC_FAILED) {
819 av_log(avctx, AV_LOG_ERROR,
820 "out of memory parsing option '%s': '%s'\n", opt, param);
821 ret = AVERROR(ENOMEM);
824 av_log(avctx, AV_LOG_ERROR,
825 "bad value for '%s': '%s'\n", opt, param);
826 ret = AVERROR(EINVAL);
833 static int convert_pix_fmt(enum AVPixelFormat pix_fmt)
836 case AV_PIX_FMT_YUV420P:
837 case AV_PIX_FMT_YUVJ420P:
838 case AV_PIX_FMT_YUV420P9:
839 case AV_PIX_FMT_YUV420P10: return X264_CSP_I420;
840 case AV_PIX_FMT_YUV422P:
841 case AV_PIX_FMT_YUVJ422P:
842 case AV_PIX_FMT_YUV422P10: return X264_CSP_I422;
843 case AV_PIX_FMT_YUV444P:
844 case AV_PIX_FMT_YUVJ444P:
845 case AV_PIX_FMT_YUV444P9:
846 case AV_PIX_FMT_YUV444P10: return X264_CSP_I444;
847 case AV_PIX_FMT_BGR0:
848 return X264_CSP_BGRA;
849 case AV_PIX_FMT_BGR24:
852 case AV_PIX_FMT_RGB24:
854 case AV_PIX_FMT_NV12: return X264_CSP_NV12;
855 case AV_PIX_FMT_NV16:
856 case AV_PIX_FMT_NV20: return X264_CSP_NV16;
858 case AV_PIX_FMT_NV21: return X264_CSP_NV21;
861 case AV_PIX_FMT_GRAY8:
862 case AV_PIX_FMT_GRAY10: return X264_CSP_I400;
868 #define PARSE_X264_OPT(name, var)\
869 if (x4->var && x264_param_parse(&x4->params, name, x4->var) < 0) {\
870 av_log(avctx, AV_LOG_ERROR, "Error parsing option '%s' with value '%s'.\n", name, x4->var);\
871 return AVERROR(EINVAL);\
874 static av_cold int X264_init(AVCodecContext *avctx)
876 X264Context *x4 = avctx->priv_data;
877 AVCPBProperties *cpb_props;
881 if (avctx->global_quality > 0)
882 av_log(avctx, AV_LOG_WARNING, "-qscale is ignored, -crf is recommended.\n");
884 #if CONFIG_LIBX262_ENCODER
885 if (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
886 x4->params.b_mpeg2 = 1;
887 x264_param_default_mpeg2(&x4->params);
890 x264_param_default(&x4->params);
892 x4->params.b_deblocking_filter = avctx->flags & AV_CODEC_FLAG_LOOP_FILTER;
894 if (x4->preset || x4->tune)
895 if (x264_param_default_preset(&x4->params, x4->preset, x4->tune) < 0) {
897 av_log(avctx, AV_LOG_ERROR, "Error setting preset/tune %s/%s.\n", x4->preset, x4->tune);
898 av_log(avctx, AV_LOG_INFO, "Possible presets:");
899 for (i = 0; x264_preset_names[i]; i++)
900 av_log(avctx, AV_LOG_INFO, " %s", x264_preset_names[i]);
901 av_log(avctx, AV_LOG_INFO, "\n");
902 av_log(avctx, AV_LOG_INFO, "Possible tunes:");
903 for (i = 0; x264_tune_names[i]; i++)
904 av_log(avctx, AV_LOG_INFO, " %s", x264_tune_names[i]);
905 av_log(avctx, AV_LOG_INFO, "\n");
906 return AVERROR(EINVAL);
909 if (avctx->level > 0)
910 x4->params.i_level_idc = avctx->level;
912 x4->params.pf_log = X264_log;
913 x4->params.p_log_private = avctx;
914 x4->params.i_log_level = X264_LOG_DEBUG;
915 x4->params.i_csp = convert_pix_fmt(avctx->pix_fmt);
916 #if X264_BUILD >= 153
917 x4->params.i_bitdepth = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth;
920 PARSE_X264_OPT("weightp", wpredp);
922 if (avctx->bit_rate) {
923 if (avctx->bit_rate / 1000 > INT_MAX || avctx->rc_max_rate / 1000 > INT_MAX) {
924 av_log(avctx, AV_LOG_ERROR, "bit_rate and rc_max_rate > %d000 not supported by libx264\n", INT_MAX);
925 return AVERROR(EINVAL);
927 x4->params.rc.i_bitrate = avctx->bit_rate / 1000;
928 x4->params.rc.i_rc_method = X264_RC_ABR;
930 x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;
931 x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate / 1000;
932 x4->params.rc.b_stat_write = avctx->flags & AV_CODEC_FLAG_PASS1;
933 if (avctx->flags & AV_CODEC_FLAG_PASS2) {
934 x4->params.rc.b_stat_read = 1;
937 x4->params.rc.i_rc_method = X264_RC_CRF;
938 x4->params.rc.f_rf_constant = x4->crf;
939 } else if (x4->cqp >= 0) {
940 x4->params.rc.i_rc_method = X264_RC_CQP;
941 x4->params.rc.i_qp_constant = x4->cqp;
944 if (x4->crf_max >= 0)
945 x4->params.rc.f_rf_constant_max = x4->crf_max;
948 if (avctx->rc_buffer_size && avctx->rc_initial_buffer_occupancy > 0 &&
949 (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {
950 x4->params.rc.f_vbv_buffer_init =
951 (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;
954 PARSE_X264_OPT("level", level);
956 if (avctx->i_quant_factor > 0)
957 x4->params.rc.f_ip_factor = 1 / fabs(avctx->i_quant_factor);
958 if (avctx->b_quant_factor > 0)
959 x4->params.rc.f_pb_factor = avctx->b_quant_factor;
961 if (x4->chroma_offset)
962 x4->params.analyse.i_chroma_qp_offset = x4->chroma_offset;
964 if (avctx->gop_size >= 0)
965 x4->params.i_keyint_max = avctx->gop_size;
966 if (avctx->max_b_frames >= 0)
967 x4->params.i_bframe = avctx->max_b_frames;
969 if (x4->scenechange_threshold >= 0)
970 x4->params.i_scenecut_threshold = x4->scenechange_threshold;
972 if (avctx->qmin >= 0)
973 x4->params.rc.i_qp_min = avctx->qmin;
974 if (avctx->qmax >= 0)
975 x4->params.rc.i_qp_max = avctx->qmax;
976 if (avctx->max_qdiff >= 0)
977 x4->params.rc.i_qp_step = avctx->max_qdiff;
978 if (avctx->qblur >= 0)
979 x4->params.rc.f_qblur = avctx->qblur; /* temporally blur quants */
980 if (avctx->qcompress >= 0)
981 x4->params.rc.f_qcompress = avctx->qcompress; /* 0.0 => cbr, 1.0 => constant qp */
982 if (avctx->refs >= 0)
983 x4->params.i_frame_reference = avctx->refs;
984 else if (x4->params.i_level_idc > 0) {
986 int mbn = AV_CEIL_RSHIFT(avctx->width, 4) * AV_CEIL_RSHIFT(avctx->height, 4);
987 int scale = X264_BUILD < 129 ? 384 : 1;
989 for (i = 0; i<x264_levels[i].level_idc; i++)
990 if (x264_levels[i].level_idc == x4->params.i_level_idc)
991 x4->params.i_frame_reference = av_clip(x264_levels[i].dpb / mbn / scale, 1, x4->params.i_frame_reference);
994 if (avctx->trellis >= 0)
995 x4->params.analyse.i_trellis = avctx->trellis;
996 if (avctx->me_range >= 0)
997 x4->params.analyse.i_me_range = avctx->me_range;
998 if (x4->noise_reduction >= 0)
999 x4->params.analyse.i_noise_reduction = x4->noise_reduction;
1000 if (avctx->me_subpel_quality >= 0)
1001 x4->params.analyse.i_subpel_refine = avctx->me_subpel_quality;
1002 if (avctx->keyint_min >= 0)
1003 x4->params.i_keyint_min = avctx->keyint_min;
1004 if (avctx->me_cmp >= 0)
1005 x4->params.analyse.b_chroma_me = avctx->me_cmp & FF_CMP_CHROMA;
1007 if (x4->aq_mode >= 0)
1008 x4->params.rc.i_aq_mode = x4->aq_mode;
1009 if (x4->aq_strength >= 0)
1010 x4->params.rc.f_aq_strength = x4->aq_strength;
1011 PARSE_X264_OPT("psy-rd", psy_rd);
1012 PARSE_X264_OPT("deblock", deblock);
1013 PARSE_X264_OPT("partitions", partitions);
1014 PARSE_X264_OPT("stats", stats);
1016 x4->params.analyse.b_psy = x4->psy;
1017 if (x4->rc_lookahead >= 0)
1018 x4->params.rc.i_lookahead = x4->rc_lookahead;
1019 if (x4->weightp >= 0)
1020 x4->params.analyse.i_weighted_pred = x4->weightp;
1021 if (x4->weightb >= 0)
1022 x4->params.analyse.b_weighted_bipred = x4->weightb;
1023 if (x4->cplxblur >= 0)
1024 x4->params.rc.f_complexity_blur = x4->cplxblur;
1027 x4->params.analyse.b_ssim = x4->ssim;
1028 if (x4->intra_refresh >= 0)
1029 x4->params.b_intra_refresh = x4->intra_refresh;
1030 if (x4->bluray_compat >= 0) {
1031 x4->params.b_bluray_compat = x4->bluray_compat;
1032 x4->params.b_vfr_input = 0;
1034 if (x4->avcintra_class >= 0)
1035 #if X264_BUILD >= 142
1036 x4->params.i_avcintra_class = x4->avcintra_class;
1038 av_log(avctx, AV_LOG_ERROR,
1039 "x264 too old for AVC Intra, at least version 142 needed\n");
1042 if (x4->avcintra_class > 200) {
1043 #if X264_BUILD < 164
1044 av_log(avctx, AV_LOG_ERROR,
1045 "x264 too old for AVC Intra 300/480, at least version 164 needed\n");
1046 return AVERROR(EINVAL);
1048 /* AVC-Intra 300/480 only supported by Sony XAVC flavor */
1049 x4->params.i_avcintra_flavor = X264_AVCINTRA_FLAVOR_SONY;
1053 if (x4->b_bias != INT_MIN)
1054 x4->params.i_bframe_bias = x4->b_bias;
1055 if (x4->b_pyramid >= 0)
1056 x4->params.i_bframe_pyramid = x4->b_pyramid;
1057 if (x4->mixed_refs >= 0)
1058 x4->params.analyse.b_mixed_references = x4->mixed_refs;
1059 if (x4->dct8x8 >= 0)
1060 x4->params.analyse.b_transform_8x8 = x4->dct8x8;
1061 if (x4->fast_pskip >= 0)
1062 x4->params.analyse.b_fast_pskip = x4->fast_pskip;
1064 x4->params.b_aud = x4->aud;
1065 if (x4->mbtree >= 0)
1066 x4->params.rc.b_mb_tree = x4->mbtree;
1067 if (x4->direct_pred >= 0)
1068 x4->params.analyse.i_direct_mv_pred = x4->direct_pred;
1070 if (x4->slice_max_size >= 0)
1071 x4->params.i_slice_max_size = x4->slice_max_size;
1073 if (x4->fastfirstpass)
1074 x264_param_apply_fastfirstpass(&x4->params);
1076 x4->profile = x4->profile_opt;
1077 /* Allow specifying the x264 profile through AVCodecContext. */
1079 switch (avctx->profile) {
1080 case AV_PROFILE_H264_BASELINE:
1081 x4->profile = "baseline";
1083 case AV_PROFILE_H264_HIGH:
1084 x4->profile = "high";
1086 case AV_PROFILE_H264_HIGH_10:
1087 x4->profile = "high10";
1089 case AV_PROFILE_H264_HIGH_422:
1090 x4->profile = "high422";
1092 case AV_PROFILE_H264_HIGH_444:
1093 x4->profile = "high444";
1095 case AV_PROFILE_H264_MAIN:
1096 x4->profile = "main";
1102 if (x4->nal_hrd >= 0)
1103 x4->params.i_nal_hrd = x4->nal_hrd;
1105 if (x4->motion_est >= 0)
1106 x4->params.analyse.i_me_method = x4->motion_est;
1109 x4->params.b_cabac = x4->coder;
1111 if (x4->b_frame_strategy >= 0)
1112 x4->params.i_bframe_adaptive = x4->b_frame_strategy;
1115 if (x264_param_apply_profile(&x4->params, x4->profile) < 0) {
1117 av_log(avctx, AV_LOG_ERROR, "Error setting profile %s.\n", x4->profile);
1118 av_log(avctx, AV_LOG_INFO, "Possible profiles:");
1119 for (i = 0; x264_profile_names[i]; i++)
1120 av_log(avctx, AV_LOG_INFO, " %s", x264_profile_names[i]);
1121 av_log(avctx, AV_LOG_INFO, "\n");
1122 return AVERROR(EINVAL);
1125 x4->params.i_width = avctx->width;
1126 x4->params.i_height = avctx->height;
1127 av_reduce(&sw, &sh, avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den, 4096);
1128 x4->params.vui.i_sar_width = sw;
1129 x4->params.vui.i_sar_height = sh;
1130 x4->params.i_timebase_den = avctx->time_base.den;
1131 x4->params.i_timebase_num = avctx->time_base.num;
1132 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
1133 x4->params.i_fps_num = avctx->framerate.num;
1134 x4->params.i_fps_den = avctx->framerate.den;
1136 x4->params.i_fps_num = avctx->time_base.den;
1137 FF_DISABLE_DEPRECATION_WARNINGS
1138 x4->params.i_fps_den = avctx->time_base.num
1139 #if FF_API_TICKS_PER_FRAME
1140 * avctx->ticks_per_frame
1143 FF_ENABLE_DEPRECATION_WARNINGS
1146 x4->params.analyse.b_psnr = avctx->flags & AV_CODEC_FLAG_PSNR;
1148 x4->params.i_threads = avctx->thread_count;
1149 if (avctx->thread_type)
1150 x4->params.b_sliced_threads = avctx->thread_type == FF_THREAD_SLICE;
1152 x4->params.b_interlaced = avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT;
1154 x4->params.b_open_gop = !(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1156 x4->params.i_slice_count = avctx->slices;
1158 if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED)
1159 x4->params.vui.b_fullrange = avctx->color_range == AVCOL_RANGE_JPEG;
1160 else if (avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||
1161 avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
1162 avctx->pix_fmt == AV_PIX_FMT_YUVJ444P)
1163 x4->params.vui.b_fullrange = 1;
1165 if (avctx->colorspace != AVCOL_SPC_UNSPECIFIED)
1166 x4->params.vui.i_colmatrix = avctx->colorspace;
1167 if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED)
1168 x4->params.vui.i_colorprim = avctx->color_primaries;
1169 if (avctx->color_trc != AVCOL_TRC_UNSPECIFIED)
1170 x4->params.vui.i_transfer = avctx->color_trc;
1171 if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
1172 x4->params.vui.i_chroma_loc = avctx->chroma_sample_location - 1;
1174 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)
1175 x4->params.b_repeat_headers = 0;
1177 if (avctx->flags & AV_CODEC_FLAG_RECON_FRAME)
1178 x4->params.b_full_recon = 1;
1181 const char *p= x4->x264opts;
1183 char param[4096]={0}, val[4096]={0};
1184 if(sscanf(p, "%4095[^:=]=%4095[^:]", param, val) == 1){
1185 ret = parse_opts(avctx, param, "1");
1189 ret = parse_opts(avctx, param, val);
1200 #if X264_BUILD >= 142
1201 /* Separate headers not supported in AVC-Intra mode */
1202 if (x4->avcintra_class >= 0)
1203 x4->params.b_repeat_headers = 1;
1207 AVDictionaryEntry *en = NULL;
1208 while (en = av_dict_get(x4->x264_params, "", en, AV_DICT_IGNORE_SUFFIX)) {
1209 if ((ret = x264_param_parse(&x4->params, en->key, en->value)) < 0) {
1210 av_log(avctx, AV_LOG_WARNING,
1211 "Error parsing option '%s = %s'.\n",
1212 en->key, en->value);
1213 #if X264_BUILD >= 161
1214 if (ret == X264_PARAM_ALLOC_FAILED)
1215 return AVERROR(ENOMEM);
1221 x4->params.analyse.b_mb_info = x4->mb_info;
1223 // update AVCodecContext with x264 parameters
1224 avctx->has_b_frames = x4->params.i_bframe ?
1225 x4->params.i_bframe_pyramid ? 2 : 1 : 0;
1226 if (avctx->max_b_frames < 0)
1227 avctx->max_b_frames = 0;
1229 avctx->bit_rate = x4->params.rc.i_bitrate*1000LL;
1231 x4->enc = x264_encoder_open(&x4->params);
1233 return AVERROR_EXTERNAL;
1235 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1240 s = x264_encoder_headers(x4->enc, &nal, &nnal);
1241 avctx->extradata = p = av_mallocz(s + AV_INPUT_BUFFER_PADDING_SIZE);
1243 return AVERROR(ENOMEM);
1245 for (i = 0; i < nnal; i++) {
1246 /* Don't put the SEI in extradata. */
1247 if (nal[i].i_type == NAL_SEI) {
1248 av_log(avctx, AV_LOG_INFO, "%s\n", nal[i].p_payload+25);
1249 x4->sei_size = nal[i].i_payload;
1250 x4->sei = av_malloc(x4->sei_size);
1252 return AVERROR(ENOMEM);
1253 memcpy(x4->sei, nal[i].p_payload, nal[i].i_payload);
1256 memcpy(p, nal[i].p_payload, nal[i].i_payload);
1257 p += nal[i].i_payload;
1259 avctx->extradata_size = p - avctx->extradata;
1262 cpb_props = ff_encode_add_cpb_side_data(avctx);
1264 return AVERROR(ENOMEM);
1265 cpb_props->buffer_size = x4->params.rc.i_vbv_buffer_size * 1000;
1266 cpb_props->max_bitrate = x4->params.rc.i_vbv_max_bitrate * 1000LL;
1267 cpb_props->avg_bitrate = x4->params.rc.i_bitrate * 1000LL;
1269 // Overestimate the reordered opaque buffer size, in case a runtime
1270 // reconfigure would increase the delay (which it shouldn't).
1271 x4->nb_reordered_opaque = x264_encoder_maximum_delayed_frames(x4->enc) + 17;
1272 x4->reordered_opaque = av_calloc(x4->nb_reordered_opaque,
1273 sizeof(*x4->reordered_opaque));
1274 if (!x4->reordered_opaque) {
1275 x4->nb_reordered_opaque = 0;
1276 return AVERROR(ENOMEM);
1282 static const enum AVPixelFormat pix_fmts_8bit[] = {
1284 AV_PIX_FMT_YUVJ420P,
1286 AV_PIX_FMT_YUVJ422P,
1288 AV_PIX_FMT_YUVJ444P,
1291 #ifdef X264_CSP_NV21
1296 static const enum AVPixelFormat pix_fmts_9bit[] = {
1297 AV_PIX_FMT_YUV420P9,
1298 AV_PIX_FMT_YUV444P9,
1301 static const enum AVPixelFormat pix_fmts_10bit[] = {
1302 AV_PIX_FMT_YUV420P10,
1303 AV_PIX_FMT_YUV422P10,
1304 AV_PIX_FMT_YUV444P10,
1308 static const enum AVPixelFormat pix_fmts_all[] = {
1310 AV_PIX_FMT_YUVJ420P,
1312 AV_PIX_FMT_YUVJ422P,
1314 AV_PIX_FMT_YUVJ444P,
1317 #ifdef X264_CSP_NV21
1320 AV_PIX_FMT_YUV420P10,
1321 AV_PIX_FMT_YUV422P10,
1322 AV_PIX_FMT_YUV444P10,
1324 #ifdef X264_CSP_I400
1330 #if CONFIG_LIBX264RGB_ENCODER
1331 static const enum AVPixelFormat pix_fmts_8bit_rgb[] = {
1339 #if X264_BUILD < 153
1340 static av_cold void X264_init_static(FFCodec *codec)
1342 if (x264_bit_depth == 8)
1343 codec->p.pix_fmts = pix_fmts_8bit;
1344 else if (x264_bit_depth == 9)
1345 codec->p.pix_fmts = pix_fmts_9bit;
1346 else if (x264_bit_depth == 10)
1347 codec->p.pix_fmts = pix_fmts_10bit;
1351 #define OFFSET(x) offsetof(X264Context, x)
1352 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1353 static const AVOption options[] = {
1354 { "preset", "Set the encoding preset (cf. x264 --fullhelp)", OFFSET(preset), AV_OPT_TYPE_STRING, { .str = "medium" }, 0, 0, VE},
1355 { "tune", "Tune the encoding params (cf. x264 --fullhelp)", OFFSET(tune), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE},
1356 { "profile", "Set profile restrictions (cf. x264 --fullhelp)", OFFSET(profile_opt), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE},
1357 { "fastfirstpass", "Use fast settings when encoding first pass", OFFSET(fastfirstpass), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, VE},
1358 {"level", "Specify level (as defined by Annex A)", OFFSET(level), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
1359 {"passlogfile", "Filename for 2 pass stats", OFFSET(stats), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
1360 {"wpredp", "Weighted prediction for P-frames", OFFSET(wpredp), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
1361 {"a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, VE},
1362 {"x264opts", "x264 options", OFFSET(x264opts), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
1363 { "crf", "Select the quality for constant quality mode", OFFSET(crf), AV_OPT_TYPE_FLOAT, {.dbl = -1 }, -1, FLT_MAX, VE },
1364 { "crf_max", "In CRF mode, prevents VBV from lowering quality beyond this point.",OFFSET(crf_max), AV_OPT_TYPE_FLOAT, {.dbl = -1 }, -1, FLT_MAX, VE },
1365 { "qp", "Constant quantization parameter rate control method",OFFSET(cqp), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE },
1366 { "aq-mode", "AQ method", OFFSET(aq_mode), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE, "aq_mode"},
1367 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = X264_AQ_NONE}, INT_MIN, INT_MAX, VE, "aq_mode" },
1368 { "variance", "Variance AQ (complexity mask)", 0, AV_OPT_TYPE_CONST, {.i64 = X264_AQ_VARIANCE}, INT_MIN, INT_MAX, VE, "aq_mode" },
1369 { "autovariance", "Auto-variance AQ", 0, AV_OPT_TYPE_CONST, {.i64 = X264_AQ_AUTOVARIANCE}, INT_MIN, INT_MAX, VE, "aq_mode" },
1370 #if X264_BUILD >= 144
1371 { "autovariance-biased", "Auto-variance AQ with bias to dark scenes", 0, AV_OPT_TYPE_CONST, {.i64 = X264_AQ_AUTOVARIANCE_BIASED}, INT_MIN, INT_MAX, VE, "aq_mode" },
1373 { "aq-strength", "AQ strength. Reduces blocking and blurring in flat and textured areas.", OFFSET(aq_strength), AV_OPT_TYPE_FLOAT, {.dbl = -1}, -1, FLT_MAX, VE},
1374 { "psy", "Use psychovisual optimizations.", OFFSET(psy), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE },
1375 { "psy-rd", "Strength of psychovisual optimization, in <psy-rd>:<psy-trellis> format.", OFFSET(psy_rd), AV_OPT_TYPE_STRING, {0 }, 0, 0, VE},
1376 { "rc-lookahead", "Number of frames to look ahead for frametype and ratecontrol", OFFSET(rc_lookahead), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE },
1377 { "weightb", "Weighted prediction for B-frames.", OFFSET(weightb), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE },
1378 { "weightp", "Weighted prediction analysis method.", OFFSET(weightp), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE, "weightp" },
1379 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = X264_WEIGHTP_NONE}, INT_MIN, INT_MAX, VE, "weightp" },
1380 { "simple", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = X264_WEIGHTP_SIMPLE}, INT_MIN, INT_MAX, VE, "weightp" },
1381 { "smart", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = X264_WEIGHTP_SMART}, INT_MIN, INT_MAX, VE, "weightp" },
1382 { "ssim", "Calculate and print SSIM stats.", OFFSET(ssim), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE },
1383 { "intra-refresh", "Use Periodic Intra Refresh instead of IDR frames.",OFFSET(intra_refresh),AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE },
1384 { "bluray-compat", "Bluray compatibility workarounds.", OFFSET(bluray_compat) ,AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE },
1385 { "b-bias", "Influences how often B-frames are used", OFFSET(b_bias), AV_OPT_TYPE_INT, { .i64 = INT_MIN}, INT_MIN, INT_MAX, VE },
1386 { "b-pyramid", "Keep some B-frames as references.", OFFSET(b_pyramid), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE, "b_pyramid" },
1387 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = X264_B_PYRAMID_NONE}, INT_MIN, INT_MAX, VE, "b_pyramid" },
1388 { "strict", "Strictly hierarchical pyramid", 0, AV_OPT_TYPE_CONST, {.i64 = X264_B_PYRAMID_STRICT}, INT_MIN, INT_MAX, VE, "b_pyramid" },
1389 { "normal", "Non-strict (not Blu-ray compatible)", 0, AV_OPT_TYPE_CONST, {.i64 = X264_B_PYRAMID_NORMAL}, INT_MIN, INT_MAX, VE, "b_pyramid" },
1390 { "mixed-refs", "One reference per partition, as opposed to one reference per macroblock", OFFSET(mixed_refs), AV_OPT_TYPE_BOOL, { .i64 = -1}, -1, 1, VE },
1391 { "8x8dct", "High profile 8x8 transform.", OFFSET(dct8x8), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE},
1392 { "fast-pskip", NULL, OFFSET(fast_pskip), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE},
1393 { "aud", "Use access unit delimiters.", OFFSET(aud), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE},
1394 { "mbtree", "Use macroblock tree ratecontrol.", OFFSET(mbtree), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE},
1395 { "deblock", "Loop filter parameters, in <alpha:beta> form.", OFFSET(deblock), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE},
1396 { "cplxblur", "Reduce fluctuations in QP (before curve compression)", OFFSET(cplxblur), AV_OPT_TYPE_FLOAT, {.dbl = -1 }, -1, FLT_MAX, VE},
1397 { "partitions", "A comma-separated list of partitions to consider. "
1398 "Possible values: p8x8, p4x4, b8x8, i8x8, i4x4, none, all", OFFSET(partitions), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE},
1399 { "direct-pred", "Direct MV prediction mode", OFFSET(direct_pred), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE, "direct-pred" },
1400 { "none", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = X264_DIRECT_PRED_NONE }, 0, 0, VE, "direct-pred" },
1401 { "spatial", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = X264_DIRECT_PRED_SPATIAL }, 0, 0, VE, "direct-pred" },
1402 { "temporal", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = X264_DIRECT_PRED_TEMPORAL }, 0, 0, VE, "direct-pred" },
1403 { "auto", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = X264_DIRECT_PRED_AUTO }, 0, 0, VE, "direct-pred" },
1404 { "slice-max-size","Limit the size of each slice in bytes", OFFSET(slice_max_size),AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE },
1405 { "stats", "Filename for 2 pass stats", OFFSET(stats), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
1406 { "nal-hrd", "Signal HRD information (requires vbv-bufsize; "
1407 "cbr not allowed in .mp4)", OFFSET(nal_hrd), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE, "nal-hrd" },
1408 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = X264_NAL_HRD_NONE}, INT_MIN, INT_MAX, VE, "nal-hrd" },
1409 { "vbr", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = X264_NAL_HRD_VBR}, INT_MIN, INT_MAX, VE, "nal-hrd" },
1410 { "cbr", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = X264_NAL_HRD_CBR}, INT_MIN, INT_MAX, VE, "nal-hrd" },
1411 { "avcintra-class","AVC-Intra class 50/100/200/300/480", OFFSET(avcintra_class),AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 480 , VE},
1412 { "me_method", "Set motion estimation method", OFFSET(motion_est), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, X264_ME_TESA, VE, "motion-est"},
1413 { "motion-est", "Set motion estimation method", OFFSET(motion_est), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, X264_ME_TESA, VE, "motion-est"},
1414 { "dia", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = X264_ME_DIA }, INT_MIN, INT_MAX, VE, "motion-est" },
1415 { "hex", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = X264_ME_HEX }, INT_MIN, INT_MAX, VE, "motion-est" },
1416 { "umh", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = X264_ME_UMH }, INT_MIN, INT_MAX, VE, "motion-est" },
1417 { "esa", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = X264_ME_ESA }, INT_MIN, INT_MAX, VE, "motion-est" },
1418 { "tesa", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = X264_ME_TESA }, INT_MIN, INT_MAX, VE, "motion-est" },
1419 { "forced-idr", "If forcing keyframes, force them as IDR frames.", OFFSET(forced_idr), AV_OPT_TYPE_BOOL, { .i64 = 0 }, -1, 1, VE },
1420 { "coder", "Coder type", OFFSET(coder), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE, "coder" },
1421 { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, VE, "coder" },
1422 { "cavlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "coder" },
1423 { "cabac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "coder" },
1424 { "vlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "coder" },
1425 { "ac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "coder" },
1426 { "b_strategy", "Strategy to choose between I/P/B-frames", OFFSET(b_frame_strategy), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 2, VE },
1427 { "chromaoffset", "QP difference between chroma and luma", OFFSET(chroma_offset), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, VE },
1428 { "sc_threshold", "Scene change threshold", OFFSET(scenechange_threshold), AV_OPT_TYPE_INT, { .i64 = -1 }, INT_MIN, INT_MAX, VE },
1429 { "noise_reduction", "Noise reduction", OFFSET(noise_reduction), AV_OPT_TYPE_INT, { .i64 = -1 }, INT_MIN, INT_MAX, VE },
1430 { "udu_sei", "Use user data unregistered SEI if available", OFFSET(udu_sei), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1431 { "x264-params", "Override the x264 configuration using a :-separated list of key=value parameters", OFFSET(x264_params), AV_OPT_TYPE_DICT, { 0 }, 0, 0, VE },
1432 { "mb_info", "Set mb_info data through AVSideData, only useful when used from the API", OFFSET(mb_info), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1436 static const FFCodecDefault x264_defaults[] = {
1441 { "i_qfactor", "-1" },
1442 { "b_qfactor", "-1" },
1448 // { "rc_lookahead", "-1" },
1450 { "trellis", "-1" },
1451 { "me_range", "-1" },
1453 { "keyint_min", "-1" },
1455 { "threads", AV_STRINGIFY(X264_THREADS_AUTO) },
1456 { "thread_type", "0" },
1457 { "flags", "+cgop" },
1458 { "rc_init_occupancy","-1" },
1462 #if CONFIG_LIBX264_ENCODER
1463 static const AVClass x264_class = {
1464 .class_name = "libx264",
1465 .item_name = av_default_item_name,
1467 .version = LIBAVUTIL_VERSION_INT,
1470 #if X264_BUILD >= 153
1473 FFCodec ff_libx264_encoder = {
1474 .p.name = "libx264",
1475 CODEC_LONG_NAME("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1476 .p.type = AVMEDIA_TYPE_VIDEO,
1477 .p.id = AV_CODEC_ID_H264,
1478 .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
1479 AV_CODEC_CAP_OTHER_THREADS |
1480 AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE |
1481 AV_CODEC_CAP_ENCODER_FLUSH |
1482 AV_CODEC_CAP_ENCODER_RECON_FRAME,
1483 .p.priv_class = &x264_class,
1484 .p.wrapper_name = "libx264",
1485 .priv_data_size = sizeof(X264Context),
1487 FF_CODEC_ENCODE_CB(X264_frame),
1488 .flush = X264_flush,
1489 .close = X264_close,
1490 .defaults = x264_defaults,
1491 #if X264_BUILD < 153
1492 .init_static_data = X264_init_static,
1494 .p.pix_fmts = pix_fmts_all,
1496 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP | FF_CODEC_CAP_AUTO_THREADS
1497 #if X264_BUILD < 158
1498 | FF_CODEC_CAP_NOT_INIT_THREADSAFE
1504 #if CONFIG_LIBX264RGB_ENCODER
1505 static const AVClass rgbclass = {
1506 .class_name = "libx264rgb",
1507 .item_name = av_default_item_name,
1509 .version = LIBAVUTIL_VERSION_INT,
1512 const FFCodec ff_libx264rgb_encoder = {
1513 .p.name = "libx264rgb",
1514 CODEC_LONG_NAME("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 RGB"),
1515 .p.type = AVMEDIA_TYPE_VIDEO,
1516 .p.id = AV_CODEC_ID_H264,
1517 .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
1518 AV_CODEC_CAP_OTHER_THREADS |
1519 AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE,
1520 .p.pix_fmts = pix_fmts_8bit_rgb,
1521 .p.priv_class = &rgbclass,
1522 .p.wrapper_name = "libx264",
1523 .priv_data_size = sizeof(X264Context),
1525 FF_CODEC_ENCODE_CB(X264_frame),
1526 .close = X264_close,
1527 .defaults = x264_defaults,
1528 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP | FF_CODEC_CAP_AUTO_THREADS
1529 #if X264_BUILD < 158
1530 | FF_CODEC_CAP_NOT_INIT_THREADSAFE
1536 #if CONFIG_LIBX262_ENCODER
1537 static const AVClass X262_class = {
1538 .class_name = "libx262",
1539 .item_name = av_default_item_name,
1541 .version = LIBAVUTIL_VERSION_INT,
1544 const FFCodec ff_libx262_encoder = {
1545 .p.name = "libx262",
1546 CODEC_LONG_NAME("libx262 MPEG2VIDEO"),
1547 .p.type = AVMEDIA_TYPE_VIDEO,
1548 .p.id = AV_CODEC_ID_MPEG2VIDEO,
1549 .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
1550 AV_CODEC_CAP_OTHER_THREADS |
1551 AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE,
1552 .p.pix_fmts = pix_fmts_8bit,
1553 .p.priv_class = &X262_class,
1554 .p.wrapper_name = "libx264",
1555 .priv_data_size = sizeof(X264Context),
1557 FF_CODEC_ENCODE_CB(X264_frame),
1558 .close = X264_close,
1559 .defaults = x264_defaults,
1560 .caps_internal = FF_CODEC_CAP_NOT_INIT_THREADSAFE |
1561 FF_CODEC_CAP_INIT_CLEANUP | FF_CODEC_CAP_AUTO_THREADS,