libx264.c 11.7 KB
Newer Older
1 2
/*
 * H.264 encoding using the x264 library
3
 * Copyright (C) 2005  Mans Rullgard <mans@mansr.com>
4
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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
20 21 22 23
 */

#include "avcodec.h"
#include <x264.h>
Michael Niedermayer's avatar
Michael Niedermayer committed
24
#include <math.h>
Robert Swain's avatar
Robert Swain committed
25 26 27
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
28 29

typedef struct X264Context {
30 31 32 33 34 35
    x264_param_t    params;
    x264_t         *enc;
    x264_picture_t  pic;
    uint8_t        *sei;
    int             sei_size;
    AVFrame         out_pic;
36 37
} X264Context;

38
static void X264_log(void *p, int level, const char *fmt, va_list args)
39 40
{
    static const int level_map[] = {
41
        [X264_LOG_ERROR]   = AV_LOG_ERROR,
42
        [X264_LOG_WARNING] = AV_LOG_WARNING,
43 44
        [X264_LOG_INFO]    = AV_LOG_INFO,
        [X264_LOG_DEBUG]   = AV_LOG_DEBUG
45 46
    };

47
    if (level < 0 || level > X264_LOG_DEBUG)
48
        return;
49 50 51 52 53

    av_vlog(p, level_map[level], fmt, args);
}


54 55
static int encode_nals(AVCodecContext *ctx, uint8_t *buf, int size,
                       x264_nal_t *nals, int nnal, int skip_sei)
56
{
57
    X264Context *x4 = ctx->priv_data;
Måns Rullgård's avatar
Måns Rullgård committed
58
    uint8_t *p = buf;
59
    int i;
60 61

    /* Write the SEI as part of the first frame. */
62
    if (x4->sei_size > 0 && nnal > 0) {
63 64 65 66
        memcpy(p, x4->sei, x4->sei_size);
        p += x4->sei_size;
        x4->sei_size = 0;
    }
67

68
    for (i = 0; i < nnal; i++){
69
        /* Don't put the SEI in extradata. */
70
        if (skip_sei && nals[i].i_type == NAL_SEI) {
71
            x4->sei_size = nals[i].i_payload;
72
            x4->sei      = av_malloc(x4->sei_size);
73
            memcpy(x4->sei, nals[i].p_payload, nals[i].i_payload);
74 75
            continue;
        }
76 77
        memcpy(p, nals[i].p_payload, nals[i].i_payload);
        p += nals[i].i_payload;
78 79 80 81 82
    }

    return p - buf;
}

83 84
static int X264_frame(AVCodecContext *ctx, uint8_t *buf,
                      int bufsize, void *data)
85 86 87 88 89 90 91
{
    X264Context *x4 = ctx->priv_data;
    AVFrame *frame = data;
    x264_nal_t *nal;
    int nnal, i;
    x264_picture_t pic_out;

92
    x264_picture_init( &x4->pic );
93
    x4->pic.img.i_csp   = X264_CSP_I420;
94 95
    x4->pic.img.i_plane = 3;

96 97 98
    if (frame) {
        for (i = 0; i < 3; i++) {
            x4->pic.img.plane[i]    = frame->data[i];
Måns Rullgård's avatar
Måns Rullgård committed
99 100
            x4->pic.img.i_stride[i] = frame->linesize[i];
        }
101

102
        x4->pic.i_pts  = frame->pts;
Måns Rullgård's avatar
Måns Rullgård committed
103
        x4->pic.i_type = X264_TYPE_AUTO;
104
    }
105

106
    do {
107
    if (x264_encoder_encode(x4->enc, &nal, &nnal, frame? &x4->pic: NULL, &pic_out) < 0)
108
        return -1;
109

110
    bufsize = encode_nals(ctx, buf, bufsize, nal, nnal, 0);
111
    if (bufsize < 0)
112
        return -1;
113
    } while (!bufsize && !frame && x264_encoder_delayed_frames(x4->enc));
114

115
    /* FIXME: libx264 now provides DTS, but AVFrame doesn't have a field for it. */
116 117
    x4->out_pic.pts = pic_out.i_pts;

118
    switch (pic_out.i_type) {
119 120 121 122 123 124 125 126 127 128 129 130 131
    case X264_TYPE_IDR:
    case X264_TYPE_I:
        x4->out_pic.pict_type = FF_I_TYPE;
        break;
    case X264_TYPE_P:
        x4->out_pic.pict_type = FF_P_TYPE;
        break;
    case X264_TYPE_B:
    case X264_TYPE_BREF:
        x4->out_pic.pict_type = FF_B_TYPE;
        break;
    }

132
    x4->out_pic.key_frame = pic_out.b_keyframe;
133
    x4->out_pic.quality   = (pic_out.i_qpplus1 - 1) * FF_QP2LAMBDA;
134 135 136 137

    return bufsize;
}

