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

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