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.

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