Libav 0.7.1
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 Libav.
00006  *
00007  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include "avcodec.h"
00023 #include <x264.h>
00024 #include <math.h>
00025 #include <stdio.h>
00026 #include <stdlib.h>
00027 #include <string.h>
00028 
00029 typedef struct X264Context {
00030     x264_param_t    params;
00031     x264_t         *enc;
00032     x264_picture_t  pic;
00033     uint8_t        *sei;
00034     int             sei_size;
00035     AVFrame         out_pic;
00036 } X264Context;
00037 
00038 static void X264_log(void *p, int level, const char *fmt, va_list args)
00039 {
00040     static const int level_map[] = {
00041         [X264_LOG_ERROR]   = AV_LOG_ERROR,
00042         [X264_LOG_WARNING] = AV_LOG_WARNING,
00043         [X264_LOG_INFO]    = AV_LOG_INFO,
00044         [X264_LOG_DEBUG]   = AV_LOG_DEBUG
00045     };
00046 
00047     if (level < 0 || level > X264_LOG_DEBUG)
00048         return;
00049 
00050     av_vlog(p, level_map[level], fmt, args);
00051 }
00052 
00053 
00054 static int encode_nals(AVCodecContext *ctx, uint8_t *buf, int size,
00055                        x264_nal_t *nals, int nnal, int skip_sei)
00056 {
00057     X264Context *x4 = ctx->priv_data;
00058     uint8_t *p = buf;
00059     int i;
00060 
00061     /* Write the SEI as part of the first frame. */
00062     if (x4->sei_size > 0 && nnal > 0) {
00063         memcpy(p, x4->sei, x4->sei_size);
00064         p += x4->sei_size;
00065         x4->sei_size = 0;
00066     }
00067 
00068     for (i = 0; i < nnal; i++){
00069         /* Don't put the SEI in extradata. */
00070         if (skip_sei && nals[i].i_type == NAL_SEI) {
00071             x4->sei_size = nals[i].i_payload;
00072             x4->sei      = av_malloc(x4->sei_size);
00073             memcpy(x4->sei, nals[i].p_payload, nals[i].i_payload);
00074             continue;
00075         }
00076         memcpy(p, nals[i].p_payload, nals[i].i_payload);
00077         p += nals[i].i_payload;
00078     }
00079 
00080     return p - buf;
00081 }
00082 
00083 static int X264_frame(AVCodecContext *ctx, uint8_t *buf,
00084                       int bufsize, void *data)
00085 {
00086     X264Context *x4 = ctx->priv_data;
00087     AVFrame *frame = data;
00088     x264_nal_t *nal;
00089     int nnal, i;
00090     x264_picture_t pic_out;
00091 
00092     x264_picture_init( &x4->pic );
00093     x4->pic.img.i_csp   = X264_CSP_I420;
00094     x4->pic.img.i_plane = 3;
00095 
00096     if (frame) {
00097         for (i = 0; i < 3; i++) {
00098             x4->pic.img.plane[i]    = frame->data[i];
00099             x4->pic.img.i_stride[i] = frame->linesize[i];
00100         }
00101 
00102         x4->pic.i_pts  = frame->pts;
00103         x4->pic.i_type =
00104             frame->pict_type == AV_PICTURE_TYPE_I ? X264_TYPE_KEYFRAME :
00105             frame->pict_type == AV_PICTURE_TYPE_P ? X264_TYPE_P :
00106             frame->pict_type == AV_PICTURE_TYPE_B ? X264_TYPE_B :
00107                                             X264_TYPE_AUTO;
00108         if (x4->params.b_tff != frame->top_field_first) {
00109             x4->params.b_tff = frame->top_field_first;
00110             x264_encoder_reconfig(x4->enc, &x4->params);
00111         }
00112     }
00113 
00114     do {
00115     if (x264_encoder_encode(x4->enc, &nal, &nnal, frame? &x4->pic: NULL, &pic_out) < 0)
00116         return -1;
00117 
00118     bufsize = encode_nals(ctx, buf, bufsize, nal, nnal, 0);
00119     if (bufsize < 0)
00120         return -1;
00121     } while (!bufsize && !frame && x264_encoder_delayed_frames(x4->enc));
00122 
00123     /* FIXME: libx264 now provides DTS, but AVFrame doesn't have a field for it. */
00124     x4->out_pic.pts = pic_out.i_pts;
00125 
00126     switch (pic_out.i_type) {
00127     case X264_TYPE_IDR:
00128     case X264_TYPE_I:
00129         x4->out_pic.pict_type = AV_PICTURE_TYPE_I;
00130         break;
00131     case X264_TYPE_P:
00132         x4->out_pic.pict_type = AV_PICTURE_TYPE_P;
00133         break;
00134     case X264_TYPE_B:
00135     case X264_TYPE_BREF:
00136         x4->out_pic.pict_type = AV_PICTURE_TYPE_B;
00137         break;
00138     }
00139 
00140     x4->out_pic.key_frame = pic_out.b_keyframe;
00141     if (bufsize)
00142         x4->out_pic.quality = (pic_out.i_qpplus1 - 1) * FF_QP2LAMBDA;
00143 
00144     return bufsize;
00145 }
00146 
00147 static av_cold int X264_close(AVCodecContext *avctx)
00148 {
00149     X264Context *x4 = avctx->priv_data;
00150 
00151     av_freep(&avctx->extradata);
00152     av_free(x4->sei);
00153 
00154     if (x4->enc)
00155         x264_encoder_close(x4->enc);
00156 
00157     return 0;
00158 }
00159 
00160 static av_cold int X264_init(AVCodecContext *avctx)
00161 {
00162     X264Context *x4 = avctx->priv_data;
00163 
00164     x4->sei_size = 0;
00165     x264_param_default(&x4->params);
00166 
00167     x4->params.pf_log               = X264_log;
00168     x4->params.p_log_private        = avctx;
00169 
00170     x4->params.i_keyint_max         = avctx->gop_size;
00171     x4->params.b_intra_refresh      = avctx->flags2 & CODEC_FLAG2_INTRA_REFRESH;
00172     x4->params.rc.i_bitrate         = avctx->bit_rate       / 1000;
00173     x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;
00174     x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate    / 1000;
00175     x4->params.rc.b_stat_write      = avctx->flags & CODEC_FLAG_PASS1;
00176     if (avctx->flags & CODEC_FLAG_PASS2) {
00177         x4->params.rc.b_stat_read = 1;
00178     } else {
00179         if (avctx->crf) {
00180             x4->params.rc.i_rc_method   = X264_RC_CRF;
00181             x4->params.rc.f_rf_constant = avctx->crf;
00182             x4->params.rc.f_rf_constant_max = avctx->crf_max;
00183         } else if (avctx->cqp > -1) {
00184             x4->params.rc.i_rc_method   = X264_RC_CQP;
00185             x4->params.rc.i_qp_constant = avctx->cqp;
00186         }
00187     }
00188 
00189     // if neither crf nor cqp modes are selected we have to enable the RC
00190     // we do it this way because we cannot check if the bitrate has been set
00191     if (!(avctx->crf || (avctx->cqp > -1)))
00192         x4->params.rc.i_rc_method = X264_RC_ABR;
00193 
00194     x4->params.i_bframe          = avctx->max_b_frames;
00195     x4->params.b_cabac           = avctx->coder_type == FF_CODER_TYPE_AC;
00196     x4->params.i_bframe_adaptive = avctx->b_frame_strategy;
00197     x4->params.i_bframe_bias     = avctx->bframebias;
00198     x4->params.i_bframe_pyramid  = avctx->flags2 & CODEC_FLAG2_BPYRAMID ? X264_B_PYRAMID_NORMAL : X264_B_PYRAMID_NONE;
00199     avctx->has_b_frames          = avctx->flags2 & CODEC_FLAG2_BPYRAMID ? 2 : !!avctx->max_b_frames;
00200 
00201     x4->params.i_keyint_min = avctx->keyint_min;
00202     if (x4->params.i_keyint_min > x4->params.i_keyint_max)
00203         x4->params.i_keyint_min = x4->params.i_keyint_max;
00204 
00205     x4->params.i_scenecut_threshold        = avctx->scenechange_threshold;
00206 
00207     x4->params.b_deblocking_filter         = avctx->flags & CODEC_FLAG_LOOP_FILTER;
00208     x4->params.i_deblocking_filter_alphac0 = avctx->deblockalpha;
00209     x4->params.i_deblocking_filter_beta    = avctx->deblockbeta;
00210 
00211     x4->params.rc.i_qp_min                 = avctx->qmin;
00212     x4->params.rc.i_qp_max                 = avctx->qmax;
00213     x4->params.rc.i_qp_step                = avctx->max_qdiff;
00214 
00215     x4->params.rc.f_qcompress       = avctx->qcompress; /* 0.0 => cbr, 1.0 => constant qp */
00216     x4->params.rc.f_qblur           = avctx->qblur;     /* temporally blur quants */
00217     x4->params.rc.f_complexity_blur = avctx->complexityblur;
00218 
00219     x4->params.i_frame_reference    = avctx->refs;
00220 
00221     x4->params.i_width              = avctx->width;
00222     x4->params.i_height             = avctx->height;
00223     x4->params.vui.i_sar_width      = avctx->sample_aspect_ratio.num;
00224     x4->params.vui.i_sar_height     = avctx->sample_aspect_ratio.den;
00225     x4->params.i_fps_num = x4->params.i_timebase_den = avctx->time_base.den;
00226     x4->params.i_fps_den = x4->params.i_timebase_num = avctx->time_base.num;
00227 
00228     x4->params.analyse.inter    = 0;
00229     if (avctx->partitions) {
00230         if (avctx->partitions & X264_PART_I4X4)
00231             x4->params.analyse.inter |= X264_ANALYSE_I4x4;
00232         if (avctx->partitions & X264_PART_I8X8)
00233             x4->params.analyse.inter |= X264_ANALYSE_I8x8;
00234         if (avctx->partitions & X264_PART_P8X8)
00235             x4->params.analyse.inter |= X264_ANALYSE_PSUB16x16;
00236         if (avctx->partitions & X264_PART_P4X4)
00237             x4->params.analyse.inter |= X264_ANALYSE_PSUB8x8;
00238         if (avctx->partitions & X264_PART_B8X8)
00239             x4->params.analyse.inter |= X264_ANALYSE_BSUB16x16;
00240     }
00241 
00242     x4->params.analyse.i_direct_mv_pred  = avctx->directpred;
00243 
00244     x4->params.analyse.b_weighted_bipred = avctx->flags2 & CODEC_FLAG2_WPRED;
00245     x4->params.analyse.i_weighted_pred = avctx->weighted_p_pred;
00246 
00247     if (avctx->me_method == ME_EPZS)
00248         x4->params.analyse.i_me_method = X264_ME_DIA;
00249     else if (avctx->me_method == ME_HEX)
00250         x4->params.analyse.i_me_method = X264_ME_HEX;
00251     else if (avctx->me_method == ME_UMH)
00252         x4->params.analyse.i_me_method = X264_ME_UMH;
00253     else if (avctx->me_method == ME_FULL)
00254         x4->params.analyse.i_me_method = X264_ME_ESA;
00255     else if (avctx->me_method == ME_TESA)
00256         x4->params.analyse.i_me_method = X264_ME_TESA;
00257     else x4->params.analyse.i_me_method = X264_ME_HEX;
00258 
00259     x4->params.rc.i_aq_mode               = avctx->aq_mode;
00260     x4->params.rc.f_aq_strength           = avctx->aq_strength;
00261     x4->params.rc.i_lookahead             = avctx->rc_lookahead;
00262 
00263     x4->params.analyse.b_psy              = avctx->flags2 & CODEC_FLAG2_PSY;
00264     x4->params.analyse.f_psy_rd           = avctx->psy_rd;
00265     x4->params.analyse.f_psy_trellis      = avctx->psy_trellis;
00266 
00267     x4->params.analyse.i_me_range         = avctx->me_range;
00268     x4->params.analyse.i_subpel_refine    = avctx->me_subpel_quality;
00269 
00270     x4->params.analyse.b_mixed_references = avctx->flags2 & CODEC_FLAG2_MIXED_REFS;
00271     x4->params.analyse.b_chroma_me        = avctx->me_cmp & FF_CMP_CHROMA;
00272     x4->params.analyse.b_transform_8x8    = avctx->flags2 & CODEC_FLAG2_8X8DCT;
00273     x4->params.analyse.b_fast_pskip       = avctx->flags2 & CODEC_FLAG2_FASTPSKIP;
00274 
00275     x4->params.analyse.i_trellis          = avctx->trellis;
00276     x4->params.analyse.i_noise_reduction  = avctx->noise_reduction;
00277 
00278     if (avctx->level > 0)
00279         x4->params.i_level_idc = avctx->level;
00280 
00281     if (avctx->rc_buffer_size && avctx->rc_initial_buffer_occupancy &&
00282         (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {
00283         x4->params.rc.f_vbv_buffer_init =
00284             (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;
00285     }
00286 
00287     x4->params.rc.b_mb_tree               = !!(avctx->flags2 & CODEC_FLAG2_MBTREE);
00288     x4->params.rc.f_ip_factor             = 1 / fabs(avctx->i_quant_factor);
00289     x4->params.rc.f_pb_factor             = avctx->b_quant_factor;
00290     x4->params.analyse.i_chroma_qp_offset = avctx->chromaoffset;
00291 
00292     x4->params.analyse.b_psnr = avctx->flags & CODEC_FLAG_PSNR;
00293     x4->params.analyse.b_ssim = avctx->flags2 & CODEC_FLAG2_SSIM;
00294     x4->params.i_log_level    = X264_LOG_DEBUG;
00295 
00296     x4->params.b_aud          = avctx->flags2 & CODEC_FLAG2_AUD;
00297 
00298     x4->params.i_threads      = avctx->thread_count;
00299 
00300     x4->params.b_interlaced   = avctx->flags & CODEC_FLAG_INTERLACED_DCT;
00301 
00302     x4->params.b_open_gop     = !(avctx->flags & CODEC_FLAG_CLOSED_GOP);
00303 
00304     x4->params.i_slice_count  = avctx->slices;
00305 
00306     x4->params.vui.b_fullrange = avctx->pix_fmt == PIX_FMT_YUVJ420P;
00307 
00308     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER)
00309         x4->params.b_repeat_headers = 0;
00310 
00311     x4->enc = x264_encoder_open(&x4->params);
00312     if (!x4->enc)
00313         return -1;
00314 
00315     avctx->coded_frame = &x4->out_pic;
00316 
00317     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
00318         x264_nal_t *nal;
00319         int nnal, s, i;
00320 
00321         s = x264_encoder_headers(x4->enc, &nal, &nnal);
00322 
00323         for (i = 0; i < nnal; i++)
00324             if (nal[i].i_type == NAL_SEI)
00325                 av_log(avctx, AV_LOG_INFO, "%s\n", nal[i].p_payload+25);
00326 
00327         avctx->extradata      = av_malloc(s);
00328         avctx->extradata_size = encode_nals(avctx, avctx->extradata, s, nal, nnal, 1);
00329     }
00330 
00331     return 0;
00332 }
00333 
00334 AVCodec ff_libx264_encoder = {
00335     .name           = "libx264",
00336     .type           = AVMEDIA_TYPE_VIDEO,
00337     .id             = CODEC_ID_H264,
00338     .priv_data_size = sizeof(X264Context),
00339     .init           = X264_init,
00340     .encode         = X264_frame,
00341     .close          = X264_close,
00342     .capabilities   = CODEC_CAP_DELAY,
00343     .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_YUV420P, PIX_FMT_YUVJ420P, PIX_FMT_NONE },
00344     .long_name      = NULL_IF_CONFIG_SMALL("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
00345 };