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

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