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.

850 lines
33KB

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