You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

912 lines
35KB

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