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.

769 lines
30KB

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