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

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