obs-x264.c 25 KB

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