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