obs-x264.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. /******************************************************************************
  2. Copyright (C) 2014 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <stdio.h>
  15. #include <string.h>
  16. #include <util/bmem.h>
  17. #include <util/dstr.h>
  18. #include <util/darray.h>
  19. #include <util/platform.h>
  20. #include <obs-module.h>
  21. #include <opts-parser.h>
  22. #ifndef _STDINT_H_INCLUDED
  23. #define _STDINT_H_INCLUDED
  24. #endif
  25. #include <x264.h>
  26. #define do_log(level, format, ...) \
  27. blog(level, "[x264 encoder: '%s'] " format, \
  28. obs_encoder_get_name(obsx264->encoder), ##__VA_ARGS__)
  29. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  30. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  31. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  32. //#define ENABLE_VFR
  33. /* ------------------------------------------------------------------------- */
  34. struct obs_x264 {
  35. obs_encoder_t *encoder;
  36. x264_param_t params;
  37. x264_t *context;
  38. DARRAY(uint8_t) packet_data;
  39. uint8_t *extra_data;
  40. uint8_t *sei;
  41. size_t extra_data_size;
  42. size_t sei_size;
  43. os_performance_token_t *performance_token;
  44. };
  45. /* ------------------------------------------------------------------------- */
  46. static const char *obs_x264_getname(void *unused)
  47. {
  48. UNUSED_PARAMETER(unused);
  49. return "x264";
  50. }
  51. static void obs_x264_stop(void *data);
  52. static void clear_data(struct obs_x264 *obsx264)
  53. {
  54. if (obsx264->context) {
  55. x264_encoder_close(obsx264->context);
  56. bfree(obsx264->sei);
  57. bfree(obsx264->extra_data);
  58. obsx264->context = NULL;
  59. obsx264->sei = NULL;
  60. obsx264->extra_data = NULL;
  61. }
  62. }
  63. static void obs_x264_destroy(void *data)
  64. {
  65. struct obs_x264 *obsx264 = data;
  66. if (obsx264) {
  67. os_end_high_performance(obsx264->performance_token);
  68. clear_data(obsx264);
  69. da_free(obsx264->packet_data);
  70. bfree(obsx264);
  71. }
  72. }
  73. static void obs_x264_defaults(obs_data_t *settings)
  74. {
  75. obs_data_set_default_int(settings, "bitrate", 2500);
  76. obs_data_set_default_bool(settings, "use_bufsize", false);
  77. obs_data_set_default_int(settings, "buffer_size", 2500);
  78. obs_data_set_default_int(settings, "keyint_sec", 0);
  79. obs_data_set_default_int(settings, "crf", 23);
  80. #ifdef ENABLE_VFR
  81. obs_data_set_default_bool(settings, "vfr", false);
  82. #endif
  83. obs_data_set_default_string(settings, "rate_control", "CBR");
  84. obs_data_set_default_string(settings, "preset", "veryfast");
  85. obs_data_set_default_string(settings, "profile", "");
  86. obs_data_set_default_string(settings, "tune", "");
  87. obs_data_set_default_string(settings, "x264opts", "");
  88. obs_data_set_default_bool(settings, "repeat_headers", false);
  89. }
  90. static inline void add_strings(obs_property_t *list, const char *const *strings)
  91. {
  92. while (*strings) {
  93. obs_property_list_add_string(list, *strings, *strings);
  94. strings++;
  95. }
  96. }
  97. #define TEXT_RATE_CONTROL obs_module_text("RateControl")
  98. #define TEXT_BITRATE obs_module_text("Bitrate")
  99. #define TEXT_CUSTOM_BUF obs_module_text("CustomBufsize")
  100. #define TEXT_BUF_SIZE obs_module_text("BufferSize")
  101. #define TEXT_VFR obs_module_text("VFR")
  102. #define TEXT_CRF obs_module_text("CRF")
  103. #define TEXT_KEYINT_SEC obs_module_text("KeyframeIntervalSec")
  104. #define TEXT_PRESET obs_module_text("CPUPreset")
  105. #define TEXT_PROFILE obs_module_text("Profile")
  106. #define TEXT_TUNE obs_module_text("Tune")
  107. #define TEXT_NONE obs_module_text("None")
  108. #define TEXT_X264_OPTS obs_module_text("EncoderOptions")
  109. static bool use_bufsize_modified(obs_properties_t *ppts, obs_property_t *p,
  110. obs_data_t *settings)
  111. {
  112. bool use_bufsize = obs_data_get_bool(settings, "use_bufsize");
  113. const char *rc = obs_data_get_string(settings, "rate_control");
  114. bool rc_crf = astrcmpi(rc, "CRF") == 0;
  115. p = obs_properties_get(ppts, "buffer_size");
  116. obs_property_set_visible(p, use_bufsize && !rc_crf);
  117. return true;
  118. }
  119. static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p,
  120. obs_data_t *settings)
  121. {
  122. const char *rc = obs_data_get_string(settings, "rate_control");
  123. bool use_bufsize = obs_data_get_bool(settings, "use_bufsize");
  124. bool abr = astrcmpi(rc, "CBR") == 0 || astrcmpi(rc, "ABR") == 0;
  125. bool rc_crf = astrcmpi(rc, "CRF") == 0;
  126. p = obs_properties_get(ppts, "crf");
  127. obs_property_set_visible(p, !abr);
  128. p = obs_properties_get(ppts, "bitrate");
  129. obs_property_set_visible(p, !rc_crf);
  130. p = obs_properties_get(ppts, "use_bufsize");
  131. obs_property_set_visible(p, !rc_crf);
  132. p = obs_properties_get(ppts, "buffer_size");
  133. obs_property_set_visible(p, !rc_crf && use_bufsize);
  134. return true;
  135. }
  136. static obs_properties_t *obs_x264_props(void *unused)
  137. {
  138. UNUSED_PARAMETER(unused);
  139. obs_properties_t *props = obs_properties_create();
  140. obs_property_t *list;
  141. obs_property_t *p;
  142. obs_property_t *headers;
  143. list = obs_properties_add_list(props, "rate_control", TEXT_RATE_CONTROL,
  144. OBS_COMBO_TYPE_LIST,
  145. OBS_COMBO_FORMAT_STRING);
  146. obs_property_list_add_string(list, "CBR", "CBR");
  147. obs_property_list_add_string(list, "ABR", "ABR");
  148. obs_property_list_add_string(list, "VBR", "VBR");
  149. obs_property_list_add_string(list, "CRF", "CRF");
  150. obs_property_set_modified_callback(list, rate_control_modified);
  151. p = obs_properties_add_int(props, "bitrate", TEXT_BITRATE, 50, 10000000,
  152. 50);
  153. obs_property_int_set_suffix(p, " Kbps");
  154. p = obs_properties_add_bool(props, "use_bufsize", TEXT_CUSTOM_BUF);
  155. obs_property_set_modified_callback(p, use_bufsize_modified);
  156. obs_properties_add_int(props, "buffer_size", TEXT_BUF_SIZE, 0, 10000000,
  157. 1);
  158. obs_properties_add_int(props, "crf", TEXT_CRF, 0, 51, 1);
  159. obs_properties_add_int(props, "keyint_sec", TEXT_KEYINT_SEC, 0, 20, 1);
  160. list = obs_properties_add_list(props, "preset", TEXT_PRESET,
  161. OBS_COMBO_TYPE_LIST,
  162. OBS_COMBO_FORMAT_STRING);
  163. add_strings(list, x264_preset_names);
  164. list = obs_properties_add_list(props, "profile", TEXT_PROFILE,
  165. OBS_COMBO_TYPE_LIST,
  166. OBS_COMBO_FORMAT_STRING);
  167. obs_property_list_add_string(list, TEXT_NONE, "");
  168. obs_property_list_add_string(list, "baseline", "baseline");
  169. obs_property_list_add_string(list, "main", "main");
  170. obs_property_list_add_string(list, "high", "high");
  171. list = obs_properties_add_list(props, "tune", TEXT_TUNE,
  172. OBS_COMBO_TYPE_LIST,
  173. OBS_COMBO_FORMAT_STRING);
  174. obs_property_list_add_string(list, TEXT_NONE, "");
  175. add_strings(list, x264_tune_names);
  176. #ifdef ENABLE_VFR
  177. obs_properties_add_bool(props, "vfr", TEXT_VFR);
  178. #endif
  179. obs_properties_add_text(props, "x264opts", TEXT_X264_OPTS,
  180. OBS_TEXT_DEFAULT);
  181. headers = obs_properties_add_bool(props, "repeat_headers",
  182. "repeat_headers");
  183. obs_property_set_visible(headers, false);
  184. return props;
  185. }
  186. static bool getparam(const char *param, char **name, const char **value)
  187. {
  188. const char *assign;
  189. if (!param || !*param || (*param == '='))
  190. return false;
  191. assign = strchr(param, '=');
  192. if (!assign || !*assign || !*(assign + 1))
  193. return false;
  194. *name = bstrdup_n(param, assign - param);
  195. *value = assign + 1;
  196. return true;
  197. }
  198. static const char *validate(struct obs_x264 *obsx264, const char *val,
  199. const char *name, const char *const *list)
  200. {
  201. if (!val || !*val)
  202. return val;
  203. while (*list) {
  204. if (strcmp(val, *list) == 0)
  205. return val;
  206. list++;
  207. }
  208. warn("Invalid %s: %s", name, val);
  209. return NULL;
  210. }
  211. static void override_base_param(struct obs_x264 *obsx264,
  212. struct obs_option option, char **preset,
  213. char **profile, char **tune)
  214. {
  215. const char *name = option.name;
  216. const char *val = option.value;
  217. if (astrcmpi(name, "preset") == 0) {
  218. const char *valid_name =
  219. validate(obsx264, val, "preset", x264_preset_names);
  220. if (valid_name) {
  221. bfree(*preset);
  222. *preset = bstrdup(val);
  223. }
  224. } else if (astrcmpi(name, "profile") == 0) {
  225. const char *valid_name =
  226. validate(obsx264, val, "profile", x264_profile_names);
  227. if (valid_name) {
  228. bfree(*profile);
  229. *profile = bstrdup(val);
  230. }
  231. } else if (astrcmpi(name, "tune") == 0) {
  232. const char *valid_name =
  233. validate(obsx264, val, "tune", x264_tune_names);
  234. if (valid_name) {
  235. bfree(*tune);
  236. *tune = bstrdup(val);
  237. }
  238. }
  239. }
  240. static inline void override_base_params(struct obs_x264 *obsx264,
  241. const struct obs_options *options,
  242. char **preset, char **profile,
  243. char **tune)
  244. {
  245. for (size_t i = 0; i < options->count; ++i)
  246. override_base_param(obsx264, options->options[i], preset,
  247. profile, tune);
  248. }
  249. #define OPENCL_ALIAS "opencl_is_experimental_and_potentially_unstable"
  250. static inline void set_param(struct obs_x264 *obsx264, struct obs_option option)
  251. {
  252. const char *name = option.name;
  253. const char *val = option.value;
  254. if (strcmp(name, "preset") != 0 && strcmp(name, "profile") != 0 &&
  255. strcmp(name, "tune") != 0 && strcmp(name, "fps") != 0 &&
  256. strcmp(name, "force-cfr") != 0 && strcmp(name, "width") != 0 &&
  257. strcmp(name, "height") != 0 && strcmp(name, "opencl") != 0) {
  258. if (strcmp(option.name, OPENCL_ALIAS) == 0)
  259. name = "opencl";
  260. if (x264_param_parse(&obsx264->params, name, val) != 0)
  261. warn("x264 param: %s=%s failed", name, val);
  262. }
  263. }
  264. static inline void apply_x264_profile(struct obs_x264 *obsx264,
  265. const char *profile)
  266. {
  267. if (!obsx264->context && profile && *profile) {
  268. int ret = x264_param_apply_profile(&obsx264->params, profile);
  269. if (ret != 0)
  270. warn("Failed to set x264 profile '%s'", profile);
  271. }
  272. }
  273. static inline const char *validate_preset(struct obs_x264 *obsx264,
  274. const char *preset)
  275. {
  276. const char *new_preset =
  277. validate(obsx264, preset, "preset", x264_preset_names);
  278. return new_preset ? new_preset : "veryfast";
  279. }
  280. static bool reset_x264_params(struct obs_x264 *obsx264, const char *preset,
  281. const char *tune)
  282. {
  283. int ret = x264_param_default_preset(
  284. &obsx264->params, validate_preset(obsx264, preset),
  285. validate(obsx264, tune, "tune", x264_tune_names));
  286. return ret == 0;
  287. }
  288. static void log_x264(void *param, int level, const char *format, va_list args)
  289. {
  290. struct obs_x264 *obsx264 = param;
  291. char str[1024];
  292. vsnprintf(str, 1024, format, args);
  293. info("%s", str);
  294. UNUSED_PARAMETER(level);
  295. }
  296. static inline int get_x264_cs_val(const char *const name,
  297. const char *const names[])
  298. {
  299. int idx = 0;
  300. do {
  301. if (strcmp(names[idx], name) == 0)
  302. return idx;
  303. } while (!!names[++idx]);
  304. return 0;
  305. }
  306. static void obs_x264_video_info(void *data, struct video_scale_info *info);
  307. enum rate_control {
  308. RATE_CONTROL_CBR,
  309. RATE_CONTROL_VBR,
  310. RATE_CONTROL_ABR,
  311. RATE_CONTROL_CRF
  312. };
  313. static void update_params(struct obs_x264 *obsx264, obs_data_t *settings,
  314. const struct obs_options *options, bool update)
  315. {
  316. video_t *video = obs_encoder_video(obsx264->encoder);
  317. const struct video_output_info *voi = video_output_get_info(video);
  318. struct video_scale_info info;
  319. info.format = voi->format;
  320. info.colorspace = voi->colorspace;
  321. info.range = voi->range;
  322. obs_x264_video_info(obsx264, &info);
  323. const char *rate_control =
  324. obs_data_get_string(settings, "rate_control");
  325. int bitrate = (int)obs_data_get_int(settings, "bitrate");
  326. int buffer_size = (int)obs_data_get_int(settings, "buffer_size");
  327. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  328. int crf = (int)obs_data_get_int(settings, "crf");
  329. int width = (int)obs_encoder_get_width(obsx264->encoder);
  330. int height = (int)obs_encoder_get_height(obsx264->encoder);
  331. int bf = (int)obs_data_get_int(settings, "bf");
  332. bool use_bufsize = obs_data_get_bool(settings, "use_bufsize");
  333. bool cbr_override = obs_data_get_bool(settings, "cbr");
  334. enum rate_control rc;
  335. #ifdef ENABLE_VFR
  336. bool vfr = obs_data_get_bool(settings, "vfr");
  337. #endif
  338. /* XXX: "cbr" setting has been deprecated */
  339. if (cbr_override) {
  340. warn("\"cbr\" setting has been deprecated for all encoders! "
  341. "Please set \"rate_control\" to \"CBR\" instead. "
  342. "Forcing CBR mode. "
  343. "(Note to all: this is why you shouldn't use strings for "
  344. "common settings)");
  345. rate_control = "CBR";
  346. }
  347. if (astrcmpi(rate_control, "ABR") == 0) {
  348. rc = RATE_CONTROL_ABR;
  349. crf = 0;
  350. } else if (astrcmpi(rate_control, "VBR") == 0) {
  351. rc = RATE_CONTROL_VBR;
  352. } else if (astrcmpi(rate_control, "CRF") == 0) {
  353. rc = RATE_CONTROL_CRF;
  354. bitrate = 0;
  355. buffer_size = 0;
  356. } else { /* CBR */
  357. rc = RATE_CONTROL_CBR;
  358. crf = 0;
  359. }
  360. if (keyint_sec)
  361. obsx264->params.i_keyint_max =
  362. keyint_sec * voi->fps_num / voi->fps_den;
  363. if (!use_bufsize)
  364. buffer_size = bitrate;
  365. #ifdef ENABLE_VFR
  366. obsx264->params.b_vfr_input = vfr;
  367. #else
  368. obsx264->params.b_vfr_input = false;
  369. #endif
  370. obsx264->params.rc.i_vbv_max_bitrate = bitrate;
  371. obsx264->params.rc.i_vbv_buffer_size = buffer_size;
  372. obsx264->params.rc.i_bitrate = bitrate;
  373. obsx264->params.i_width = width;
  374. obsx264->params.i_height = height;
  375. obsx264->params.i_fps_num = voi->fps_num;
  376. obsx264->params.i_fps_den = voi->fps_den;
  377. obsx264->params.i_timebase_num = voi->fps_den;
  378. obsx264->params.i_timebase_den = voi->fps_num;
  379. obsx264->params.pf_log = log_x264;
  380. obsx264->params.p_log_private = obsx264;
  381. obsx264->params.i_log_level = X264_LOG_WARNING;
  382. if (obs_data_has_user_value(settings, "bf"))
  383. obsx264->params.i_bframe = bf;
  384. static const char *const smpte170m = "smpte170m";
  385. static const char *const bt709 = "bt709";
  386. static const char *const iec61966_2_1 = "iec61966-2-1";
  387. const char *colorprim = NULL;
  388. const char *transfer = NULL;
  389. const char *colmatrix = NULL;
  390. switch (info.colorspace) {
  391. case VIDEO_CS_601:
  392. colorprim = smpte170m;
  393. transfer = smpte170m;
  394. colmatrix = smpte170m;
  395. break;
  396. case VIDEO_CS_DEFAULT:
  397. case VIDEO_CS_709:
  398. colorprim = bt709;
  399. transfer = bt709;
  400. colmatrix = bt709;
  401. break;
  402. case VIDEO_CS_SRGB:
  403. colorprim = bt709;
  404. transfer = iec61966_2_1;
  405. colmatrix = bt709;
  406. break;
  407. }
  408. obsx264->params.vui.i_sar_height = 1;
  409. obsx264->params.vui.i_sar_width = 1;
  410. obsx264->params.vui.b_fullrange = info.range == VIDEO_RANGE_FULL;
  411. obsx264->params.vui.i_colorprim =
  412. get_x264_cs_val(colorprim, x264_colorprim_names);
  413. obsx264->params.vui.i_transfer =
  414. get_x264_cs_val(transfer, x264_transfer_names);
  415. obsx264->params.vui.i_colmatrix =
  416. get_x264_cs_val(colmatrix, x264_colmatrix_names);
  417. /* use the new filler method for CBR to allow real-time adjusting of
  418. * the bitrate */
  419. if (rc == RATE_CONTROL_CBR || rc == RATE_CONTROL_ABR) {
  420. obsx264->params.rc.i_rc_method = X264_RC_ABR;
  421. if (rc == RATE_CONTROL_CBR) {
  422. #if X264_BUILD >= 139
  423. obsx264->params.rc.b_filler = true;
  424. #else
  425. obsx264->params.i_nal_hrd = X264_NAL_HRD_CBR;
  426. #endif
  427. }
  428. } else {
  429. obsx264->params.rc.i_rc_method = X264_RC_CRF;
  430. obsx264->params.rc.f_rf_constant = (float)crf;
  431. }
  432. if (info.format == VIDEO_FORMAT_NV12)
  433. obsx264->params.i_csp = X264_CSP_NV12;
  434. else if (info.format == VIDEO_FORMAT_I420)
  435. obsx264->params.i_csp = X264_CSP_I420;
  436. else if (info.format == VIDEO_FORMAT_I444)
  437. obsx264->params.i_csp = X264_CSP_I444;
  438. else
  439. obsx264->params.i_csp = X264_CSP_NV12;
  440. for (size_t i = 0; i < options->ignored_word_count; ++i)
  441. warn("ignoring invalid x264 option: %s",
  442. options->ignored_words[i]);
  443. for (size_t i = 0; i < options->count; ++i)
  444. set_param(obsx264, options->options[i]);
  445. if (!update) {
  446. info("settings:\n"
  447. "\trate_control: %s\n"
  448. "\tbitrate: %d\n"
  449. "\tbuffer size: %d\n"
  450. "\tcrf: %d\n"
  451. "\tfps_num: %d\n"
  452. "\tfps_den: %d\n"
  453. "\twidth: %d\n"
  454. "\theight: %d\n"
  455. "\tkeyint: %d\n",
  456. rate_control, obsx264->params.rc.i_vbv_max_bitrate,
  457. obsx264->params.rc.i_vbv_buffer_size,
  458. (int)obsx264->params.rc.f_rf_constant, voi->fps_num,
  459. voi->fps_den, width, height, obsx264->params.i_keyint_max);
  460. }
  461. }
  462. static void log_custom_options(struct obs_x264 *obsx264,
  463. const struct obs_options *options)
  464. {
  465. if (options->count == 0) {
  466. return;
  467. }
  468. size_t settings_string_length = 0;
  469. for (size_t i = 0; i < options->count; ++i)
  470. settings_string_length += strlen(options->options[i].name) +
  471. strlen(options->options[i].value) + 5;
  472. size_t buffer_size = settings_string_length + 1;
  473. char *settings_string = bmalloc(settings_string_length + 1);
  474. char *p = settings_string;
  475. size_t remaining_buffer_size = buffer_size;
  476. for (size_t i = 0; i < options->count; ++i) {
  477. int chars_written = snprintf(p, remaining_buffer_size,
  478. "\n\t%s = %s",
  479. options->options[i].name,
  480. options->options[i].value);
  481. assert(chars_written >= 0);
  482. assert((size_t)chars_written <= remaining_buffer_size);
  483. p += chars_written;
  484. remaining_buffer_size -= chars_written;
  485. }
  486. assert(remaining_buffer_size == 1);
  487. assert(*p == '\0');
  488. info("custom settings: %s", settings_string);
  489. bfree(settings_string);
  490. }
  491. static bool update_settings(struct obs_x264 *obsx264, obs_data_t *settings,
  492. bool update)
  493. {
  494. char *preset = bstrdup(obs_data_get_string(settings, "preset"));
  495. char *profile = bstrdup(obs_data_get_string(settings, "profile"));
  496. char *tune = bstrdup(obs_data_get_string(settings, "tune"));
  497. struct obs_options options =
  498. obs_parse_options(obs_data_get_string(settings, "x264opts"));
  499. bool repeat_headers = obs_data_get_bool(settings, "repeat_headers");
  500. bool success = true;
  501. if (!update)
  502. blog(LOG_INFO, "---------------------------------");
  503. if (!obsx264->context) {
  504. override_base_params(obsx264, &options, &preset, &profile,
  505. &tune);
  506. if (preset && *preset)
  507. info("preset: %s", preset);
  508. if (profile && *profile)
  509. info("profile: %s", profile);
  510. if (tune && *tune)
  511. info("tune: %s", tune);
  512. success = reset_x264_params(obsx264, preset, tune);
  513. }
  514. if (repeat_headers) {
  515. obsx264->params.b_repeat_headers = 1;
  516. obsx264->params.b_annexb = 1;
  517. obsx264->params.b_aud = 1;
  518. }
  519. if (success) {
  520. update_params(obsx264, settings, &options, update);
  521. if (!update) {
  522. log_custom_options(obsx264, &options);
  523. }
  524. if (!obsx264->context)
  525. apply_x264_profile(obsx264, profile);
  526. }
  527. obs_free_options(options);
  528. bfree(preset);
  529. bfree(profile);
  530. bfree(tune);
  531. return success;
  532. }
  533. static bool obs_x264_update(void *data, obs_data_t *settings)
  534. {
  535. struct obs_x264 *obsx264 = data;
  536. bool success = update_settings(obsx264, settings, true);
  537. int ret;
  538. if (success) {
  539. ret = x264_encoder_reconfig(obsx264->context, &obsx264->params);
  540. if (ret != 0)
  541. warn("Failed to reconfigure: %d", ret);
  542. return ret == 0;
  543. }
  544. return false;
  545. }
  546. static void load_headers(struct obs_x264 *obsx264)
  547. {
  548. x264_nal_t *nals;
  549. int nal_count;
  550. DARRAY(uint8_t) header;
  551. DARRAY(uint8_t) sei;
  552. da_init(header);
  553. da_init(sei);
  554. x264_encoder_headers(obsx264->context, &nals, &nal_count);
  555. for (int i = 0; i < nal_count; i++) {
  556. x264_nal_t *nal = nals + i;
  557. if (nal->i_type == NAL_SEI)
  558. da_push_back_array(sei, nal->p_payload, nal->i_payload);
  559. else
  560. da_push_back_array(header, nal->p_payload,
  561. nal->i_payload);
  562. }
  563. obsx264->extra_data = header.array;
  564. obsx264->extra_data_size = header.num;
  565. obsx264->sei = sei.array;
  566. obsx264->sei_size = sei.num;
  567. }
  568. static void *obs_x264_create(obs_data_t *settings, obs_encoder_t *encoder)
  569. {
  570. struct obs_x264 *obsx264 = bzalloc(sizeof(struct obs_x264));
  571. obsx264->encoder = encoder;
  572. if (update_settings(obsx264, settings, false)) {
  573. obsx264->context = x264_encoder_open(&obsx264->params);
  574. if (obsx264->context == NULL)
  575. warn("x264 failed to load");
  576. else
  577. load_headers(obsx264);
  578. } else {
  579. warn("bad settings specified");
  580. }
  581. if (!obsx264->context) {
  582. bfree(obsx264);
  583. return NULL;
  584. }
  585. obsx264->performance_token =
  586. os_request_high_performance("x264 encoding");
  587. return obsx264;
  588. }
  589. static void parse_packet(struct obs_x264 *obsx264,
  590. struct encoder_packet *packet, x264_nal_t *nals,
  591. int nal_count, x264_picture_t *pic_out)
  592. {
  593. if (!nal_count)
  594. return;
  595. da_resize(obsx264->packet_data, 0);
  596. for (int i = 0; i < nal_count; i++) {
  597. x264_nal_t *nal = nals + i;
  598. da_push_back_array(obsx264->packet_data, nal->p_payload,
  599. nal->i_payload);
  600. }
  601. packet->data = obsx264->packet_data.array;
  602. packet->size = obsx264->packet_data.num;
  603. packet->type = OBS_ENCODER_VIDEO;
  604. packet->pts = pic_out->i_pts;
  605. packet->dts = pic_out->i_dts;
  606. packet->keyframe = pic_out->b_keyframe != 0;
  607. }
  608. static inline void init_pic_data(struct obs_x264 *obsx264, x264_picture_t *pic,
  609. struct encoder_frame *frame)
  610. {
  611. x264_picture_init(pic);
  612. pic->i_pts = frame->pts;
  613. pic->img.i_csp = obsx264->params.i_csp;
  614. if (obsx264->params.i_csp == X264_CSP_NV12)
  615. pic->img.i_plane = 2;
  616. else if (obsx264->params.i_csp == X264_CSP_I420)
  617. pic->img.i_plane = 3;
  618. else if (obsx264->params.i_csp == X264_CSP_I444)
  619. pic->img.i_plane = 3;
  620. for (int i = 0; i < pic->img.i_plane; i++) {
  621. pic->img.i_stride[i] = (int)frame->linesize[i];
  622. pic->img.plane[i] = frame->data[i];
  623. }
  624. }
  625. static bool obs_x264_encode(void *data, struct encoder_frame *frame,
  626. struct encoder_packet *packet,
  627. bool *received_packet)
  628. {
  629. struct obs_x264 *obsx264 = data;
  630. x264_nal_t *nals;
  631. int nal_count;
  632. int ret;
  633. x264_picture_t pic, pic_out;
  634. if (!frame || !packet || !received_packet)
  635. return false;
  636. if (frame)
  637. init_pic_data(obsx264, &pic, frame);
  638. ret = x264_encoder_encode(obsx264->context, &nals, &nal_count,
  639. (frame ? &pic : NULL), &pic_out);
  640. if (ret < 0) {
  641. warn("encode failed");
  642. return false;
  643. }
  644. *received_packet = (nal_count != 0);
  645. parse_packet(obsx264, packet, nals, nal_count, &pic_out);
  646. return true;
  647. }
  648. static bool obs_x264_extra_data(void *data, uint8_t **extra_data, size_t *size)
  649. {
  650. struct obs_x264 *obsx264 = data;
  651. if (!obsx264->context)
  652. return false;
  653. *extra_data = obsx264->extra_data;
  654. *size = obsx264->extra_data_size;
  655. return true;
  656. }
  657. static bool obs_x264_sei(void *data, uint8_t **sei, size_t *size)
  658. {
  659. struct obs_x264 *obsx264 = data;
  660. if (!obsx264->context)
  661. return false;
  662. *sei = obsx264->sei;
  663. *size = obsx264->sei_size;
  664. return true;
  665. }
  666. static inline bool valid_format(enum video_format format)
  667. {
  668. return format == VIDEO_FORMAT_I420 || format == VIDEO_FORMAT_NV12 ||
  669. format == VIDEO_FORMAT_I444;
  670. }
  671. static void obs_x264_video_info(void *data, struct video_scale_info *info)
  672. {
  673. struct obs_x264 *obsx264 = data;
  674. enum video_format pref_format;
  675. pref_format = obs_encoder_get_preferred_video_format(obsx264->encoder);
  676. if (!valid_format(pref_format)) {
  677. pref_format = valid_format(info->format) ? info->format
  678. : VIDEO_FORMAT_NV12;
  679. }
  680. info->format = pref_format;
  681. }
  682. struct obs_encoder_info obs_x264_encoder = {
  683. .id = "obs_x264",
  684. .type = OBS_ENCODER_VIDEO,
  685. .codec = "h264",
  686. .get_name = obs_x264_getname,
  687. .create = obs_x264_create,
  688. .destroy = obs_x264_destroy,
  689. .encode = obs_x264_encode,
  690. .update = obs_x264_update,
  691. .get_properties = obs_x264_props,
  692. .get_defaults = obs_x264_defaults,
  693. .get_extra_data = obs_x264_extra_data,
  694. .get_sei_data = obs_x264_sei,
  695. .get_video_info = obs_x264_video_info,
  696. .caps = OBS_ENCODER_CAP_DYN_BITRATE,
  697. };