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

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