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

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