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

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