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

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