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.

827 lines
32KB

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