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.

913 lines
36KB

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