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

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