• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

libavcodec/libx264.c

Go to the documentation of this file.
00001 /*
00002  * H.264 encoding using the x264 library
00003  * Copyright (C) 2005  Mans Rullgard <mans@mansr.com>
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include "libavutil/opt.h"
00023 #include "avcodec.h"
00024 #include <x264.h>
00025 #include <math.h>
00026 #include <stdio.h>
00027 #include <stdlib.h>
00028 #include <string.h>
00029 
00030 typedef struct X264Context {
00031     AVClass        *class;
00032     x264_param_t    params;
00033     x264_t         *enc;
00034     x264_picture_t  pic;
00035     uint8_t        *sei;
00036     int             sei_size;
00037     AVFrame         out_pic;
00038     char *preset;
00039     char *tune;
00040     char *profile;
00041     char *level;
00042     int fastfirstpass;
00043     char *stats;
00044     char *weightp;
00045     char *x264opts;
00046 } X264Context;
00047 
00048 static void X264_log(void *p, int level, const char *fmt, va_list args)
00049 {
00050     static const int level_map[] = {
00051         [X264_LOG_ERROR]   = AV_LOG_ERROR,
00052         [X264_LOG_WARNING] = AV_LOG_WARNING,
00053         [X264_LOG_INFO]    = AV_LOG_INFO,
00054         [X264_LOG_DEBUG]   = AV_LOG_DEBUG
00055     };
00056 
00057     if (level < 0 || level > X264_LOG_DEBUG)
00058         return;
00059 
00060     av_vlog(p, level_map[level], fmt, args);
00061 }
00062 
00063 
00064 static int encode_nals(AVCodecContext *ctx, uint8_t *buf, int size,
00065                        x264_nal_t *nals, int nnal, int skip_sei)
00066 {
00067     X264Context *x4 = ctx->priv_data;
00068     uint8_t *p = buf;
00069     int i;
00070 
00071     /* Write the SEI as part of the first frame. */
00072     if (x4->sei_size > 0 && nnal > 0) {
00073         if (x4->sei_size > size) {
00074             av_log(ctx, AV_LOG_ERROR, "Error: nal buffer is too small\n");
00075             return -1;
00076         }
00077         memcpy(p, x4->sei, x4->sei_size);
00078         p += x4->sei_size;
00079         x4->sei_size = 0;
00080         // why is x4->sei not freed?
00081     }
00082 
00083     for (i = 0; i < nnal; i++){
00084         /* Don't put the SEI in extradata. */
00085         if (skip_sei && nals[i].i_type == NAL_SEI) {
00086             x4->sei_size = nals[i].i_payload;
00087             x4->sei      = av_malloc(x4->sei_size);
00088             memcpy(x4->sei, nals[i].p_payload, nals[i].i_payload);
00089             continue;
00090         }
00091         if (nals[i].i_payload > (size - (p - buf))) {
00092             // return only complete nals which fit in buf
00093             av_log(ctx, AV_LOG_ERROR, "Error: nal buffer is too small\n");
00094             break;
00095         }
00096         memcpy(p, nals[i].p_payload, nals[i].i_payload);
00097         p += nals[i].i_payload;
00098     }
00099 
00100     return p - buf;
00101 }
00102 
00103 static int X264_frame(AVCodecContext *ctx, uint8_t *buf,
00104                       int orig_bufsize, void *data)
00105 {
00106     X264Context *x4 = ctx->priv_data;
00107     AVFrame *frame = data;
00108     x264_nal_t *nal;
00109     int nnal, i;
00110     x264_picture_t pic_out;
00111     int bufsize;
00112 
00113     x264_picture_init( &x4->pic );
00114     x4->pic.img.i_csp   = X264_CSP_I420;
00115     x4->pic.img.i_plane = 3;
00116 
00117     if (frame) {
00118         for (i = 0; i < 3; i++) {
00119             x4->pic.img.plane[i]    = frame->data[i];
00120             x4->pic.img.i_stride[i] = frame->linesize[i];
00121         }
00122 
00123         x4->pic.i_pts  = frame->pts;
00124         x4->pic.i_type =
00125             frame->pict_type == AV_PICTURE_TYPE_I ? X264_TYPE_KEYFRAME :
00126             frame->pict_type == AV_PICTURE_TYPE_P ? X264_TYPE_P :
00127             frame->pict_type == AV_PICTURE_TYPE_B ? X264_TYPE_B :
00128                                             X264_TYPE_AUTO;
00129         if (x4->params.b_tff != frame->top_field_first) {
00130             x4->params.b_tff = frame->top_field_first;
00131             x264_encoder_reconfig(x4->enc, &x4->params);
00132         }
00133         if (x4->params.vui.i_sar_height != ctx->sample_aspect_ratio.den
00134          || x4->params.vui.i_sar_width != ctx->sample_aspect_ratio.num) {
00135             x4->params.vui.i_sar_height = ctx->sample_aspect_ratio.den;
00136             x4->params.vui.i_sar_width = ctx->sample_aspect_ratio.num;
00137             x264_encoder_reconfig(x4->enc, &x4->params);
00138         }
00139     }
00140 
00141     do {
00142         bufsize = orig_bufsize;
00143     if (x264_encoder_encode(x4->enc, &nal, &nnal, frame? &x4->pic: NULL, &pic_out) < 0)
00144         return -1;
00145 
00146     bufsize = encode_nals(ctx, buf, bufsize, nal, nnal, 0);
00147     if (bufsize < 0)
00148         return -1;
00149     } while (!bufsize && !frame && x264_encoder_delayed_frames(x4->enc));
00150 
00151     /* FIXME: libx264 now provides DTS, but AVFrame doesn't have a field for it. */
00152     x4->out_pic.pts = pic_out.i_pts;
00153 
00154     switch (pic_out.i_type) {
00155     case X264_TYPE_IDR:
00156     case X264_TYPE_I:
00157         x4->out_pic.pict_type = AV_PICTURE_TYPE_I;
00158         break;
00159     case X264_TYPE_P:
00160         x4->out_pic.pict_type = AV_PICTURE_TYPE_P;
00161         break;
00162     case X264_TYPE_B:
00163     case X264_TYPE_BREF:
00164         x4->out_pic.pict_type = AV_PICTURE_TYPE_B;
00165         break;
00166     }
00167 
00168     x4->out_pic.key_frame = pic_out.b_keyframe;
00169     if (bufsize)
00170         x4->out_pic.quality = (pic_out.i_qpplus1 - 1) * FF_QP2LAMBDA;
00171 
00172     return bufsize;
00173 }
00174 
00175 static av_cold int X264_close(AVCodecContext *avctx)
00176 {
00177     X264Context *x4 = avctx->priv_data;
00178 
00179     av_freep(&avctx->extradata);
00180     av_free(x4->sei);
00181 
00182     if (x4->enc)
00183         x264_encoder_close(x4->enc);
00184 
00185     return 0;
00186 }
00187 
00191 static void check_default_settings(AVCodecContext *avctx)
00192 {
00193     X264Context *x4 = avctx->priv_data;
00194 
00195     int score = 0;
00196     score += x4->params.analyse.i_me_range == 0;
00197     score += x4->params.rc.i_qp_step == 3;
00198     score += x4->params.i_keyint_max == 12;
00199     score += x4->params.rc.i_qp_min == 2;
00200     score += x4->params.rc.i_qp_max == 31;
00201     score += x4->params.rc.f_qcompress == 0.5;
00202     score += fabs(x4->params.rc.f_ip_factor - 1.25) < 0.01;
00203     score += fabs(x4->params.rc.f_pb_factor - 1.25) < 0.01;
00204     score += x4->params.analyse.inter == 0 && x4->params.analyse.i_subpel_refine == 8;
00205     if (score >= 5) {
00206         av_log(avctx, AV_LOG_ERROR, "Default settings detected, using medium profile\n");
00207         x4->preset = av_strdup("medium");
00208         if (avctx->bit_rate == 200*1000)
00209             avctx->crf = 23;
00210     }
00211 }
00212 
00213 #define OPT_STR(opt, param)                                             \
00214     do {                                                                \
00215         if (param && x264_param_parse(&x4->params, opt, param) < 0) {   \
00216             av_log(avctx, AV_LOG_ERROR,                                 \
00217                    "bad value for '%s': '%s'\n", opt, param);           \
00218             return -1;                                                  \
00219         }                                                               \
00220     } while (0);                                                        \
00221 
00222 static av_cold int X264_init(AVCodecContext *avctx)
00223 {
00224     X264Context *x4 = avctx->priv_data;
00225 
00226     x4->sei_size = 0;
00227     x264_param_default(&x4->params);
00228 
00229     x4->params.i_keyint_max         = avctx->gop_size;
00230 
00231     x4->params.i_bframe          = avctx->max_b_frames;
00232     x4->params.b_cabac           = avctx->coder_type == FF_CODER_TYPE_AC;
00233     x4->params.i_bframe_adaptive = avctx->b_frame_strategy;
00234     x4->params.i_bframe_bias     = avctx->bframebias;
00235     x4->params.i_bframe_pyramid  = avctx->flags2 & CODEC_FLAG2_BPYRAMID ? X264_B_PYRAMID_NORMAL : X264_B_PYRAMID_NONE;
00236 
00237     x4->params.i_keyint_min = avctx->keyint_min;
00238     if (x4->params.i_keyint_min > x4->params.i_keyint_max)
00239         x4->params.i_keyint_min = x4->params.i_keyint_max;
00240 
00241     x4->params.i_scenecut_threshold        = avctx->scenechange_threshold;
00242 
00243     x4->params.b_deblocking_filter         = avctx->flags & CODEC_FLAG_LOOP_FILTER;
00244     x4->params.i_deblocking_filter_alphac0 = avctx->deblockalpha;
00245     x4->params.i_deblocking_filter_beta    = avctx->deblockbeta;
00246 
00247     x4->params.rc.i_qp_min                 = avctx->qmin;
00248     x4->params.rc.i_qp_max                 = avctx->qmax;
00249     x4->params.rc.i_qp_step                = avctx->max_qdiff;
00250 
00251     x4->params.rc.f_qcompress       = avctx->qcompress; /* 0.0 => cbr, 1.0 => constant qp */
00252     x4->params.rc.f_qblur           = avctx->qblur;     /* temporally blur quants */
00253     x4->params.rc.f_complexity_blur = avctx->complexityblur;
00254 
00255     x4->params.i_frame_reference    = avctx->refs;
00256 
00257     x4->params.analyse.inter    = 0;
00258     if (avctx->partitions) {
00259         if (avctx->partitions & X264_PART_I4X4)
00260             x4->params.analyse.inter |= X264_ANALYSE_I4x4;
00261         if (avctx->partitions & X264_PART_I8X8)
00262             x4->params.analyse.inter |= X264_ANALYSE_I8x8;
00263         if (avctx->partitions & X264_PART_P8X8)
00264             x4->params.analyse.inter |= X264_ANALYSE_PSUB16x16;
00265         if (avctx->partitions & X264_PART_P4X4)
00266             x4->params.analyse.inter |= X264_ANALYSE_PSUB8x8;
00267         if (avctx->partitions & X264_PART_B8X8)
00268             x4->params.analyse.inter |= X264_ANALYSE_BSUB16x16;
00269     }
00270 
00271     x4->params.analyse.i_direct_mv_pred  = avctx->directpred;
00272 
00273     x4->params.analyse.b_weighted_bipred = avctx->flags2 & CODEC_FLAG2_WPRED;
00274 
00275     if (avctx->me_method == ME_EPZS)
00276         x4->params.analyse.i_me_method = X264_ME_DIA;
00277     else if (avctx->me_method == ME_HEX)
00278         x4->params.analyse.i_me_method = X264_ME_HEX;
00279     else if (avctx->me_method == ME_UMH)
00280         x4->params.analyse.i_me_method = X264_ME_UMH;
00281     else if (avctx->me_method == ME_FULL)
00282         x4->params.analyse.i_me_method = X264_ME_ESA;
00283     else if (avctx->me_method == ME_TESA)
00284         x4->params.analyse.i_me_method = X264_ME_TESA;
00285     else x4->params.analyse.i_me_method = X264_ME_HEX;
00286 
00287     x4->params.rc.i_aq_mode               = avctx->aq_mode;
00288     x4->params.rc.f_aq_strength           = avctx->aq_strength;
00289     x4->params.rc.i_lookahead             = avctx->rc_lookahead;
00290 
00291     x4->params.analyse.b_psy              = avctx->flags2 & CODEC_FLAG2_PSY;
00292     x4->params.analyse.f_psy_rd           = avctx->psy_rd;
00293     x4->params.analyse.f_psy_trellis      = avctx->psy_trellis;
00294 
00295     x4->params.analyse.i_me_range         = avctx->me_range;
00296     x4->params.analyse.i_subpel_refine    = avctx->me_subpel_quality;
00297 
00298     x4->params.analyse.b_mixed_references = avctx->flags2 & CODEC_FLAG2_MIXED_REFS;
00299     x4->params.analyse.b_chroma_me        = avctx->me_cmp & FF_CMP_CHROMA;
00300     x4->params.analyse.b_transform_8x8    = avctx->flags2 & CODEC_FLAG2_8X8DCT;
00301     x4->params.analyse.b_fast_pskip       = avctx->flags2 & CODEC_FLAG2_FASTPSKIP;
00302 
00303     x4->params.analyse.i_trellis          = avctx->trellis;
00304     x4->params.analyse.i_noise_reduction  = avctx->noise_reduction;
00305 
00306     x4->params.rc.b_mb_tree               = !!(avctx->flags2 & CODEC_FLAG2_MBTREE);
00307     x4->params.rc.f_ip_factor             = 1 / fabs(avctx->i_quant_factor);
00308     x4->params.rc.f_pb_factor             = avctx->b_quant_factor;
00309     x4->params.analyse.i_chroma_qp_offset = avctx->chromaoffset;
00310 
00311     if (!x4->preset)
00312         check_default_settings(avctx);
00313 
00314     if (x4->preset || x4->tune) {
00315         if (x264_param_default_preset(&x4->params, x4->preset, x4->tune) < 0)
00316             return -1;
00317     }
00318 
00319     x4->params.pf_log               = X264_log;
00320     x4->params.p_log_private        = avctx;
00321     x4->params.i_log_level          = X264_LOG_DEBUG;
00322 
00323     OPT_STR("weightp", x4->weightp);
00324 
00325     x4->params.b_intra_refresh      = avctx->flags2 & CODEC_FLAG2_INTRA_REFRESH;
00326     x4->params.rc.i_bitrate         = avctx->bit_rate       / 1000;
00327     x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;
00328     x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate    / 1000;
00329     x4->params.rc.b_stat_write      = avctx->flags & CODEC_FLAG_PASS1;
00330     if (avctx->flags & CODEC_FLAG_PASS2) {
00331         x4->params.rc.b_stat_read = 1;
00332     } else {
00333         if (avctx->crf) {
00334             x4->params.rc.i_rc_method   = X264_RC_CRF;
00335             x4->params.rc.f_rf_constant = avctx->crf;
00336             x4->params.rc.f_rf_constant_max = avctx->crf_max;
00337         } else if (avctx->cqp > -1) {
00338             x4->params.rc.i_rc_method   = X264_RC_CQP;
00339             x4->params.rc.i_qp_constant = avctx->cqp;
00340         }
00341     }
00342 
00343     OPT_STR("stats", x4->stats);
00344 
00345     // if neither crf nor cqp modes are selected we have to enable the RC
00346     // we do it this way because we cannot check if the bitrate has been set
00347     if (!(avctx->crf || (avctx->cqp > -1)))
00348         x4->params.rc.i_rc_method = X264_RC_ABR;
00349 
00350     if (avctx->rc_buffer_size && avctx->rc_initial_buffer_occupancy &&
00351         (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {
00352         x4->params.rc.f_vbv_buffer_init =
00353             (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;
00354     }
00355 
00356     OPT_STR("level", x4->level);
00357 
00358     if(x4->x264opts){
00359         const char *p= x4->x264opts;
00360         while(p){
00361             char param[256]={0}, val[256]={0};
00362             sscanf(p, "%255[^:=]=%255[^:]", param, val);
00363             OPT_STR(param, val);
00364             p= strchr(p, ':');
00365             p+=!!p;
00366         }
00367     }
00368 
00369     if (x4->fastfirstpass)
00370         x264_param_apply_fastfirstpass(&x4->params);
00371 
00372     if (x4->profile)
00373         if (x264_param_apply_profile(&x4->params, x4->profile) < 0)
00374             return -1;
00375 
00376     x4->params.i_width          = avctx->width;
00377     x4->params.i_height         = avctx->height;
00378     x4->params.vui.i_sar_width  = avctx->sample_aspect_ratio.num;
00379     x4->params.vui.i_sar_height = avctx->sample_aspect_ratio.den;
00380     x4->params.i_fps_num = x4->params.i_timebase_den = avctx->time_base.den;
00381     x4->params.i_fps_den = x4->params.i_timebase_num = avctx->time_base.num;
00382 
00383     x4->params.analyse.b_psnr = avctx->flags & CODEC_FLAG_PSNR;
00384     x4->params.analyse.b_ssim = avctx->flags2 & CODEC_FLAG2_SSIM;
00385 
00386     x4->params.b_aud          = avctx->flags2 & CODEC_FLAG2_AUD;
00387 
00388     x4->params.i_threads      = avctx->thread_count;
00389 
00390     x4->params.b_interlaced   = avctx->flags & CODEC_FLAG_INTERLACED_DCT;
00391 
00392 //    x4->params.b_open_gop     = !(avctx->flags & CODEC_FLAG_CLOSED_GOP);
00393 
00394     x4->params.i_slice_count  = avctx->slices;
00395 
00396     x4->params.vui.b_fullrange = avctx->pix_fmt == PIX_FMT_YUVJ420P;
00397 
00398     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER)
00399         x4->params.b_repeat_headers = 0;
00400 
00401     // update AVCodecContext with x264 parameters
00402     avctx->has_b_frames = x4->params.i_bframe ?
00403         x4->params.i_bframe_pyramid ? 2 : 1 : 0;
00404     avctx->bit_rate = x4->params.rc.i_bitrate*1000;
00405     avctx->crf = x4->params.rc.f_rf_constant;
00406 
00407     x4->enc = x264_encoder_open(&x4->params);
00408     if (!x4->enc)
00409         return -1;
00410 
00411     avctx->coded_frame = &x4->out_pic;
00412 
00413     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
00414         x264_nal_t *nal;
00415         int nnal, s, i;
00416 
00417         s = x264_encoder_headers(x4->enc, &nal, &nnal);
00418 
00419         for (i = 0; i < nnal; i++)
00420             if (nal[i].i_type == NAL_SEI)
00421                 av_log(avctx, AV_LOG_INFO, "%s\n", nal[i].p_payload+25);
00422 
00423         avctx->extradata      = av_malloc(s);
00424         avctx->extradata_size = encode_nals(avctx, avctx->extradata, s, nal, nnal, 1);
00425     }
00426 
00427     return 0;
00428 }
00429 
00430 #define OFFSET(x) offsetof(X264Context,x)
00431 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
00432 
00433 static const AVOption options[] = {
00434     {"preset", "Set the encoding preset", OFFSET(preset), FF_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
00435     {"tune", "Tune the encoding params", OFFSET(tune), FF_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
00436     {"fastfirstpass", "Use fast settings when encoding first pass", OFFSET(fastfirstpass), FF_OPT_TYPE_INT, {.dbl=1}, 0, 1, VE},
00437     {"profile", "Set profile restrictions", OFFSET(profile), FF_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
00438     {"level", "Specify level (as defined by Annex A)", OFFSET(level), FF_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
00439     {"passlogfile", "Filename for 2 pass stats", OFFSET(stats), FF_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
00440     {"wpredp", "Weighted prediction for P-frames", OFFSET(weightp), FF_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
00441     {"x264opts", "x264 options", OFFSET(x264opts), FF_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
00442     { NULL },
00443 };
00444 
00445 static const AVClass class = { "libx264", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
00446 
00447 AVCodec ff_libx264_encoder = {
00448     .name           = "libx264",
00449     .type           = AVMEDIA_TYPE_VIDEO,
00450     .id             = CODEC_ID_H264,
00451     .priv_data_size = sizeof(X264Context),
00452     .init           = X264_init,
00453     .encode         = X264_frame,
00454     .close          = X264_close,
00455     .capabilities   = CODEC_CAP_DELAY,
00456     .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_YUV420P, PIX_FMT_YUVJ420P, PIX_FMT_NONE },
00457     .long_name      = NULL_IF_CONFIG_SMALL("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
00458     .priv_class     = &class,
00459 };

Generated on Fri Feb 22 2013 07:24:27 for FFmpeg by  doxygen 1.7.1