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