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

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