window-basic-auto-config-test.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. #include <chrono>
  2. #include <QFormLayout>
  3. #include <obs.hpp>
  4. #include <util/platform.h>
  5. #include <util/util_uint64.h>
  6. #include <graphics/vec4.h>
  7. #include <graphics/graphics.h>
  8. #include <graphics/math-extra.h>
  9. #include "window-basic-auto-config.hpp"
  10. #include "window-basic-main.hpp"
  11. #include "streaming-helpers.hpp"
  12. #include "qt-wrappers.hpp"
  13. #include "obs-app.hpp"
  14. #include "ui_AutoConfigTestPage.h"
  15. #define wiz reinterpret_cast<AutoConfig *>(wizard())
  16. using namespace std;
  17. using namespace json11;
  18. /* ------------------------------------------------------------------------- */
  19. class TestMode {
  20. obs_video_info ovi;
  21. OBSSource source[6];
  22. static void render_rand(void *, uint32_t cx, uint32_t cy)
  23. {
  24. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  25. gs_eparam_t *randomvals[3] = {
  26. gs_effect_get_param_by_name(solid, "randomvals1"),
  27. gs_effect_get_param_by_name(solid, "randomvals2"),
  28. gs_effect_get_param_by_name(solid, "randomvals3")};
  29. struct vec4 r;
  30. for (int i = 0; i < 3; i++) {
  31. vec4_set(&r, rand_float(true) * 100.0f,
  32. rand_float(true) * 100.0f,
  33. rand_float(true) * 50000.0f + 10000.0f, 0.0f);
  34. gs_effect_set_vec4(randomvals[i], &r);
  35. }
  36. while (gs_effect_loop(solid, "Random"))
  37. gs_draw_sprite(nullptr, 0, cx, cy);
  38. }
  39. public:
  40. inline TestMode()
  41. {
  42. obs_get_video_info(&ovi);
  43. obs_add_main_render_callback(render_rand, this);
  44. for (uint32_t i = 0; i < 6; i++) {
  45. source[i] = obs_get_output_source(i);
  46. obs_source_release(source[i]);
  47. obs_set_output_source(i, nullptr);
  48. }
  49. }
  50. inline ~TestMode()
  51. {
  52. for (uint32_t i = 0; i < 6; i++)
  53. obs_set_output_source(i, source[i]);
  54. obs_remove_main_render_callback(render_rand, this);
  55. obs_reset_video(&ovi);
  56. }
  57. inline void SetVideo(int cx, int cy, int fps_num, int fps_den)
  58. {
  59. obs_video_info newOVI = ovi;
  60. newOVI.output_width = (uint32_t)cx;
  61. newOVI.output_height = (uint32_t)cy;
  62. newOVI.fps_num = (uint32_t)fps_num;
  63. newOVI.fps_den = (uint32_t)fps_den;
  64. obs_reset_video(&newOVI);
  65. }
  66. };
  67. /* ------------------------------------------------------------------------- */
  68. #define TEST_STR(x) "Basic.AutoConfig.TestPage." x
  69. #define SUBTITLE_TESTING TEST_STR("Subtitle.Testing")
  70. #define SUBTITLE_COMPLETE TEST_STR("Subtitle.Complete")
  71. #define TEST_BW TEST_STR("TestingBandwidth")
  72. #define TEST_BW_CONNECTING TEST_STR("TestingBandwidth.Connecting")
  73. #define TEST_BW_CONNECT_FAIL TEST_STR("TestingBandwidth.ConnectFailed")
  74. #define TEST_BW_SERVER TEST_STR("TestingBandwidth.Server")
  75. #define TEST_RES TEST_STR("TestingRes")
  76. #define TEST_RES_VAL TEST_STR("TestingRes.Resolution")
  77. #define TEST_RES_FAIL TEST_STR("TestingRes.Fail")
  78. #define TEST_SE TEST_STR("TestingStreamEncoder")
  79. #define TEST_RE TEST_STR("TestingRecordingEncoder")
  80. #define TEST_RESULT_SE TEST_STR("Result.StreamingEncoder")
  81. #define TEST_RESULT_RE TEST_STR("Result.RecordingEncoder")
  82. void AutoConfigTestPage::StartBandwidthStage()
  83. {
  84. ui->progressLabel->setText(QTStr(TEST_BW));
  85. testThread = std::thread([this]() { TestBandwidthThread(); });
  86. }
  87. void AutoConfigTestPage::StartStreamEncoderStage()
  88. {
  89. ui->progressLabel->setText(QTStr(TEST_SE));
  90. testThread = std::thread([this]() { TestStreamEncoderThread(); });
  91. }
  92. void AutoConfigTestPage::StartRecordingEncoderStage()
  93. {
  94. ui->progressLabel->setText(QTStr(TEST_RE));
  95. testThread = std::thread([this]() { TestRecordingEncoderThread(); });
  96. }
  97. void AutoConfigTestPage::GetServers(std::vector<ServerInfo> &servers)
  98. {
  99. Json root = get_services_json();
  100. Json service = get_service_from_json(root, wiz->serviceName.c_str());
  101. auto &json_services = service["servers"].array_items();
  102. for (const Json &server : json_services) {
  103. const std::string &name = server["name"].string_value();
  104. const std::string &url = server["url"].string_value();
  105. if (wiz->CanTestServer(name.c_str())) {
  106. ServerInfo info(name, url);
  107. servers.push_back(info);
  108. }
  109. }
  110. }
  111. static inline void string_depad_key(string &key)
  112. {
  113. while (!key.empty()) {
  114. char ch = key.back();
  115. if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')
  116. key.pop_back();
  117. else
  118. break;
  119. }
  120. }
  121. const char *FindAudioEncoderFromCodec(const char *type);
  122. void AutoConfigTestPage::TestBandwidthThread()
  123. {
  124. bool connected = false;
  125. bool stopped = false;
  126. TestMode testMode;
  127. testMode.SetVideo(128, 128, 60, 1);
  128. QMetaObject::invokeMethod(this, "Progress", Q_ARG(int, 0));
  129. /*
  130. * create encoders
  131. * create output
  132. * test for 10 seconds
  133. */
  134. QMetaObject::invokeMethod(this, "UpdateMessage",
  135. Q_ARG(QString, QStringLiteral("")));
  136. /* -----------------------------------*/
  137. /* create obs objects */
  138. const char *serverType = wiz->customServer ? "rtmp_custom"
  139. : "rtmp_common";
  140. OBSEncoderAutoRelease vencoder = obs_video_encoder_create(
  141. "obs_x264", "test_x264", nullptr, nullptr);
  142. OBSEncoderAutoRelease aencoder = obs_audio_encoder_create(
  143. "ffmpeg_aac", "test_aac", nullptr, 0, nullptr);
  144. OBSServiceAutoRelease service = obs_service_create(
  145. serverType, "test_service", nullptr, nullptr);
  146. /* -----------------------------------*/
  147. /* configure settings */
  148. // service: "service", "server", "key"
  149. // vencoder: "bitrate", "rate_control",
  150. // obs_service_apply_encoder_settings
  151. // aencoder: "bitrate"
  152. // output: "bind_ip" via main config -> "Output", "BindIP"
  153. // obs_output_set_service
  154. OBSDataAutoRelease service_settings = obs_data_create();
  155. OBSDataAutoRelease vencoder_settings = obs_data_create();
  156. OBSDataAutoRelease aencoder_settings = obs_data_create();
  157. OBSDataAutoRelease output_settings = obs_data_create();
  158. std::string key = wiz->key;
  159. if (wiz->service == AutoConfig::Service::Twitch) {
  160. string_depad_key(key);
  161. key += "?bandwidthtest";
  162. } else if (wiz->serviceName == "Restream.io" ||
  163. wiz->serviceName == "Restream.io - RTMP") {
  164. string_depad_key(key);
  165. key += "?test=true";
  166. } else if (wiz->serviceName == "Restream.io - FTL") {
  167. string_depad_key(key);
  168. key += "?test";
  169. }
  170. obs_data_set_string(service_settings, "service",
  171. wiz->serviceName.c_str());
  172. obs_data_set_string(service_settings, "key", key.c_str());
  173. obs_data_set_int(vencoder_settings, "bitrate", wiz->startingBitrate);
  174. obs_data_set_string(vencoder_settings, "rate_control", "CBR");
  175. obs_data_set_string(vencoder_settings, "preset", "veryfast");
  176. obs_data_set_int(vencoder_settings, "keyint_sec", 2);
  177. obs_data_set_int(aencoder_settings, "bitrate", 32);
  178. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  179. const char *bind_ip =
  180. config_get_string(main->Config(), "Output", "BindIP");
  181. obs_data_set_string(output_settings, "bind_ip", bind_ip);
  182. /* -----------------------------------*/
  183. /* determine which servers to test */
  184. std::vector<ServerInfo> servers;
  185. if (wiz->customServer)
  186. servers.emplace_back(wiz->server.c_str(), wiz->server.c_str());
  187. else
  188. GetServers(servers);
  189. /* just use the first server if it only has one alternate server,
  190. * or if using Restream or Nimo TV due to their "auto" servers */
  191. if (servers.size() < 3 ||
  192. wiz->serviceName.substr(0, 11) == "Restream.io" ||
  193. wiz->serviceName == "Nimo TV") {
  194. servers.resize(1);
  195. } else if (wiz->service == AutoConfig::Service::Twitch &&
  196. wiz->twitchAuto) {
  197. /* if using Twitch and "Auto" is available, test 3 closest
  198. * server */
  199. servers.erase(servers.begin() + 1);
  200. servers.resize(3);
  201. } else if (wiz->service == AutoConfig::Service::YouTube) {
  202. /* Only test first set of primary + backup servers */
  203. servers.resize(2);
  204. }
  205. /* -----------------------------------*/
  206. /* apply service settings */
  207. obs_service_update(service, service_settings);
  208. obs_service_apply_encoder_settings(service, vencoder_settings,
  209. aencoder_settings);
  210. /* -----------------------------------*/
  211. /* create output */
  212. const char *output_type = obs_service_get_output_type(service);
  213. if (!output_type)
  214. output_type = "rtmp_output";
  215. OBSOutputAutoRelease output =
  216. obs_output_create(output_type, "test_stream", nullptr, nullptr);
  217. obs_output_update(output, output_settings);
  218. const char *audio_codec = obs_output_get_supported_audio_codecs(output);
  219. if (strcmp(audio_codec, "aac") != 0) {
  220. const char *id = FindAudioEncoderFromCodec(audio_codec);
  221. aencoder = obs_audio_encoder_create(id, "test_audio", nullptr,
  222. 0, nullptr);
  223. }
  224. /* -----------------------------------*/
  225. /* connect encoders/services/outputs */
  226. obs_encoder_update(vencoder, vencoder_settings);
  227. obs_encoder_update(aencoder, aencoder_settings);
  228. obs_encoder_set_video(vencoder, obs_get_video());
  229. obs_encoder_set_audio(aencoder, obs_get_audio());
  230. obs_output_set_video_encoder(output, vencoder);
  231. obs_output_set_audio_encoder(output, aencoder, 0);
  232. obs_output_set_reconnect_settings(output, 0, 0);
  233. obs_output_set_service(output, service);
  234. /* -----------------------------------*/
  235. /* connect signals */
  236. auto on_started = [&]() {
  237. unique_lock<mutex> lock(m);
  238. connected = true;
  239. stopped = false;
  240. cv.notify_one();
  241. };
  242. auto on_stopped = [&]() {
  243. unique_lock<mutex> lock(m);
  244. connected = false;
  245. stopped = true;
  246. cv.notify_one();
  247. };
  248. using on_started_t = decltype(on_started);
  249. using on_stopped_t = decltype(on_stopped);
  250. auto pre_on_started = [](void *data, calldata_t *) {
  251. on_started_t &on_started =
  252. *reinterpret_cast<on_started_t *>(data);
  253. on_started();
  254. };
  255. auto pre_on_stopped = [](void *data, calldata_t *) {
  256. on_stopped_t &on_stopped =
  257. *reinterpret_cast<on_stopped_t *>(data);
  258. on_stopped();
  259. };
  260. signal_handler *sh = obs_output_get_signal_handler(output);
  261. signal_handler_connect(sh, "start", pre_on_started, &on_started);
  262. signal_handler_connect(sh, "stop", pre_on_stopped, &on_stopped);
  263. /* -----------------------------------*/
  264. /* test servers */
  265. bool success = false;
  266. for (size_t i = 0; i < servers.size(); i++) {
  267. auto &server = servers[i];
  268. connected = false;
  269. stopped = false;
  270. int per = int((i + 1) * 100 / servers.size());
  271. QMetaObject::invokeMethod(this, "Progress", Q_ARG(int, per));
  272. QMetaObject::invokeMethod(
  273. this, "UpdateMessage",
  274. Q_ARG(QString, QTStr(TEST_BW_CONNECTING)
  275. .arg(server.name.c_str())));
  276. obs_data_set_string(service_settings, "server",
  277. server.address.c_str());
  278. obs_service_update(service, service_settings);
  279. if (!obs_output_start(output))
  280. continue;
  281. unique_lock<mutex> ul(m);
  282. if (cancel) {
  283. ul.unlock();
  284. obs_output_force_stop(output);
  285. return;
  286. }
  287. if (!stopped && !connected)
  288. cv.wait(ul);
  289. if (cancel) {
  290. ul.unlock();
  291. obs_output_force_stop(output);
  292. return;
  293. }
  294. if (!connected)
  295. continue;
  296. QMetaObject::invokeMethod(
  297. this, "UpdateMessage",
  298. Q_ARG(QString,
  299. QTStr(TEST_BW_SERVER).arg(server.name.c_str())));
  300. /* ignore first 2.5 seconds due to possible buffering skewing
  301. * the result */
  302. cv.wait_for(ul, chrono::milliseconds(2500));
  303. if (stopped)
  304. continue;
  305. if (cancel) {
  306. ul.unlock();
  307. obs_output_force_stop(output);
  308. return;
  309. }
  310. /* continue test */
  311. int start_bytes = (int)obs_output_get_total_bytes(output);
  312. uint64_t t_start = os_gettime_ns();
  313. cv.wait_for(ul, chrono::seconds(10));
  314. if (stopped)
  315. continue;
  316. if (cancel) {
  317. ul.unlock();
  318. obs_output_force_stop(output);
  319. return;
  320. }
  321. obs_output_stop(output);
  322. cv.wait(ul);
  323. uint64_t total_time = os_gettime_ns() - t_start;
  324. if (total_time == 0)
  325. total_time = 1;
  326. int total_bytes =
  327. (int)obs_output_get_total_bytes(output) - start_bytes;
  328. uint64_t bitrate = util_mul_div64(
  329. total_bytes, 8ULL * 1000000000ULL / 1000ULL,
  330. total_time);
  331. if (obs_output_get_frames_dropped(output) ||
  332. (int)bitrate < (wiz->startingBitrate * 75 / 100)) {
  333. server.bitrate = (int)bitrate * 70 / 100;
  334. } else {
  335. server.bitrate = wiz->startingBitrate;
  336. }
  337. server.ms = obs_output_get_connect_time_ms(output);
  338. success = true;
  339. }
  340. if (!success) {
  341. QMetaObject::invokeMethod(this, "Failure",
  342. Q_ARG(QString,
  343. QTStr(TEST_BW_CONNECT_FAIL)));
  344. return;
  345. }
  346. int bestBitrate = 0;
  347. int bestMS = 0x7FFFFFFF;
  348. string bestServer;
  349. string bestServerName;
  350. for (auto &server : servers) {
  351. bool close = abs(server.bitrate - bestBitrate) < 400;
  352. if ((!close && server.bitrate > bestBitrate) ||
  353. (close && server.ms < bestMS)) {
  354. bestServer = server.address;
  355. bestServerName = server.name;
  356. bestBitrate = server.bitrate;
  357. bestMS = server.ms;
  358. }
  359. }
  360. wiz->server = std::move(bestServer);
  361. wiz->serverName = std::move(bestServerName);
  362. wiz->idealBitrate = bestBitrate;
  363. QMetaObject::invokeMethod(this, "NextStage");
  364. }
  365. /* this is used to estimate the lower bitrate limit for a given
  366. * resolution/fps. yes, it is a totally arbitrary equation that gets
  367. * the closest to the expected values */
  368. static long double EstimateBitrateVal(int cx, int cy, int fps_num, int fps_den)
  369. {
  370. long fps = (long double)fps_num / (long double)fps_den;
  371. long double areaVal = pow((long double)(cx * cy), 0.85l);
  372. return areaVal * sqrt(pow(fps, 1.1l));
  373. }
  374. static long double EstimateMinBitrate(int cx, int cy, int fps_num, int fps_den)
  375. {
  376. long double val = EstimateBitrateVal(1920, 1080, 60, 1) / 5800.0l;
  377. return EstimateBitrateVal(cx, cy, fps_num, fps_den) / val;
  378. }
  379. static long double EstimateUpperBitrate(int cx, int cy, int fps_num,
  380. int fps_den)
  381. {
  382. long double val = EstimateBitrateVal(1280, 720, 30, 1) / 3000.0l;
  383. return EstimateBitrateVal(cx, cy, fps_num, fps_den) / val;
  384. }
  385. struct Result {
  386. int cx;
  387. int cy;
  388. int fps_num;
  389. int fps_den;
  390. inline Result(int cx_, int cy_, int fps_num_, int fps_den_)
  391. : cx(cx_), cy(cy_), fps_num(fps_num_), fps_den(fps_den_)
  392. {
  393. }
  394. };
  395. static void CalcBaseRes(int &baseCX, int &baseCY)
  396. {
  397. const int maxBaseArea = 1920 * 1200;
  398. const int clipResArea = 1920 * 1080;
  399. /* if base resolution unusually high, recalculate to a more reasonable
  400. * value to start the downscaling at, based upon 1920x1080's area.
  401. *
  402. * for 16:9 resolutions this will always change the starting value to
  403. * 1920x1080 */
  404. if ((baseCX * baseCY) > maxBaseArea) {
  405. long double xyAspect =
  406. (long double)baseCX / (long double)baseCY;
  407. baseCY = (int)sqrt((long double)clipResArea / xyAspect);
  408. baseCX = (int)((long double)baseCY * xyAspect);
  409. }
  410. }
  411. bool AutoConfigTestPage::TestSoftwareEncoding()
  412. {
  413. TestMode testMode;
  414. QMetaObject::invokeMethod(this, "UpdateMessage",
  415. Q_ARG(QString, QStringLiteral("")));
  416. /* -----------------------------------*/
  417. /* create obs objects */
  418. OBSEncoderAutoRelease vencoder = obs_video_encoder_create(
  419. "obs_x264", "test_x264", nullptr, nullptr);
  420. OBSEncoderAutoRelease aencoder = obs_audio_encoder_create(
  421. "ffmpeg_aac", "test_aac", nullptr, 0, nullptr);
  422. OBSOutputAutoRelease output =
  423. obs_output_create("null_output", "null", nullptr, nullptr);
  424. /* -----------------------------------*/
  425. /* configure settings */
  426. OBSDataAutoRelease aencoder_settings = obs_data_create();
  427. OBSDataAutoRelease vencoder_settings = obs_data_create();
  428. obs_data_set_int(aencoder_settings, "bitrate", 32);
  429. if (wiz->type != AutoConfig::Type::Recording) {
  430. obs_data_set_int(vencoder_settings, "keyint_sec", 2);
  431. obs_data_set_int(vencoder_settings, "bitrate",
  432. wiz->idealBitrate);
  433. obs_data_set_string(vencoder_settings, "rate_control", "CBR");
  434. obs_data_set_string(vencoder_settings, "profile", "main");
  435. obs_data_set_string(vencoder_settings, "preset", "veryfast");
  436. } else {
  437. obs_data_set_int(vencoder_settings, "crf", 20);
  438. obs_data_set_string(vencoder_settings, "rate_control", "CRF");
  439. obs_data_set_string(vencoder_settings, "profile", "high");
  440. obs_data_set_string(vencoder_settings, "preset", "veryfast");
  441. }
  442. /* -----------------------------------*/
  443. /* apply settings */
  444. obs_encoder_update(vencoder, vencoder_settings);
  445. obs_encoder_update(aencoder, aencoder_settings);
  446. /* -----------------------------------*/
  447. /* connect encoders/services/outputs */
  448. obs_output_set_video_encoder(output, vencoder);
  449. obs_output_set_audio_encoder(output, aencoder, 0);
  450. /* -----------------------------------*/
  451. /* connect signals */
  452. auto on_stopped = [&]() {
  453. unique_lock<mutex> lock(m);
  454. cv.notify_one();
  455. };
  456. using on_stopped_t = decltype(on_stopped);
  457. auto pre_on_stopped = [](void *data, calldata_t *) {
  458. on_stopped_t &on_stopped =
  459. *reinterpret_cast<on_stopped_t *>(data);
  460. on_stopped();
  461. };
  462. signal_handler *sh = obs_output_get_signal_handler(output);
  463. signal_handler_connect(sh, "deactivate", pre_on_stopped, &on_stopped);
  464. /* -----------------------------------*/
  465. /* calculate starting resolution */
  466. int baseCX = wiz->baseResolutionCX;
  467. int baseCY = wiz->baseResolutionCY;
  468. CalcBaseRes(baseCX, baseCY);
  469. /* -----------------------------------*/
  470. /* calculate starting test rates */
  471. int pcores = os_get_physical_cores();
  472. int lcores = os_get_logical_cores();
  473. int maxDataRate;
  474. if (lcores > 8 || pcores > 4) {
  475. /* superb */
  476. maxDataRate = 1920 * 1200 * 60 + 1000;
  477. } else if (lcores > 4 && pcores == 4) {
  478. /* great */
  479. maxDataRate = 1920 * 1080 * 60 + 1000;
  480. } else if (pcores == 4) {
  481. /* okay */
  482. maxDataRate = 1920 * 1080 * 30 + 1000;
  483. } else {
  484. /* toaster */
  485. maxDataRate = 960 * 540 * 30 + 1000;
  486. }
  487. /* -----------------------------------*/
  488. /* perform tests */
  489. vector<Result> results;
  490. int i = 0;
  491. int count = 1;
  492. auto testRes = [&](int cy, int fps_num, int fps_den, bool force) {
  493. int per = ++i * 100 / count;
  494. QMetaObject::invokeMethod(this, "Progress", Q_ARG(int, per));
  495. if (cy > baseCY)
  496. return true;
  497. /* no need for more than 3 tests max */
  498. if (results.size() >= 3)
  499. return true;
  500. if (!fps_num || !fps_den) {
  501. fps_num = wiz->specificFPSNum;
  502. fps_den = wiz->specificFPSDen;
  503. }
  504. long double fps = ((long double)fps_num / (long double)fps_den);
  505. int cx = int(((long double)baseCX / (long double)baseCY) *
  506. (long double)cy);
  507. if (!force && wiz->type != AutoConfig::Type::Recording) {
  508. int est = EstimateMinBitrate(cx, cy, fps_num, fps_den);
  509. if (est > wiz->idealBitrate)
  510. return true;
  511. }
  512. long double rate = (long double)cx * (long double)cy * fps;
  513. if (!force && rate > maxDataRate)
  514. return true;
  515. testMode.SetVideo(cx, cy, fps_num, fps_den);
  516. obs_encoder_set_video(vencoder, obs_get_video());
  517. obs_encoder_set_audio(aencoder, obs_get_audio());
  518. obs_encoder_update(vencoder, vencoder_settings);
  519. obs_output_set_media(output, obs_get_video(), obs_get_audio());
  520. QString cxStr = QString::number(cx);
  521. QString cyStr = QString::number(cy);
  522. QString fpsStr = (fps_den > 1) ? QString::number(fps, 'f', 2)
  523. : QString::number(fps, 'g', 2);
  524. QMetaObject::invokeMethod(
  525. this, "UpdateMessage",
  526. Q_ARG(QString,
  527. QTStr(TEST_RES_VAL).arg(cxStr, cyStr, fpsStr)));
  528. unique_lock<mutex> ul(m);
  529. if (cancel)
  530. return false;
  531. if (!obs_output_start(output)) {
  532. QMetaObject::invokeMethod(this, "Failure",
  533. Q_ARG(QString,
  534. QTStr(TEST_RES_FAIL)));
  535. return false;
  536. }
  537. cv.wait_for(ul, chrono::seconds(5));
  538. obs_output_stop(output);
  539. cv.wait(ul);
  540. int skipped =
  541. (int)video_output_get_skipped_frames(obs_get_video());
  542. if (force || skipped <= 10)
  543. results.emplace_back(cx, cy, fps_num, fps_den);
  544. return !cancel;
  545. };
  546. if (wiz->specificFPSNum && wiz->specificFPSDen) {
  547. count = 7;
  548. if (!testRes(2160, 0, 0, false))
  549. return false;
  550. if (!testRes(1440, 0, 0, false))
  551. return false;
  552. if (!testRes(1080, 0, 0, false))
  553. return false;
  554. if (!testRes(720, 0, 0, false))
  555. return false;
  556. if (!testRes(480, 0, 0, false))
  557. return false;
  558. if (!testRes(360, 0, 0, false))
  559. return false;
  560. if (!testRes(240, 0, 0, true))
  561. return false;
  562. } else {
  563. count = 14;
  564. if (!testRes(2160, 60, 1, false))
  565. return false;
  566. if (!testRes(2160, 30, 1, false))
  567. return false;
  568. if (!testRes(1440, 60, 1, false))
  569. return false;
  570. if (!testRes(1440, 30, 1, false))
  571. return false;
  572. if (!testRes(1080, 60, 1, false))
  573. return false;
  574. if (!testRes(1080, 30, 1, false))
  575. return false;
  576. if (!testRes(720, 60, 1, false))
  577. return false;
  578. if (!testRes(720, 30, 1, false))
  579. return false;
  580. if (!testRes(480, 60, 1, false))
  581. return false;
  582. if (!testRes(480, 30, 1, false))
  583. return false;
  584. if (!testRes(360, 60, 1, false))
  585. return false;
  586. if (!testRes(360, 30, 1, false))
  587. return false;
  588. if (!testRes(240, 60, 1, false))
  589. return false;
  590. if (!testRes(240, 30, 1, true))
  591. return false;
  592. }
  593. /* -----------------------------------*/
  594. /* find preferred settings */
  595. int minArea = 960 * 540 + 1000;
  596. if (!wiz->specificFPSNum && wiz->preferHighFPS && results.size() > 1) {
  597. Result &result1 = results[0];
  598. Result &result2 = results[1];
  599. if (result1.fps_num == 30 && result2.fps_num == 60) {
  600. int nextArea = result2.cx * result2.cy;
  601. if (nextArea >= minArea)
  602. results.erase(results.begin());
  603. }
  604. }
  605. Result result = results.front();
  606. wiz->idealResolutionCX = result.cx;
  607. wiz->idealResolutionCY = result.cy;
  608. wiz->idealFPSNum = result.fps_num;
  609. wiz->idealFPSDen = result.fps_den;
  610. long double fUpperBitrate = EstimateUpperBitrate(
  611. result.cx, result.cy, result.fps_num, result.fps_den);
  612. int upperBitrate = int(floor(fUpperBitrate / 50.0l) * 50.0l);
  613. if (wiz->streamingEncoder != AutoConfig::Encoder::x264) {
  614. upperBitrate *= 114;
  615. upperBitrate /= 100;
  616. }
  617. if (wiz->idealBitrate > upperBitrate)
  618. wiz->idealBitrate = upperBitrate;
  619. softwareTested = true;
  620. return true;
  621. }
  622. void AutoConfigTestPage::FindIdealHardwareResolution()
  623. {
  624. int baseCX = wiz->baseResolutionCX;
  625. int baseCY = wiz->baseResolutionCY;
  626. CalcBaseRes(baseCX, baseCY);
  627. vector<Result> results;
  628. int pcores = os_get_physical_cores();
  629. int maxDataRate;
  630. if (pcores >= 4) {
  631. maxDataRate = 1920 * 1200 * 60 + 1000;
  632. } else {
  633. maxDataRate = 1280 * 720 * 30 + 1000;
  634. }
  635. auto testRes = [&](int cy, int fps_num, int fps_den, bool force) {
  636. if (cy > baseCY)
  637. return;
  638. if (results.size() >= 3)
  639. return;
  640. if (!fps_num || !fps_den) {
  641. fps_num = wiz->specificFPSNum;
  642. fps_den = wiz->specificFPSDen;
  643. }
  644. long double fps = ((long double)fps_num / (long double)fps_den);
  645. int cx = int(((long double)baseCX / (long double)baseCY) *
  646. (long double)cy);
  647. long double rate = (long double)cx * (long double)cy * fps;
  648. if (!force && rate > maxDataRate)
  649. return;
  650. AutoConfig::Encoder encType = wiz->streamingEncoder;
  651. bool nvenc = encType == AutoConfig::Encoder::NVENC;
  652. int minBitrate = EstimateMinBitrate(cx, cy, fps_num, fps_den);
  653. /* most hardware encoders don't have a good quality to bitrate
  654. * ratio, so increase the minimum bitrate estimate for them.
  655. * NVENC currently is the exception because of the improvements
  656. * its made to its quality in recent generations. */
  657. if (!nvenc)
  658. minBitrate = minBitrate * 114 / 100;
  659. if (wiz->type == AutoConfig::Type::Recording)
  660. force = true;
  661. if (force || wiz->idealBitrate >= minBitrate)
  662. results.emplace_back(cx, cy, fps_num, fps_den);
  663. };
  664. if (wiz->specificFPSNum && wiz->specificFPSDen) {
  665. testRes(2160, 0, 0, false);
  666. testRes(1440, 0, 0, false);
  667. testRes(1080, 0, 0, false);
  668. testRes(720, 0, 0, false);
  669. testRes(480, 0, 0, false);
  670. testRes(360, 0, 0, false);
  671. testRes(240, 0, 0, true);
  672. } else {
  673. testRes(2160, 60, 1, false);
  674. testRes(2160, 30, 1, false);
  675. testRes(1440, 60, 1, false);
  676. testRes(1440, 30, 1, false);
  677. testRes(1080, 60, 1, false);
  678. testRes(1080, 30, 1, false);
  679. testRes(720, 60, 1, false);
  680. testRes(720, 30, 1, false);
  681. testRes(480, 60, 1, false);
  682. testRes(480, 30, 1, false);
  683. testRes(360, 60, 1, false);
  684. testRes(360, 30, 1, false);
  685. testRes(240, 60, 1, false);
  686. testRes(240, 30, 1, true);
  687. }
  688. int minArea = 960 * 540 + 1000;
  689. if (!wiz->specificFPSNum && wiz->preferHighFPS && results.size() > 1) {
  690. Result &result1 = results[0];
  691. Result &result2 = results[1];
  692. if (result1.fps_num == 30 && result2.fps_num == 60) {
  693. int nextArea = result2.cx * result2.cy;
  694. if (nextArea >= minArea)
  695. results.erase(results.begin());
  696. }
  697. }
  698. Result result = results.front();
  699. wiz->idealResolutionCX = result.cx;
  700. wiz->idealResolutionCY = result.cy;
  701. wiz->idealFPSNum = result.fps_num;
  702. wiz->idealFPSDen = result.fps_den;
  703. }
  704. void AutoConfigTestPage::TestStreamEncoderThread()
  705. {
  706. bool preferHardware = wiz->preferHardware;
  707. if (!softwareTested) {
  708. if (!preferHardware || !wiz->hardwareEncodingAvailable) {
  709. if (!TestSoftwareEncoding()) {
  710. return;
  711. }
  712. }
  713. }
  714. if (!softwareTested) {
  715. if (wiz->nvencAvailable)
  716. wiz->streamingEncoder = AutoConfig::Encoder::NVENC;
  717. else if (wiz->qsvAvailable)
  718. wiz->streamingEncoder = AutoConfig::Encoder::QSV;
  719. else
  720. wiz->streamingEncoder = AutoConfig::Encoder::AMD;
  721. } else {
  722. wiz->streamingEncoder = AutoConfig::Encoder::x264;
  723. }
  724. if (preferHardware && !softwareTested && wiz->hardwareEncodingAvailable)
  725. FindIdealHardwareResolution();
  726. QMetaObject::invokeMethod(this, "NextStage");
  727. }
  728. void AutoConfigTestPage::TestRecordingEncoderThread()
  729. {
  730. if (!wiz->hardwareEncodingAvailable && !softwareTested) {
  731. if (!TestSoftwareEncoding()) {
  732. return;
  733. }
  734. }
  735. if (wiz->type == AutoConfig::Type::Recording &&
  736. wiz->hardwareEncodingAvailable)
  737. FindIdealHardwareResolution();
  738. wiz->recordingQuality = AutoConfig::Quality::High;
  739. bool recordingOnly = wiz->type == AutoConfig::Type::Recording;
  740. if (wiz->hardwareEncodingAvailable) {
  741. if (wiz->nvencAvailable)
  742. wiz->recordingEncoder = AutoConfig::Encoder::NVENC;
  743. else if (wiz->qsvAvailable)
  744. wiz->recordingEncoder = AutoConfig::Encoder::QSV;
  745. else
  746. wiz->recordingEncoder = AutoConfig::Encoder::AMD;
  747. } else {
  748. wiz->recordingEncoder = AutoConfig::Encoder::x264;
  749. }
  750. if (wiz->recordingEncoder != AutoConfig::Encoder::NVENC) {
  751. if (!recordingOnly) {
  752. wiz->recordingEncoder = AutoConfig::Encoder::Stream;
  753. wiz->recordingQuality = AutoConfig::Quality::Stream;
  754. }
  755. }
  756. QMetaObject::invokeMethod(this, "NextStage");
  757. }
  758. #define ENCODER_TEXT(x) "Basic.Settings.Output.Simple.Encoder." x
  759. #define ENCODER_SOFTWARE ENCODER_TEXT("Software")
  760. #define ENCODER_NVENC ENCODER_TEXT("Hardware.NVENC")
  761. #define ENCODER_QSV ENCODER_TEXT("Hardware.QSV")
  762. #define ENCODER_AMD ENCODER_TEXT("Hardware.AMD")
  763. #define QUALITY_SAME "Basic.Settings.Output.Simple.RecordingQuality.Stream"
  764. #define QUALITY_HIGH "Basic.Settings.Output.Simple.RecordingQuality.Small"
  765. void set_closest_res(int &cx, int &cy, struct obs_service_resolution *res_list,
  766. size_t count)
  767. {
  768. int best_pixel_diff = 0x7FFFFFFF;
  769. int start_cx = cx;
  770. int start_cy = cy;
  771. for (size_t i = 0; i < count; i++) {
  772. struct obs_service_resolution &res = res_list[i];
  773. int pixel_cx_diff = abs(start_cx - res.cx);
  774. int pixel_cy_diff = abs(start_cy - res.cy);
  775. int pixel_diff = pixel_cx_diff + pixel_cy_diff;
  776. if (pixel_diff < best_pixel_diff) {
  777. best_pixel_diff = pixel_diff;
  778. cx = res.cx;
  779. cy = res.cy;
  780. }
  781. }
  782. }
  783. void AutoConfigTestPage::FinalizeResults()
  784. {
  785. ui->stackedWidget->setCurrentIndex(1);
  786. setSubTitle(QTStr(SUBTITLE_COMPLETE));
  787. QFormLayout *form = results;
  788. auto encName = [](AutoConfig::Encoder enc) -> QString {
  789. switch (enc) {
  790. case AutoConfig::Encoder::x264:
  791. return QTStr(ENCODER_SOFTWARE);
  792. case AutoConfig::Encoder::NVENC:
  793. return QTStr(ENCODER_NVENC);
  794. case AutoConfig::Encoder::QSV:
  795. return QTStr(ENCODER_QSV);
  796. case AutoConfig::Encoder::AMD:
  797. return QTStr(ENCODER_AMD);
  798. case AutoConfig::Encoder::Stream:
  799. return QTStr(QUALITY_SAME);
  800. }
  801. return QTStr(ENCODER_SOFTWARE);
  802. };
  803. auto newLabel = [this](const char *str) -> QLabel * {
  804. return new QLabel(QTStr(str), this);
  805. };
  806. if (wiz->type == AutoConfig::Type::Streaming) {
  807. const char *serverType = wiz->customServer ? "rtmp_custom"
  808. : "rtmp_common";
  809. OBSServiceAutoRelease service = obs_service_create(
  810. serverType, "temp_service", nullptr, nullptr);
  811. OBSDataAutoRelease service_settings = obs_data_create();
  812. OBSDataAutoRelease vencoder_settings = obs_data_create();
  813. obs_data_set_int(vencoder_settings, "bitrate",
  814. wiz->idealBitrate);
  815. obs_data_set_string(service_settings, "service",
  816. wiz->serviceName.c_str());
  817. obs_service_update(service, service_settings);
  818. obs_service_apply_encoder_settings(service, vencoder_settings,
  819. nullptr);
  820. BPtr<obs_service_resolution> res_list;
  821. size_t res_count;
  822. int maxFPS;
  823. obs_service_get_supported_resolutions(service, &res_list,
  824. &res_count);
  825. obs_service_get_max_fps(service, &maxFPS);
  826. if (res_list) {
  827. set_closest_res(wiz->idealResolutionCX,
  828. wiz->idealResolutionCY, res_list,
  829. res_count);
  830. }
  831. if (maxFPS) {
  832. double idealFPS = (double)wiz->idealFPSNum /
  833. (double)wiz->idealFPSDen;
  834. if (idealFPS > (double)maxFPS) {
  835. wiz->idealFPSNum = maxFPS;
  836. wiz->idealFPSDen = 1;
  837. }
  838. }
  839. wiz->idealBitrate =
  840. (int)obs_data_get_int(vencoder_settings, "bitrate");
  841. if (!wiz->customServer)
  842. form->addRow(
  843. newLabel("Basic.AutoConfig.StreamPage.Service"),
  844. new QLabel(wiz->serviceName.c_str(),
  845. ui->finishPage));
  846. form->addRow(newLabel("Basic.AutoConfig.StreamPage.Server"),
  847. new QLabel(wiz->serverName.c_str(),
  848. ui->finishPage));
  849. form->addRow(newLabel("Basic.Settings.Output.VideoBitrate"),
  850. new QLabel(QString::number(wiz->idealBitrate),
  851. ui->finishPage));
  852. form->addRow(newLabel(TEST_RESULT_SE),
  853. new QLabel(encName(wiz->streamingEncoder),
  854. ui->finishPage));
  855. }
  856. QString baseRes =
  857. QString("%1x%2").arg(QString::number(wiz->baseResolutionCX),
  858. QString::number(wiz->baseResolutionCY));
  859. QString scaleRes =
  860. QString("%1x%2").arg(QString::number(wiz->idealResolutionCX),
  861. QString::number(wiz->idealResolutionCY));
  862. if (wiz->recordingEncoder != AutoConfig::Encoder::Stream ||
  863. wiz->recordingQuality != AutoConfig::Quality::Stream)
  864. form->addRow(newLabel(TEST_RESULT_RE),
  865. new QLabel(encName(wiz->recordingEncoder),
  866. ui->finishPage));
  867. QString recQuality;
  868. switch (wiz->recordingQuality) {
  869. case AutoConfig::Quality::High:
  870. recQuality = QTStr(QUALITY_HIGH);
  871. break;
  872. case AutoConfig::Quality::Stream:
  873. recQuality = QTStr(QUALITY_SAME);
  874. break;
  875. }
  876. form->addRow(newLabel("Basic.Settings.Output.Simple.RecordingQuality"),
  877. new QLabel(recQuality, ui->finishPage));
  878. long double fps =
  879. (long double)wiz->idealFPSNum / (long double)wiz->idealFPSDen;
  880. QString fpsStr = (wiz->idealFPSDen > 1) ? QString::number(fps, 'f', 2)
  881. : QString::number(fps, 'g', 2);
  882. form->addRow(newLabel("Basic.Settings.Video.BaseResolution"),
  883. new QLabel(baseRes, ui->finishPage));
  884. form->addRow(newLabel("Basic.Settings.Video.ScaledResolution"),
  885. new QLabel(scaleRes, ui->finishPage));
  886. form->addRow(newLabel("Basic.Settings.Video.FPS"),
  887. new QLabel(fpsStr, ui->finishPage));
  888. }
  889. #define STARTING_SEPARATOR \
  890. "\n==== Auto-config wizard testing commencing ======\n"
  891. #define STOPPING_SEPARATOR \
  892. "\n==== Auto-config wizard testing stopping ========\n"
  893. void AutoConfigTestPage::NextStage()
  894. {
  895. if (testThread.joinable())
  896. testThread.join();
  897. if (cancel)
  898. return;
  899. ui->subProgressLabel->setText(QString());
  900. /* make it skip to bandwidth stage if only set to config recording */
  901. if (stage == Stage::Starting) {
  902. if (!started) {
  903. blog(LOG_INFO, STARTING_SEPARATOR);
  904. started = true;
  905. }
  906. if (wiz->type != AutoConfig::Type::Streaming) {
  907. stage = Stage::StreamEncoder;
  908. } else if (!wiz->bandwidthTest) {
  909. stage = Stage::BandwidthTest;
  910. }
  911. }
  912. if (stage == Stage::Starting) {
  913. stage = Stage::BandwidthTest;
  914. StartBandwidthStage();
  915. } else if (stage == Stage::BandwidthTest) {
  916. stage = Stage::StreamEncoder;
  917. StartStreamEncoderStage();
  918. } else if (stage == Stage::StreamEncoder) {
  919. stage = Stage::RecordingEncoder;
  920. StartRecordingEncoderStage();
  921. } else {
  922. stage = Stage::Finished;
  923. FinalizeResults();
  924. emit completeChanged();
  925. }
  926. }
  927. void AutoConfigTestPage::UpdateMessage(QString message)
  928. {
  929. ui->subProgressLabel->setText(message);
  930. }
  931. void AutoConfigTestPage::Failure(QString message)
  932. {
  933. ui->errorLabel->setText(message);
  934. ui->stackedWidget->setCurrentIndex(2);
  935. }
  936. void AutoConfigTestPage::Progress(int percentage)
  937. {
  938. ui->progressBar->setValue(percentage);
  939. }
  940. AutoConfigTestPage::AutoConfigTestPage(QWidget *parent)
  941. : QWizardPage(parent), ui(new Ui_AutoConfigTestPage)
  942. {
  943. ui->setupUi(this);
  944. setTitle(QTStr("Basic.AutoConfig.TestPage"));
  945. setSubTitle(QTStr(SUBTITLE_TESTING));
  946. setCommitPage(true);
  947. }
  948. AutoConfigTestPage::~AutoConfigTestPage()
  949. {
  950. if (testThread.joinable()) {
  951. {
  952. unique_lock<mutex> ul(m);
  953. cancel = true;
  954. cv.notify_one();
  955. }
  956. testThread.join();
  957. }
  958. if (started)
  959. blog(LOG_INFO, STOPPING_SEPARATOR);
  960. }
  961. void AutoConfigTestPage::initializePage()
  962. {
  963. if (wiz->type == AutoConfig::Type::VirtualCam) {
  964. wiz->idealResolutionCX = wiz->baseResolutionCX;
  965. wiz->idealResolutionCY = wiz->baseResolutionCY;
  966. wiz->idealFPSNum = 30;
  967. wiz->idealFPSDen = 1;
  968. stage = Stage::Finished;
  969. } else {
  970. stage = Stage::Starting;
  971. }
  972. setSubTitle(QTStr(SUBTITLE_TESTING));
  973. softwareTested = false;
  974. cancel = false;
  975. DeleteLayout(results);
  976. results = new QFormLayout();
  977. results->setContentsMargins(0, 0, 0, 0);
  978. ui->finishPageLayout->insertLayout(1, results);
  979. ui->stackedWidget->setCurrentIndex(0);
  980. NextStage();
  981. }
  982. void AutoConfigTestPage::cleanupPage()
  983. {
  984. if (testThread.joinable()) {
  985. {
  986. unique_lock<mutex> ul(m);
  987. cancel = true;
  988. cv.notify_one();
  989. }
  990. testThread.join();
  991. }
  992. }
  993. bool AutoConfigTestPage::isComplete() const
  994. {
  995. return stage == Stage::Finished;
  996. }
  997. int AutoConfigTestPage::nextId() const
  998. {
  999. return -1;
  1000. }