138
static av_cold int X264_close(AVCodecContext *avctx)
139 140 141
{
    X264Context *x4 = avctx->priv_data;

Ralf Terdic's avatar
Ralf Terdic committed
142
    av_freep(&avctx->extradata);
143
    av_free(x4->sei);
Ralf Terdic's avatar
Ralf Terdic committed
144

145
    if (x4->enc)
146
        x264_encoder_close(x4->enc);
147 148 149 150

    return 0;
}

151
static av_cold int X264_init(AVCodecContext *avctx)
152 153 154
{
    X264Context *x4 = avctx->priv_data;

155
    x4->sei_size = 0;
156 157
    x264_param_default(&x4->params);

158 159
    x4->params.pf_log               = X264_log;
    x4->params.p_log_private        = avctx;
160

161
    x4->params.i_keyint_max         = avctx->gop_size;
162
    x4->params.b_intra_refresh      = avctx->flags2 & CODEC_FLAG2_INTRA_REFRESH;
163
    x4->params.rc.i_bitrate         = avctx->bit_rate       / 1000;
164
    x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;
165
    x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate    / 1000;
166
    x4->params.rc.b_stat_write      = avctx->flags & CODEC_FLAG_PASS1;
167 168 169 170 171
    if (avctx->flags & CODEC_FLAG_PASS2) {
        x4->params.rc.b_stat_read = 1;
    } else {
        if (avctx->crf) {
            x4->params.rc.i_rc_method   = X264_RC_CRF;
172
            x4->params.rc.f_rf_constant = avctx->crf;
173
            x4->params.rc.f_rf_constant_max = avctx->crf_max;
174 175
        } else if (avctx->cqp > -1) {
            x4->params.rc.i_rc_method   = X264_RC_CQP;
Loren Merritt's avatar
Loren Merritt committed
176 177
            x4->params.rc.i_qp_constant = avctx->cqp;
        }
Robert Swain's avatar
Robert Swain committed
178 179 180 181
    }

    // if neither crf nor cqp modes are selected we have to enable the RC
    // we do it this way because we cannot check if the bitrate has been set
182 183
    if (!(avctx->crf || (avctx->cqp > -1)))
        x4->params.rc.i_rc_method = X264_RC_ABR;
Robert Swain's avatar
Robert Swain committed
184

185 186
    x4->params.i_bframe          = avctx->max_b_frames;
    x4->params.b_cabac           = avctx->coder_type == FF_CODER_TYPE_AC;
187
    x4->params.i_bframe_adaptive = avctx->b_frame_strategy;
188
    x4->params.i_bframe_bias     = avctx->bframebias;
189
    x4->params.i_bframe_pyramid  = avctx->flags2 & CODEC_FLAG2_BPYRAMID ? X264_B_PYRAMID_NORMAL : X264_B_PYRAMID_NONE;
190
    avctx->has_b_frames          = avctx->flags2 & CODEC_FLAG2_BPYRAMID ? 2 : !!avctx->max_b_frames;
Robert Swain's avatar
Robert Swain committed
191 192

    x4->params.i_keyint_min = avctx->keyint_min;
193
    if (x4->params.i_keyint_min > x4->params.i_keyint_max)
Robert Swain's avatar
Robert Swain committed
194 195
        x4->params.i_keyint_min = x4->params.i_keyint_max;

196
    x4->params.i_scenecut_threshold        = avctx->scenechange_threshold;
Robert Swain's avatar
Robert Swain committed
197

198
    x4->params.b_deblocking_filter         = avctx->flags & CODEC_FLAG_LOOP_FILTER;
Robert Swain's avatar
Robert Swain committed
199
    x4->params.i_deblocking_filter_alphac0 = avctx->deblockalpha;
200
    x4->params.i_deblocking_filter_beta    = avctx->deblockbeta;
201

202 203 204
    x4->params.rc.i_qp_min                 = avctx->qmin;
    x4->params.rc.i_qp_max                 = avctx->qmax;
    x4->params.rc.i_qp_step                = avctx->max_qdiff;
205

206 207
    x4->params.rc.f_qcompress       = avctx->qcompress; /* 0.0 => cbr, 1.0 => constant qp */
    x4->params.rc.f_qblur           = avctx->qblur;     /* temporally blur quants */
Robert Swain's avatar
Robert Swain committed
208
    x4->params.rc.f_complexity_blur = avctx->complexityblur;
209

210
    x4->params.i_frame_reference    = avctx->refs;
211

212 213 214 215
    x4->params.i_width              = avctx->width;
    x4->params.i_height             = avctx->height;
    x4->params.vui.i_sar_width      = avctx->sample_aspect_ratio.num;
    x4->params.vui.i_sar_height     = avctx->sample_aspect_ratio.den;
216 217
    x4->params.i_fps_num = x4->params.i_timebase_den = avctx->time_base.den;
    x4->params.i_fps_den = x4->params.i_timebase_num = avctx->time_base.num;
218

219 220 221
    x4->params.analyse.inter    = 0;
    if (avctx->partitions) {
        if (avctx->partitions & X264_PART_I4X4)
Robert Swain's avatar
Robert Swain committed
222
            x4->params.analyse.inter |= X264_ANALYSE_I4x4;
223
        if (avctx->partitions & X264_PART_I8X8)
Robert Swain's avatar
Robert Swain committed
224
            x4->params.analyse.inter |= X264_ANALYSE_I8x8;
225
        if (avctx->partitions & X264_PART_P8X8)
Robert Swain's avatar
Robert Swain committed
226
            x4->params.analyse.inter |= X264_ANALYSE_PSUB16x16;
227
        if (avctx->partitions & X264_PART_P4X4)
Robert Swain's avatar
Robert Swain committed
228
            x4->params.analyse.inter |= X264_ANALYSE_PSUB8x8;
229
        if (avctx->partitions & X264_PART_B8X8)
Robert Swain's avatar
Robert Swain committed
230 231 232
            x4->params.analyse.inter |= X264_ANALYSE_BSUB16x16;
    }

233
    x4->params.analyse.i_direct_mv_pred  = avctx->directpred;
Robert Swain's avatar
Robert Swain committed
234

235
    x4->params.analyse.b_weighted_bipred = avctx->flags2 & CODEC_FLAG2_WPRED;
236
    x4->params.analyse.i_weighted_pred = avctx->weighted_p_pred;
Robert Swain's avatar
Robert Swain committed
237

238
    if (avctx->me_method == ME_EPZS)
Robert Swain's avatar
Robert Swain committed
239
        x4->params.analyse.i_me_method = X264_ME_DIA;
240
    else if (avctx->me_method == ME_HEX)
Robert Swain's avatar
Robert Swain committed
241
        x4->params.analyse.i_me_method = X264_ME_HEX;
242
    else if (avctx->me_method == ME_UMH)
Robert Swain's avatar
Robert Swain committed
243
        x4->params.analyse.i_me_method = X264_ME_UMH;
244
    else if (avctx->me_method == ME_FULL)
Robert Swain's avatar
Robert Swain committed
245
        x4->params.analyse.i_me_method = X264_ME_ESA;
246
    else if (avctx->me_method == ME_TESA)
247
        x4->params.analyse.i_me_method = X264_ME_TESA;
Robert Swain's avatar
Robert Swain committed
248 249
    else x4->params.analyse.i_me_method = X264_ME_HEX;

250 251 252
    x4->params.rc.i_aq_mode               = avctx->aq_mode;
    x4->params.rc.f_aq_strength           = avctx->aq_strength;
    x4->params.rc.i_lookahead             = avctx->rc_lookahead;
253

254 255 256
    x4->params.analyse.b_psy              = avctx->flags2 & CODEC_FLAG2_PSY;
    x4->params.analyse.f_psy_rd           = avctx->psy_rd;
    x4->params.analyse.f_psy_trellis      = avctx->psy_trellis;
257

258 259
    x4->params.analyse.i_me_range         = avctx->me_range;
    x4->params.analyse.i_subpel_refine    = avctx->me_subpel_quality;
Robert Swain's avatar
Robert Swain committed
260

261 262 263 264
    x4->params.analyse.b_mixed_references = avctx->flags2 & CODEC_FLAG2_MIXED_REFS;
    x4->params.analyse.b_chroma_me        = avctx->me_cmp & FF_CMP_CHROMA;
    x4->params.analyse.b_transform_8x8    = avctx->flags2 & CODEC_FLAG2_8X8DCT;
    x4->params.analyse.b_fast_pskip       = avctx->flags2 & CODEC_FLAG2_FASTPSKIP;
Robert Swain's avatar
Robert Swain committed
265

266 267
    x4->params.analyse.i_trellis          = avctx->trellis;
    x4->params.analyse.i_noise_reduction  = avctx->noise_reduction;
Robert Swain's avatar
Robert Swain committed
268

269 270
    if (avctx->level > 0)
        x4->params.i_level_idc = avctx->level;
Robert Swain's avatar
Robert Swain committed
271

272
    x4->params.rc.f_rate_tolerance =
Robert Swain's avatar
Robert Swain committed
273 274
        (float)avctx->bit_rate_tolerance/avctx->bit_rate;

275 276
    if ((avctx->rc_buffer_size != 0) &&
        (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {
Robert Swain's avatar
Robert Swain committed
277
        x4->params.rc.f_vbv_buffer_init =
278 279 280
            (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;
    } else
        x4->params.rc.f_vbv_buffer_init = 0.9;
Robert Swain's avatar
Robert Swain committed
281

282
    x4->params.rc.b_mb_tree               = !!(avctx->flags2 & CODEC_FLAG2_MBTREE);
283 284
    x4->params.rc.f_ip_factor             = 1 / fabs(avctx->i_quant_factor);
    x4->params.rc.f_pb_factor             = avctx->b_quant_factor;
Robert Swain's avatar
Robert Swain committed
285 286
    x4->params.analyse.i_chroma_qp_offset = avctx->chromaoffset;

287
    x4->params.analyse.b_psnr = avctx->flags & CODEC_FLAG_PSNR;
288
    x4->params.analyse.b_ssim = avctx->flags2 & CODEC_FLAG2_SSIM;
289
    x4->params.i_log_level    = X264_LOG_DEBUG;
Robert Swain's avatar
Robert Swain committed
290

291
    x4->params.b_aud          = avctx->flags2 & CODEC_FLAG2_AUD;
Robert Swain's avatar
Robert Swain committed
292

293
    x4->params.i_threads      = avctx->thread_count;
294

295
    x4->params.b_interlaced   = avctx->flags & CODEC_FLAG_INTERLACED_DCT;
296

297
    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER)
298 299
        x4->params.b_repeat_headers = 0;

300
    x4->enc = x264_encoder_open(&x4->params);
301
    if (!x4->enc)
302 303 304 305
        return -1;

    avctx->coded_frame = &x4->out_pic;

306
    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
307
        x264_nal_t *nal;
308
        int nnal, s, i;
309

310
        s = x264_encoder_headers(x4->enc, &nal, &nnal);
311

312 313 314 315
        for (i = 0; i < nnal; i++)
            if (nal[i].i_type == NAL_SEI)
                av_log(avctx, AV_LOG_INFO, "%s\n", nal[i].p_payload+25);

316
        avctx->extradata      = av_malloc(s);
317
        avctx->extradata_size = encode_nals(avctx, avctx->extradata, s, nal, nnal, 1);
318 319
    }

320 321 322
    return 0;
}

323
AVCodec libx264_encoder = {
324
    .name           = "libx264",
325
    .type           = AVMEDIA_TYPE_VIDEO,
326
    .id             = CODEC_ID_H264,
327
    .priv_data_size = sizeof(X264Context),
328 329 330 331 332 333
    .init           = X264_init,
    .encode         = X264_frame,
    .close          = X264_close,
    .capabilities   = CODEC_CAP_DELAY,
    .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_YUV420P, PIX_FMT_NONE },
    .long_name      = NULL_IF_CONFIG_SMALL("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
334
};