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

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