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

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