]> git.sesse.net Git - ffmpeg/blob - libavcodec/libx264.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / libx264.c
1 /*
2  * H.264 encoding using the x264 library
3  * Copyright (C) 2005  Mans Rullgard <mans@mansr.com>
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 #include "libavutil/opt.h"
23 #include "libavutil/pixdesc.h"
24 #include "avcodec.h"
25 #include "internal.h"
26 #include <x264.h>
27 #include <float.h>
28 #include <math.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 typedef struct X264Context {
34     AVClass        *class;
35     x264_param_t    params;
36     x264_t         *enc;
37     x264_picture_t  pic;
38     uint8_t        *sei;
39     int             sei_size;
40     AVFrame         out_pic;
41     char *preset;
42     char *tune;
43     char *profile;
44     char *level;
45     int fastfirstpass;
46     char *stats;
47     char *wpredp;
48     char *x264opts;
49     float crf;
50     float crf_max;
51     int cqp;
52     int aq_mode;
53     float aq_strength;
54     char *psy_rd;
55     int psy;
56     int rc_lookahead;
57     int weightp;
58     int weightb;
59     int ssim;
60     int intra_refresh;
61     int b_bias;
62     int b_pyramid;
63     int mixed_refs;
64     int dct8x8;
65     int fast_pskip;
66     int aud;
67     int mbtree;
68     char *deblock;
69     float cplxblur;
70     char *partitions;
71     int direct_pred;
72     int slice_max_size;
73 } X264Context;
74
75 static void X264_log(void *p, int level, const char *fmt, va_list args)
76 {
77     static const int level_map[] = {
78         [X264_LOG_ERROR]   = AV_LOG_ERROR,
79         [X264_LOG_WARNING] = AV_LOG_WARNING,
80         [X264_LOG_INFO]    = AV_LOG_INFO,
81         [X264_LOG_DEBUG]   = AV_LOG_DEBUG
82     };
83
84     if (level < 0 || level > X264_LOG_DEBUG)
85         return;
86
87     av_vlog(p, level_map[level], fmt, args);
88 }
89
90
91 static int encode_nals(AVCodecContext *ctx, uint8_t *buf, int size,
92                        x264_nal_t *nals, int nnal, int skip_sei)
93 {
94     X264Context *x4 = ctx->priv_data;
95     uint8_t *p = buf;
96     int i;
97
98     /* Write the SEI as part of the first frame. */
99     if (x4->sei_size > 0 && nnal > 0) {
100         if (x4->sei_size > size) {
101             av_log(ctx, AV_LOG_ERROR, "Error: nal buffer is too small\n");
102             return -1;
103         }
104         memcpy(p, x4->sei, x4->sei_size);
105         p += x4->sei_size;
106         x4->sei_size = 0;
107         av_freep(&x4->sei);
108     }
109
110     for (i = 0; i < nnal; i++){
111         /* Don't put the SEI in extradata. */
112         if (skip_sei && nals[i].i_type == NAL_SEI) {
113             x4->sei_size = nals[i].i_payload;
114             x4->sei      = av_malloc(x4->sei_size);
115             memcpy(x4->sei, nals[i].p_payload, nals[i].i_payload);
116             continue;
117         }
118         if (nals[i].i_payload > (size - (p - buf))) {
119             // return only complete nals which fit in buf
120             av_log(ctx, AV_LOG_ERROR, "Error: nal buffer is too small\n");
121             break;
122         }
123         memcpy(p, nals[i].p_payload, nals[i].i_payload);
124         p += nals[i].i_payload;
125     }
126
127     return p - buf;
128 }
129
130 static int avfmt2_num_planes(int avfmt)
131 {
132     switch (avfmt) {
133     case PIX_FMT_YUV420P:
134     case PIX_FMT_YUVJ420P:
135     case PIX_FMT_YUV420P9:
136     case PIX_FMT_YUV420P10:
137     case PIX_FMT_YUV444P:
138         return 3;
139
140     case PIX_FMT_BGR24:
141     case PIX_FMT_RGB24:
142         return 1;
143
144     default:
145         return 3;
146     }
147 }
148
149 static int X264_frame(AVCodecContext *ctx, uint8_t *buf,
150                       int orig_bufsize, void *data)
151 {
152     X264Context *x4 = ctx->priv_data;
153     AVFrame *frame = data;
154     x264_nal_t *nal;
155     int nnal, i;
156     x264_picture_t pic_out;
157     int bufsize;
158
159     x264_picture_init( &x4->pic );
160     x4->pic.img.i_csp   = x4->params.i_csp;
161     if (x264_bit_depth > 8)
162         x4->pic.img.i_csp |= X264_CSP_HIGH_DEPTH;
163     x4->pic.img.i_plane = avfmt2_num_planes(ctx->pix_fmt);
164
165     if (frame) {
166         for (i = 0; i < x4->pic.img.i_plane; i++) {
167             x4->pic.img.plane[i]    = frame->data[i];
168             x4->pic.img.i_stride[i] = frame->linesize[i];
169         }
170
171         x4->pic.i_pts  = frame->pts;
172         x4->pic.i_type =
173             frame->pict_type == AV_PICTURE_TYPE_I ? X264_TYPE_KEYFRAME :
174             frame->pict_type == AV_PICTURE_TYPE_P ? X264_TYPE_P :
175             frame->pict_type == AV_PICTURE_TYPE_B ? X264_TYPE_B :
176                                             X264_TYPE_AUTO;
177         if (x4->params.b_tff != frame->top_field_first) {
178             x4->params.b_tff = frame->top_field_first;
179             x264_encoder_reconfig(x4->enc, &x4->params);
180         }
181         if (x4->params.vui.i_sar_height != ctx->sample_aspect_ratio.den
182          || x4->params.vui.i_sar_width != ctx->sample_aspect_ratio.num) {
183             x4->params.vui.i_sar_height = ctx->sample_aspect_ratio.den;
184             x4->params.vui.i_sar_width = ctx->sample_aspect_ratio.num;
185             x264_encoder_reconfig(x4->enc, &x4->params);
186         }
187     }
188
189     do {
190         bufsize = orig_bufsize;
191     if (x264_encoder_encode(x4->enc, &nal, &nnal, frame? &x4->pic: NULL, &pic_out) < 0)
192         return -1;
193
194     bufsize = encode_nals(ctx, buf, bufsize, nal, nnal, 0);
195     if (bufsize < 0)
196         return -1;
197     } while (!bufsize && !frame && x264_encoder_delayed_frames(x4->enc));
198
199     /* FIXME: libx264 now provides DTS, but AVFrame doesn't have a field for it. */
200     x4->out_pic.pts = pic_out.i_pts;
201
202     switch (pic_out.i_type) {
203     case X264_TYPE_IDR:
204     case X264_TYPE_I:
205         x4->out_pic.pict_type = AV_PICTURE_TYPE_I;
206         break;
207     case X264_TYPE_P:
208         x4->out_pic.pict_type = AV_PICTURE_TYPE_P;
209         break;
210     case X264_TYPE_B:
211     case X264_TYPE_BREF:
212         x4->out_pic.pict_type = AV_PICTURE_TYPE_B;
213         break;
214     }
215
216     x4->out_pic.key_frame = pic_out.b_keyframe;
217     if (bufsize)
218         x4->out_pic.quality = (pic_out.i_qpplus1 - 1) * FF_QP2LAMBDA;
219
220     return bufsize;
221 }
222
223 static av_cold int X264_close(AVCodecContext *avctx)
224 {
225     X264Context *x4 = avctx->priv_data;
226
227     av_freep(&avctx->extradata);
228     av_free(x4->sei);
229
230     if (x4->enc)
231         x264_encoder_close(x4->enc);
232
233     return 0;
234 }
235
236 #define OPT_STR(opt, param)                                                   \
237     do {                                                                      \
238         int ret;                                                              \
239         if (param && (ret = x264_param_parse(&x4->params, opt, param)) < 0) { \
240             if(ret == X264_PARAM_BAD_NAME)                                    \
241                 av_log(avctx, AV_LOG_ERROR,                                   \
242                         "bad option '%s': '%s'\n", opt, param);               \
243             else                                                              \
244                 av_log(avctx, AV_LOG_ERROR,                                   \
245                         "bad value for '%s': '%s'\n", opt, param);            \
246             return -1;                                                        \
247         }                                                                     \
248     } while (0);
249
250 static int convert_pix_fmt(enum PixelFormat pix_fmt)
251 {
252     switch (pix_fmt) {
253     case PIX_FMT_YUV420P:
254     case PIX_FMT_YUVJ420P:
255     case PIX_FMT_YUV420P9:
256     case PIX_FMT_YUV420P10: return X264_CSP_I420;
257     case PIX_FMT_YUV422P:
258     case PIX_FMT_YUV422P10: return X264_CSP_I422;
259     case PIX_FMT_YUV444P:
260     case PIX_FMT_YUV444P9:
261     case PIX_FMT_YUV444P10: return X264_CSP_I444;
262 #ifdef X264_CSP_BGR
263     case PIX_FMT_BGR24:
264         return X264_CSP_BGR;
265
266     case PIX_FMT_RGB24:
267         return X264_CSP_RGB;
268 #endif
269     };
270     return 0;
271 }
272
273 #define PARSE_X264_OPT(name, var)\
274     if (x4->var && x264_param_parse(&x4->params, name, x4->var) < 0) {\
275         av_log(avctx, AV_LOG_ERROR, "Error parsing option '%s' with value '%s'.\n", name, x4->var);\
276         return AVERROR(EINVAL);\
277     }
278
279 static av_cold int X264_init(AVCodecContext *avctx)
280 {
281     X264Context *x4 = avctx->priv_data;
282
283     x264_param_default(&x4->params);
284
285     x4->params.b_deblocking_filter         = avctx->flags & CODEC_FLAG_LOOP_FILTER;
286
287     x4->params.rc.f_ip_factor             = 1 / fabs(avctx->i_quant_factor);
288     x4->params.rc.f_pb_factor             = avctx->b_quant_factor;
289     x4->params.analyse.i_chroma_qp_offset = avctx->chromaoffset;
290     if (x4->preset || x4->tune)
291         if (x264_param_default_preset(&x4->params, x4->preset, x4->tune) < 0) {
292             av_log(avctx, AV_LOG_ERROR, "Error setting preset/tune %s/%s.\n", x4->preset, x4->tune);
293             return AVERROR(EINVAL);
294         }
295
296     if (avctx->level > 0)
297         x4->params.i_level_idc = avctx->level;
298
299     x4->params.pf_log               = X264_log;
300     x4->params.p_log_private        = avctx;
301     x4->params.i_log_level          = X264_LOG_DEBUG;
302     x4->params.i_csp                = convert_pix_fmt(avctx->pix_fmt);
303
304     OPT_STR("weightp", x4->wpredp);
305
306     if (avctx->bit_rate) {
307         x4->params.rc.i_bitrate   = avctx->bit_rate / 1000;
308         x4->params.rc.i_rc_method = X264_RC_ABR;
309     }
310     x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;
311     x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate    / 1000;
312     x4->params.rc.b_stat_write      = avctx->flags & CODEC_FLAG_PASS1;
313     if (avctx->flags & CODEC_FLAG_PASS2) {
314         x4->params.rc.b_stat_read = 1;
315     } else {
316 #if FF_API_X264_GLOBAL_OPTS
317         if (avctx->crf) {
318             x4->params.rc.i_rc_method   = X264_RC_CRF;
319             x4->params.rc.f_rf_constant = avctx->crf;
320             x4->params.rc.f_rf_constant_max = avctx->crf_max;
321         } else if (avctx->cqp > -1) {
322             x4->params.rc.i_rc_method   = X264_RC_CQP;
323             x4->params.rc.i_qp_constant = avctx->cqp;
324         }
325 #endif
326
327         if (x4->crf >= 0) {
328             x4->params.rc.i_rc_method   = X264_RC_CRF;
329             x4->params.rc.f_rf_constant = x4->crf;
330         } else if (x4->cqp >= 0) {
331             x4->params.rc.i_rc_method   = X264_RC_CQP;
332             x4->params.rc.i_qp_constant = x4->cqp;
333         }
334
335         if (x4->crf_max >= 0)
336             x4->params.rc.f_rf_constant_max = x4->crf_max;
337     }
338
339     OPT_STR("stats", x4->stats);
340
341     if (avctx->rc_buffer_size && avctx->rc_initial_buffer_occupancy &&
342         (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {
343         x4->params.rc.f_vbv_buffer_init =
344             (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;
345     }
346
347     OPT_STR("level", x4->level);
348
349     if(x4->x264opts){
350         const char *p= x4->x264opts;
351         while(p){
352             char param[256]={0}, val[256]={0};
353             if(sscanf(p, "%255[^:=]=%255[^:]", param, val) == 1){
354                 OPT_STR(param, "1");
355             }else
356                 OPT_STR(param, val);
357             p= strchr(p, ':');
358             p+=!!p;
359         }
360     }
361
362 #if FF_API_X264_GLOBAL_OPTS
363     if (avctx->aq_mode >= 0)
364         x4->params.rc.i_aq_mode = avctx->aq_mode;
365     if (avctx->aq_strength >= 0)
366         x4->params.rc.f_aq_strength = avctx->aq_strength;
367     if (avctx->psy_rd >= 0)
368         x4->params.analyse.f_psy_rd           = avctx->psy_rd;
369     if (avctx->psy_trellis >= 0)
370         x4->params.analyse.f_psy_trellis      = avctx->psy_trellis;
371     if (avctx->rc_lookahead >= 0)
372         x4->params.rc.i_lookahead             = avctx->rc_lookahead;
373     if (avctx->weighted_p_pred >= 0)
374         x4->params.analyse.i_weighted_pred    = avctx->weighted_p_pred;
375     if (avctx->bframebias)
376         x4->params.i_bframe_bias              = avctx->bframebias;
377     if (avctx->deblockalpha)
378         x4->params.i_deblocking_filter_alphac0 = avctx->deblockalpha;
379     if (avctx->deblockbeta)
380         x4->params.i_deblocking_filter_beta    = avctx->deblockbeta;
381     if (avctx->complexityblur >= 0)
382         x4->params.rc.f_complexity_blur        = avctx->complexityblur;
383     if (avctx->directpred >= 0)
384         x4->params.analyse.i_direct_mv_pred    = avctx->directpred;
385     if (avctx->partitions) {
386         if (avctx->partitions & X264_PART_I4X4)
387             x4->params.analyse.inter |= X264_ANALYSE_I4x4;
388         if (avctx->partitions & X264_PART_I8X8)
389             x4->params.analyse.inter |= X264_ANALYSE_I8x8;
390         if (avctx->partitions & X264_PART_P8X8)
391             x4->params.analyse.inter |= X264_ANALYSE_PSUB16x16;
392         if (avctx->partitions & X264_PART_P4X4)
393             x4->params.analyse.inter |= X264_ANALYSE_PSUB8x8;
394         if (avctx->partitions & X264_PART_B8X8)
395             x4->params.analyse.inter |= X264_ANALYSE_BSUB16x16;
396     }
397     if (avctx->flags2) {
398         x4->params.analyse.b_ssim = avctx->flags2 & CODEC_FLAG2_SSIM;
399         x4->params.b_intra_refresh = avctx->flags2 & CODEC_FLAG2_INTRA_REFRESH;
400         x4->params.i_bframe_pyramid = avctx->flags2 & CODEC_FLAG2_BPYRAMID ? X264_B_PYRAMID_NORMAL : X264_B_PYRAMID_NONE;
401         x4->params.analyse.b_weighted_bipred  = avctx->flags2 & CODEC_FLAG2_WPRED;
402         x4->params.analyse.b_mixed_references = avctx->flags2 & CODEC_FLAG2_MIXED_REFS;
403         x4->params.analyse.b_transform_8x8    = avctx->flags2 & CODEC_FLAG2_8X8DCT;
404         x4->params.analyse.b_fast_pskip       = avctx->flags2 & CODEC_FLAG2_FASTPSKIP;
405         x4->params.b_aud                      = avctx->flags2 & CODEC_FLAG2_AUD;
406         x4->params.analyse.b_psy              = avctx->flags2 & CODEC_FLAG2_PSY;
407         x4->params.rc.b_mb_tree               = !!(avctx->flags2 & CODEC_FLAG2_MBTREE);
408     }
409 #endif
410
411     if (avctx->me_method == ME_EPZS)
412         x4->params.analyse.i_me_method = X264_ME_DIA;
413     else if (avctx->me_method == ME_HEX)
414         x4->params.analyse.i_me_method = X264_ME_HEX;
415     else if (avctx->me_method == ME_UMH)
416         x4->params.analyse.i_me_method = X264_ME_UMH;
417     else if (avctx->me_method == ME_FULL)
418         x4->params.analyse.i_me_method = X264_ME_ESA;
419     else if (avctx->me_method == ME_TESA)
420         x4->params.analyse.i_me_method = X264_ME_TESA;
421
422     if (avctx->gop_size >= 0)
423         x4->params.i_keyint_max         = avctx->gop_size;
424     if (avctx->max_b_frames >= 0)
425         x4->params.i_bframe             = avctx->max_b_frames;
426     if (avctx->scenechange_threshold >= 0)
427         x4->params.i_scenecut_threshold = avctx->scenechange_threshold;
428     if (avctx->qmin >= 0)
429         x4->params.rc.i_qp_min          = avctx->qmin;
430     if (avctx->qmax >= 0)
431         x4->params.rc.i_qp_max          = avctx->qmax;
432     if (avctx->max_qdiff >= 0)
433         x4->params.rc.i_qp_step         = avctx->max_qdiff;
434     if (avctx->qblur >= 0)
435         x4->params.rc.f_qblur           = avctx->qblur;     /* temporally blur quants */
436     if (avctx->qcompress >= 0)
437         x4->params.rc.f_qcompress       = avctx->qcompress; /* 0.0 => cbr, 1.0 => constant qp */
438     if (avctx->refs >= 0)
439         x4->params.i_frame_reference    = avctx->refs;
440     if (avctx->trellis >= 0)
441         x4->params.analyse.i_trellis    = avctx->trellis;
442     if (avctx->me_range >= 0)
443         x4->params.analyse.i_me_range   = avctx->me_range;
444     if (avctx->noise_reduction >= 0)
445         x4->params.analyse.i_noise_reduction = avctx->noise_reduction;
446     if (avctx->me_subpel_quality >= 0)
447         x4->params.analyse.i_subpel_refine   = avctx->me_subpel_quality;
448     if (avctx->b_frame_strategy >= 0)
449         x4->params.i_bframe_adaptive = avctx->b_frame_strategy;
450     if (avctx->keyint_min >= 0)
451         x4->params.i_keyint_min = avctx->keyint_min;
452     if (avctx->coder_type >= 0)
453         x4->params.b_cabac = avctx->coder_type == FF_CODER_TYPE_AC;
454     if (avctx->me_cmp >= 0)
455         x4->params.analyse.b_chroma_me = avctx->me_cmp & FF_CMP_CHROMA;
456
457     if (x4->aq_mode >= 0)
458         x4->params.rc.i_aq_mode = x4->aq_mode;
459     if (x4->aq_strength >= 0)
460         x4->params.rc.f_aq_strength = x4->aq_strength;
461     PARSE_X264_OPT("psy-rd", psy_rd);
462     PARSE_X264_OPT("deblock", deblock);
463     PARSE_X264_OPT("partitions", partitions);
464     if (x4->psy >= 0)
465         x4->params.analyse.b_psy  = x4->psy;
466     if (x4->rc_lookahead >= 0)
467         x4->params.rc.i_lookahead = x4->rc_lookahead;
468     if (x4->weightp >= 0)
469         x4->params.analyse.i_weighted_pred = x4->weightp;
470     if (x4->weightb >= 0)
471         x4->params.analyse.b_weighted_bipred = x4->weightb;
472     if (x4->cplxblur >= 0)
473         x4->params.rc.f_complexity_blur = x4->cplxblur;
474
475     if (x4->ssim >= 0)
476         x4->params.analyse.b_ssim = x4->ssim;
477     if (x4->intra_refresh >= 0)
478         x4->params.b_intra_refresh = x4->intra_refresh;
479     if (x4->b_bias != INT_MIN)
480         x4->params.i_bframe_bias              = x4->b_bias;
481     if (x4->b_pyramid >= 0)
482         x4->params.i_bframe_pyramid = x4->b_pyramid;
483     if (x4->mixed_refs >= 0)
484         x4->params.analyse.b_mixed_references = x4->mixed_refs;
485     if (x4->dct8x8 >= 0)
486         x4->params.analyse.b_transform_8x8    = x4->dct8x8;
487     if (x4->fast_pskip >= 0)
488         x4->params.analyse.b_fast_pskip       = x4->fast_pskip;
489     if (x4->aud >= 0)
490         x4->params.b_aud                      = x4->aud;
491     if (x4->mbtree >= 0)
492         x4->params.rc.b_mb_tree               = x4->mbtree;
493     if (x4->direct_pred >= 0)
494         x4->params.analyse.i_direct_mv_pred   = x4->direct_pred;
495
496     if (x4->slice_max_size >= 0)
497         x4->params.i_slice_max_size =  x4->slice_max_size;
498
499     if (x4->fastfirstpass)
500         x264_param_apply_fastfirstpass(&x4->params);
501
502     if (x4->profile)
503         if (x264_param_apply_profile(&x4->params, x4->profile) < 0) {
504             av_log(avctx, AV_LOG_ERROR, "Error setting profile %s.\n", x4->profile);
505             return AVERROR(EINVAL);
506         }
507
508     x4->params.i_width          = avctx->width;
509     x4->params.i_height         = avctx->height;
510     x4->params.vui.i_sar_width  = avctx->sample_aspect_ratio.num;
511     x4->params.vui.i_sar_height = avctx->sample_aspect_ratio.den;
512     x4->params.i_fps_num = x4->params.i_timebase_den = avctx->time_base.den;
513     x4->params.i_fps_den = x4->params.i_timebase_num = avctx->time_base.num;
514
515     x4->params.analyse.b_psnr = avctx->flags & CODEC_FLAG_PSNR;
516
517     x4->params.i_threads      = avctx->thread_count;
518
519     x4->params.b_interlaced   = avctx->flags & CODEC_FLAG_INTERLACED_DCT;
520
521 //    x4->params.b_open_gop     = !(avctx->flags & CODEC_FLAG_CLOSED_GOP);
522
523     x4->params.i_slice_count  = avctx->slices;
524
525     x4->params.vui.b_fullrange = avctx->pix_fmt == PIX_FMT_YUVJ420P;
526
527     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER)
528         x4->params.b_repeat_headers = 0;
529
530     // update AVCodecContext with x264 parameters
531     avctx->has_b_frames = x4->params.i_bframe ?
532         x4->params.i_bframe_pyramid ? 2 : 1 : 0;
533     avctx->bit_rate = x4->params.rc.i_bitrate*1000;
534 #if FF_API_X264_GLOBAL_OPTS
535     avctx->crf = x4->params.rc.f_rf_constant;
536 #endif
537
538     x4->enc = x264_encoder_open(&x4->params);
539     if (!x4->enc)
540         return -1;
541
542     avctx->coded_frame = &x4->out_pic;
543
544     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
545         x264_nal_t *nal;
546         int nnal, s, i;
547
548         s = x264_encoder_headers(x4->enc, &nal, &nnal);
549
550         for (i = 0; i < nnal; i++)
551             if (nal[i].i_type == NAL_SEI)
552                 av_log(avctx, AV_LOG_INFO, "%s\n", nal[i].p_payload+25);
553
554         avctx->extradata      = av_malloc(s);
555         avctx->extradata_size = encode_nals(avctx, avctx->extradata, s, nal, nnal, 1);
556     }
557
558     return 0;
559 }
560
561 static const enum PixelFormat pix_fmts_8bit[] = {
562     PIX_FMT_YUV420P,
563     PIX_FMT_YUVJ420P,
564     PIX_FMT_YUV422P,
565     PIX_FMT_YUV444P,
566     PIX_FMT_NONE
567 };
568 static const enum PixelFormat pix_fmts_9bit[] = {
569     PIX_FMT_YUV420P9,
570     PIX_FMT_YUV444P9,
571     PIX_FMT_NONE
572 };
573 static const enum PixelFormat pix_fmts_10bit[] = {
574     PIX_FMT_YUV420P10,
575     PIX_FMT_YUV422P10,
576     PIX_FMT_YUV444P10,
577     PIX_FMT_NONE
578 };
579 static const enum PixelFormat pix_fmts_8bit_rgb[] = {
580 #ifdef X264_CSP_BGR
581     PIX_FMT_BGR24,
582     PIX_FMT_RGB24,
583 #endif
584     PIX_FMT_NONE
585 };
586
587 static av_cold void X264_init_static(AVCodec *codec)
588 {
589     if (x264_bit_depth == 8)
590         codec->pix_fmts = pix_fmts_8bit;
591     else if (x264_bit_depth == 9)
592         codec->pix_fmts = pix_fmts_9bit;
593     else if (x264_bit_depth == 10)
594         codec->pix_fmts = pix_fmts_10bit;
595 }
596
597 #define OFFSET(x) offsetof(X264Context, x)
598 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
599 static const AVOption options[] = {
600     { "preset",        "Set the encoding preset (cf. x264 --fullhelp)",   OFFSET(preset),        AV_OPT_TYPE_STRING, { .str = "medium" }, 0, 0, VE},
601     { "tune",          "Tune the encoding params (cf. x264 --fullhelp)",  OFFSET(tune),          AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE},
602     { "profile",       "Set profile restrictions (cf. x264 --fullhelp) ", OFFSET(profile),       AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE},
603     { "fastfirstpass", "Use fast settings when encoding first pass",      OFFSET(fastfirstpass), AV_OPT_TYPE_INT,    { 1 }, 0, 1, VE},
604     {"level", "Specify level (as defined by Annex A)", OFFSET(level), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
605     {"passlogfile", "Filename for 2 pass stats", OFFSET(stats), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
606     {"wpredp", "Weighted prediction for P-frames", OFFSET(wpredp), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
607     {"x264opts", "x264 options", OFFSET(x264opts), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
608     { "crf",           "Select the quality for constant quality mode",    OFFSET(crf),           AV_OPT_TYPE_FLOAT,  {-1 }, -1, FLT_MAX, VE },
609     { "crf_max",       "In CRF mode, prevents VBV from lowering quality beyond this point.",OFFSET(crf_max), AV_OPT_TYPE_FLOAT, {-1 }, -1, FLT_MAX, VE },
610     { "qp",            "Constant quantization parameter rate control method",OFFSET(cqp),        AV_OPT_TYPE_INT,    {-1 }, -1, INT_MAX, VE },
611     { "aq-mode",       "AQ method",                                       OFFSET(aq_mode),       AV_OPT_TYPE_INT,    {-1 }, -1, INT_MAX, VE, "aq_mode"},
612     { "none",          NULL,                              0, AV_OPT_TYPE_CONST, {X264_AQ_NONE},         INT_MIN, INT_MAX, VE, "aq_mode" },
613     { "variance",      "Variance AQ (complexity mask)",   0, AV_OPT_TYPE_CONST, {X264_AQ_VARIANCE},     INT_MIN, INT_MAX, VE, "aq_mode" },
614     { "autovariance",  "Auto-variance AQ (experimental)", 0, AV_OPT_TYPE_CONST, {X264_AQ_AUTOVARIANCE}, INT_MIN, INT_MAX, VE, "aq_mode" },
615     { "aq-strength",   "AQ strength. Reduces blocking and blurring in flat and textured areas.", OFFSET(aq_strength), AV_OPT_TYPE_FLOAT, {-1}, -1, FLT_MAX, VE},
616     { "psy",           "Use psychovisual optimizations.",                 OFFSET(psy),           AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE },
617     { "psy-rd",        "Strength of psychovisual optimization, in <psy-rd>:<psy-trellis> format.", OFFSET(psy_rd), AV_OPT_TYPE_STRING,  {0 }, 0, 0, VE},
618     { "rc-lookahead",  "Number of frames to look ahead for frametype and ratecontrol", OFFSET(rc_lookahead), AV_OPT_TYPE_INT, {-1 }, -1, INT_MAX, VE },
619     { "weightb",       "Weighted prediction for B-frames.",               OFFSET(weightb),       AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE },
620     { "weightp",       "Weighted prediction analysis method.",            OFFSET(weightp),       AV_OPT_TYPE_INT,    {-1 }, -1, INT_MAX, VE, "weightp" },
621     { "none",          NULL, 0, AV_OPT_TYPE_CONST, {X264_WEIGHTP_NONE},   INT_MIN, INT_MAX, VE, "weightp" },
622     { "simple",        NULL, 0, AV_OPT_TYPE_CONST, {X264_WEIGHTP_SIMPLE}, INT_MIN, INT_MAX, VE, "weightp" },
623     { "smart",         NULL, 0, AV_OPT_TYPE_CONST, {X264_WEIGHTP_SMART},  INT_MIN, INT_MAX, VE, "weightp" },
624     { "ssim",          "Calculate and print SSIM stats.",                 OFFSET(ssim),          AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE },
625     { "intra-refresh", "Use Periodic Intra Refresh instead of IDR frames.",OFFSET(intra_refresh),AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE },
626     { "b-bias",        "Influences how often B-frames are used",          OFFSET(b_bias),        AV_OPT_TYPE_INT,    {INT_MIN}, INT_MIN, INT_MAX, VE },
627     { "b-pyramid",     "Keep some B-frames as references.",               OFFSET(b_pyramid),     AV_OPT_TYPE_INT,    {-1 }, -1, INT_MAX, VE, "b_pyramid" },
628     { "none",          NULL,                                  0, AV_OPT_TYPE_CONST, {X264_B_PYRAMID_NONE},   INT_MIN, INT_MAX, VE, "b_pyramid" },
629     { "strict",        "Strictly hierarchical pyramid",       0, AV_OPT_TYPE_CONST, {X264_B_PYRAMID_STRICT}, INT_MIN, INT_MAX, VE, "b_pyramid" },
630     { "normal",        "Non-strict (not Blu-ray compatible)", 0, AV_OPT_TYPE_CONST, {X264_B_PYRAMID_NORMAL}, INT_MIN, INT_MAX, VE, "b_pyramid" },
631     { "mixed-refs",    "One reference per partition, as opposed to one reference per macroblock", OFFSET(mixed_refs), AV_OPT_TYPE_INT, {-1}, -1, 1, VE },
632     { "8x8dct",        "High profile 8x8 transform.",                     OFFSET(dct8x8),        AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE},
633     { "fast-pskip",    NULL,                                              OFFSET(fast_pskip),    AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE},
634     { "aud",           "Use access unit delimiters.",                     OFFSET(aud),           AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE},
635     { "mbtree",        "Use macroblock tree ratecontrol.",                OFFSET(mbtree),        AV_OPT_TYPE_INT,    {-1 }, -1, 1, VE},
636     { "deblock",       "Loop filter parameters, in <alpha:beta> form.",   OFFSET(deblock),       AV_OPT_TYPE_STRING, { 0 },  0, 0, VE},
637     { "cplxblur",      "Reduce fluctuations in QP (before curve compression)", OFFSET(cplxblur), AV_OPT_TYPE_FLOAT,  {-1 }, -1, FLT_MAX, VE},
638     { "partitions",    "A comma-separated list of partitions to consider. "
639                        "Possible values: p8x8, p4x4, b8x8, i8x8, i4x4, none, all", OFFSET(partitions), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE},
640     { "direct-pred",   "Direct MV prediction mode",                       OFFSET(direct_pred),   AV_OPT_TYPE_INT,    {-1 }, -1, INT_MAX, VE, "direct-pred" },
641     { "none",          NULL,      0,    AV_OPT_TYPE_CONST, { X264_DIRECT_PRED_NONE },     0, 0, VE, "direct-pred" },
642     { "spatial",       NULL,      0,    AV_OPT_TYPE_CONST, { X264_DIRECT_PRED_SPATIAL },  0, 0, VE, "direct-pred" },
643     { "temporal",      NULL,      0,    AV_OPT_TYPE_CONST, { X264_DIRECT_PRED_TEMPORAL }, 0, 0, VE, "direct-pred" },
644     { "auto",          NULL,      0,    AV_OPT_TYPE_CONST, { X264_DIRECT_PRED_AUTO },     0, 0, VE, "direct-pred" },
645     { "slice-max-size","Constant quantization parameter rate control method",OFFSET(slice_max_size),        AV_OPT_TYPE_INT,    {-1 }, -1, INT_MAX, VE },
646     { NULL },
647 };
648
649 static const AVClass class = {
650     .class_name = "libx264",
651     .item_name  = av_default_item_name,
652     .option     = options,
653     .version    = LIBAVUTIL_VERSION_INT,
654 };
655
656 static const AVClass rgbclass = {
657     .class_name = "libx264rgb",
658     .item_name  = av_default_item_name,
659     .option     = options,
660     .version    = LIBAVUTIL_VERSION_INT,
661 };
662
663 static const AVCodecDefault x264_defaults[] = {
664     { "b",                "0" },
665     { "bf",               "-1" },
666     { "flags2",           "0" },
667     { "g",                "-1" },
668     { "qmin",             "-1" },
669     { "qmax",             "-1" },
670     { "qdiff",            "-1" },
671     { "qblur",            "-1" },
672     { "qcomp",            "-1" },
673     { "rc_lookahead",     "-1" },
674     { "refs",             "-1" },
675     { "sc_threshold",     "-1" },
676     { "trellis",          "-1" },
677     { "nr",               "-1" },
678     { "me_range",         "-1" },
679     { "me_method",        "-1" },
680     { "subq",             "-1" },
681     { "b_strategy",       "-1" },
682     { "keyint_min",       "-1" },
683     { "coder",            "-1" },
684     { "cmp",              "-1" },
685     { "threads",          AV_STRINGIFY(X264_THREADS_AUTO) },
686     { NULL },
687 };
688
689 AVCodec ff_libx264_encoder = {
690     .name           = "libx264",
691     .type           = AVMEDIA_TYPE_VIDEO,
692     .id             = CODEC_ID_H264,
693     .priv_data_size = sizeof(X264Context),
694     .init           = X264_init,
695     .encode         = X264_frame,
696     .close          = X264_close,
697     .capabilities   = CODEC_CAP_DELAY,
698     .long_name      = NULL_IF_CONFIG_SMALL("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
699     .priv_class     = &class,
700     .defaults       = x264_defaults,
701     .init_static_data = X264_init_static,
702 };
703
704 AVCodec ff_libx264rgb_encoder = {
705     .name           = "libx264rgb",
706     .type           = AVMEDIA_TYPE_VIDEO,
707     .id             = CODEC_ID_H264,
708     .priv_data_size = sizeof(X264Context),
709     .init           = X264_init,
710     .encode         = X264_frame,
711     .close          = X264_close,
712     .capabilities   = CODEC_CAP_DELAY,
713     .long_name      = NULL_IF_CONFIG_SMALL("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 RGB"),
714     .priv_class     = &rgbclass,
715     .defaults       = x264_defaults,
716     .pix_fmts       = pix_fmts_8bit_rgb,
717 };