window-basic-stats.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. #include "obs-frontend-api/obs-frontend-api.h"
  2. #include "window-basic-stats.hpp"
  3. #include "window-basic-main.hpp"
  4. #include "platform.hpp"
  5. #include "obs-app.hpp"
  6. #include "qt-wrappers.hpp"
  7. #include <QPushButton>
  8. #include <QScrollArea>
  9. #include <QVBoxLayout>
  10. #include <QHBoxLayout>
  11. #include <QGridLayout>
  12. #include <QScreen>
  13. #include <string>
  14. #define TIMER_INTERVAL 2000
  15. #define REC_TIME_LEFT_INTERVAL 30000
  16. void OBSBasicStats::OBSFrontendEvent(enum obs_frontend_event event, void *ptr)
  17. {
  18. OBSBasicStats *stats = reinterpret_cast<OBSBasicStats *>(ptr);
  19. switch (event) {
  20. case OBS_FRONTEND_EVENT_RECORDING_STARTED:
  21. stats->StartRecTimeLeft();
  22. break;
  23. case OBS_FRONTEND_EVENT_RECORDING_STOPPED:
  24. stats->ResetRecTimeLeft();
  25. break;
  26. case OBS_FRONTEND_EVENT_EXIT:
  27. // This is only reached when the non-closable (dock) stats
  28. // window is being cleaned up. The closable stats window is
  29. // already gone by this point as it's deleted on close.
  30. obs_frontend_remove_event_callback(OBSFrontendEvent, stats);
  31. break;
  32. default:
  33. break;
  34. }
  35. }
  36. static QString MakeTimeLeftText(int hours, int minutes)
  37. {
  38. return QString::asprintf("%d %s, %d %s", hours, Str("Hours"), minutes,
  39. Str("Minutes"));
  40. }
  41. static QString MakeMissedFramesText(uint32_t total_lagged,
  42. uint32_t total_rendered, long double num)
  43. {
  44. return QString("%1 / %2 (%3%)")
  45. .arg(QString::number(total_lagged),
  46. QString::number(total_rendered),
  47. QString::number(num, 'f', 1));
  48. }
  49. OBSBasicStats::OBSBasicStats(QWidget *parent, bool closable)
  50. : QFrame(parent),
  51. cpu_info(os_cpu_usage_info_start()),
  52. timer(this),
  53. recTimeLeft(this)
  54. {
  55. QVBoxLayout *mainLayout = new QVBoxLayout();
  56. QGridLayout *topLayout = new QGridLayout();
  57. outputLayout = new QGridLayout();
  58. bitrates.reserve(REC_TIME_LEFT_INTERVAL / TIMER_INTERVAL);
  59. int row = 0;
  60. auto newStatBare = [&](QString name, QWidget *label, int col) {
  61. QLabel *typeLabel = new QLabel(name, this);
  62. topLayout->addWidget(typeLabel, row, col);
  63. topLayout->addWidget(label, row++, col + 1);
  64. };
  65. auto newStat = [&](const char *strLoc, QWidget *label, int col) {
  66. std::string str = "Basic.Stats.";
  67. str += strLoc;
  68. newStatBare(QTStr(str.c_str()), label, col);
  69. };
  70. /* --------------------------------------------- */
  71. cpuUsage = new QLabel(this);
  72. hddSpace = new QLabel(this);
  73. recordTimeLeft = new QLabel(this);
  74. memUsage = new QLabel(this);
  75. QString str = MakeTimeLeftText(99999, 59);
  76. int textWidth = recordTimeLeft->fontMetrics().boundingRect(str).width();
  77. recordTimeLeft->setMinimumWidth(textWidth);
  78. newStat("CPUUsage", cpuUsage, 0);
  79. newStat("HDDSpaceAvailable", hddSpace, 0);
  80. newStat("DiskFullIn", recordTimeLeft, 0);
  81. newStat("MemoryUsage", memUsage, 0);
  82. fps = new QLabel(this);
  83. renderTime = new QLabel(this);
  84. skippedFrames = new QLabel(this);
  85. missedFrames = new QLabel(this);
  86. str = MakeMissedFramesText(999999, 999999, 99.99);
  87. textWidth = missedFrames->fontMetrics().boundingRect(str).width();
  88. missedFrames->setMinimumWidth(textWidth);
  89. row = 0;
  90. newStatBare("FPS", fps, 2);
  91. newStat("AverageTimeToRender", renderTime, 2);
  92. newStat("MissedFrames", missedFrames, 2);
  93. newStat("SkippedFrames", skippedFrames, 2);
  94. /* --------------------------------------------- */
  95. QPushButton *closeButton = nullptr;
  96. if (closable)
  97. closeButton = new QPushButton(QTStr("Close"));
  98. QPushButton *resetButton = new QPushButton(QTStr("Reset"));
  99. QHBoxLayout *buttonLayout = new QHBoxLayout;
  100. buttonLayout->addStretch();
  101. buttonLayout->addWidget(resetButton);
  102. if (closable)
  103. buttonLayout->addWidget(closeButton);
  104. /* --------------------------------------------- */
  105. int col = 0;
  106. auto addOutputCol = [&](const char *loc) {
  107. QLabel *label = new QLabel(QTStr(loc), this);
  108. label->setStyleSheet("font-weight: bold");
  109. outputLayout->addWidget(label, 0, col++);
  110. };
  111. addOutputCol("Basic.Settings.Output");
  112. addOutputCol("Basic.Stats.Status");
  113. addOutputCol("Basic.Stats.DroppedFrames");
  114. addOutputCol("Basic.Stats.MegabytesSent");
  115. addOutputCol("Basic.Stats.Bitrate");
  116. /* --------------------------------------------- */
  117. AddOutputLabels(QTStr("Basic.Stats.Output.Stream"));
  118. AddOutputLabels(QTStr("Basic.Stats.Output.Recording"));
  119. /* --------------------------------------------- */
  120. QVBoxLayout *outputContainerLayout = new QVBoxLayout();
  121. outputContainerLayout->addLayout(outputLayout);
  122. outputContainerLayout->addStretch();
  123. QWidget *widget = new QWidget(this);
  124. widget->setLayout(outputContainerLayout);
  125. QScrollArea *scrollArea = new QScrollArea(this);
  126. scrollArea->setWidget(widget);
  127. scrollArea->setWidgetResizable(true);
  128. /* --------------------------------------------- */
  129. mainLayout->addLayout(topLayout);
  130. mainLayout->addWidget(scrollArea);
  131. mainLayout->addLayout(buttonLayout);
  132. setLayout(mainLayout);
  133. /* --------------------------------------------- */
  134. if (closable)
  135. connect(closeButton, &QPushButton::clicked,
  136. [this]() { close(); });
  137. connect(resetButton, &QPushButton::clicked, [this]() { Reset(); });
  138. delete shortcutFilter;
  139. shortcutFilter = CreateShortcutFilter();
  140. installEventFilter(shortcutFilter);
  141. resize(800, 280);
  142. setWindowTitle(QTStr("Basic.Stats"));
  143. #ifdef __APPLE__
  144. setWindowIcon(
  145. QIcon::fromTheme("obs", QIcon(":/res/images/obs_256x256.png")));
  146. #else
  147. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  148. #endif
  149. setWindowModality(Qt::NonModal);
  150. setAttribute(Qt::WA_DeleteOnClose, true);
  151. QObject::connect(&timer, &QTimer::timeout, this,
  152. &OBSBasicStats::Update);
  153. timer.setInterval(TIMER_INTERVAL);
  154. if (isVisible())
  155. timer.start();
  156. Update();
  157. QObject::connect(&recTimeLeft, &QTimer::timeout, this,
  158. &OBSBasicStats::RecordingTimeLeft);
  159. recTimeLeft.setInterval(REC_TIME_LEFT_INTERVAL);
  160. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  161. const char *geometry =
  162. config_get_string(main->Config(), "Stats", "geometry");
  163. if (geometry != NULL) {
  164. QByteArray byteArray =
  165. QByteArray::fromBase64(QByteArray(geometry));
  166. restoreGeometry(byteArray);
  167. QRect windowGeometry = normalGeometry();
  168. if (!WindowPositionValid(windowGeometry)) {
  169. QRect rect =
  170. QGuiApplication::primaryScreen()->geometry();
  171. setGeometry(QStyle::alignedRect(Qt::LeftToRight,
  172. Qt::AlignCenter, size(),
  173. rect));
  174. }
  175. }
  176. obs_frontend_add_event_callback(OBSFrontendEvent, this);
  177. if (obs_frontend_recording_active())
  178. StartRecTimeLeft();
  179. }
  180. void OBSBasicStats::closeEvent(QCloseEvent *event)
  181. {
  182. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  183. if (isVisible()) {
  184. config_set_string(main->Config(), "Stats", "geometry",
  185. saveGeometry().toBase64().constData());
  186. config_save_safe(main->Config(), "tmp", nullptr);
  187. }
  188. // This code is only reached when the non-dockable stats window is
  189. // manually closed or OBS is exiting.
  190. obs_frontend_remove_event_callback(OBSFrontendEvent, this);
  191. QWidget::closeEvent(event);
  192. }
  193. OBSBasicStats::~OBSBasicStats()
  194. {
  195. delete shortcutFilter;
  196. os_cpu_usage_info_destroy(cpu_info);
  197. }
  198. void OBSBasicStats::AddOutputLabels(QString name)
  199. {
  200. OutputLabels ol;
  201. ol.name = new QLabel(name, this);
  202. ol.status = new QLabel(this);
  203. ol.droppedFrames = new QLabel(this);
  204. ol.megabytesSent = new QLabel(this);
  205. ol.bitrate = new QLabel(this);
  206. int col = 0;
  207. int row = outputLabels.size() + 1;
  208. outputLayout->addWidget(ol.name, row, col++);
  209. outputLayout->addWidget(ol.status, row, col++);
  210. outputLayout->addWidget(ol.droppedFrames, row, col++);
  211. outputLayout->addWidget(ol.megabytesSent, row, col++);
  212. outputLayout->addWidget(ol.bitrate, row, col++);
  213. outputLabels.push_back(ol);
  214. }
  215. static uint32_t first_encoded = 0xFFFFFFFF;
  216. static uint32_t first_skipped = 0xFFFFFFFF;
  217. static uint32_t first_rendered = 0xFFFFFFFF;
  218. static uint32_t first_lagged = 0xFFFFFFFF;
  219. void OBSBasicStats::InitializeValues()
  220. {
  221. video_t *video = obs_get_video();
  222. first_encoded = video_output_get_total_frames(video);
  223. first_skipped = video_output_get_skipped_frames(video);
  224. first_rendered = obs_get_total_frames();
  225. first_lagged = obs_get_lagged_frames();
  226. }
  227. void OBSBasicStats::Update()
  228. {
  229. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  230. /* TODO: Un-hardcode */
  231. struct obs_video_info ovi = {};
  232. obs_get_video_info(&ovi);
  233. OBSOutputAutoRelease strOutput = obs_frontend_get_streaming_output();
  234. OBSOutputAutoRelease recOutput = obs_frontend_get_recording_output();
  235. if (!strOutput && !recOutput)
  236. return;
  237. /* ------------------------------------------- */
  238. /* general usage */
  239. double curFPS = obs_get_active_fps();
  240. double obsFPS = (double)ovi.fps_num / (double)ovi.fps_den;
  241. QString str = QString::number(curFPS, 'f', 2);
  242. fps->setText(str);
  243. if (curFPS < (obsFPS * 0.8))
  244. setThemeID(fps, "error");
  245. else if (curFPS < (obsFPS * 0.95))
  246. setThemeID(fps, "warning");
  247. else
  248. setThemeID(fps, "");
  249. /* ------------------ */
  250. double usage = os_cpu_usage_info_query(cpu_info);
  251. str = QString::number(usage, 'g', 2) + QStringLiteral("%");
  252. cpuUsage->setText(str);
  253. /* ------------------ */
  254. const char *path = main->GetCurrentOutputPath();
  255. #define MBYTE (1024ULL * 1024ULL)
  256. #define GBYTE (1024ULL * 1024ULL * 1024ULL)
  257. #define TBYTE (1024ULL * 1024ULL * 1024ULL * 1024ULL)
  258. num_bytes = os_get_free_disk_space(path);
  259. QString abrv = QStringLiteral(" MB");
  260. long double num;
  261. num = (long double)num_bytes / (1024.0l * 1024.0l);
  262. if (num_bytes > TBYTE) {
  263. num /= 1024.0l * 1024.0l;
  264. abrv = QStringLiteral(" TB");
  265. } else if (num_bytes > GBYTE) {
  266. num /= 1024.0l;
  267. abrv = QStringLiteral(" GB");
  268. }
  269. str = QString::number(num, 'f', 1) + abrv;
  270. hddSpace->setText(str);
  271. if (num_bytes < GBYTE)
  272. setThemeID(hddSpace, "error");
  273. else if (num_bytes < (5 * GBYTE))
  274. setThemeID(hddSpace, "warning");
  275. else
  276. setThemeID(hddSpace, "");
  277. /* ------------------ */
  278. num = (long double)os_get_proc_resident_size() / (1024.0l * 1024.0l);
  279. str = QString::number(num, 'f', 1) + QStringLiteral(" MB");
  280. memUsage->setText(str);
  281. /* ------------------ */
  282. num = (long double)obs_get_average_frame_time_ns() / 1000000.0l;
  283. str = QString::number(num, 'f', 1) + QStringLiteral(" ms");
  284. renderTime->setText(str);
  285. long double fpsFrameTime =
  286. (long double)ovi.fps_den * 1000.0l / (long double)ovi.fps_num;
  287. if (num > fpsFrameTime)
  288. setThemeID(renderTime, "error");
  289. else if (num > fpsFrameTime * 0.75l)
  290. setThemeID(renderTime, "warning");
  291. else
  292. setThemeID(renderTime, "");
  293. /* ------------------ */
  294. video_t *video = obs_get_video();
  295. uint32_t total_encoded = video_output_get_total_frames(video);
  296. uint32_t total_skipped = video_output_get_skipped_frames(video);
  297. if (total_encoded < first_encoded || total_skipped < first_skipped) {
  298. first_encoded = total_encoded;
  299. first_skipped = total_skipped;
  300. }
  301. total_encoded -= first_encoded;
  302. total_skipped -= first_skipped;
  303. num = total_encoded
  304. ? (long double)total_skipped / (long double)total_encoded
  305. : 0.0l;
  306. num *= 100.0l;
  307. str = QString("%1 / %2 (%3%)")
  308. .arg(QString::number(total_skipped),
  309. QString::number(total_encoded),
  310. QString::number(num, 'f', 1));
  311. skippedFrames->setText(str);
  312. if (num > 5.0l)
  313. setThemeID(skippedFrames, "error");
  314. else if (num > 1.0l)
  315. setThemeID(skippedFrames, "warning");
  316. else
  317. setThemeID(skippedFrames, "");
  318. /* ------------------ */
  319. uint32_t total_rendered = obs_get_total_frames();
  320. uint32_t total_lagged = obs_get_lagged_frames();
  321. if (total_rendered < first_rendered || total_lagged < first_lagged) {
  322. first_rendered = total_rendered;
  323. first_lagged = total_lagged;
  324. }
  325. total_rendered -= first_rendered;
  326. total_lagged -= first_lagged;
  327. num = total_rendered
  328. ? (long double)total_lagged / (long double)total_rendered
  329. : 0.0l;
  330. num *= 100.0l;
  331. str = MakeMissedFramesText(total_lagged, total_rendered, num);
  332. missedFrames->setText(str);
  333. if (num > 5.0l)
  334. setThemeID(missedFrames, "error");
  335. else if (num > 1.0l)
  336. setThemeID(missedFrames, "warning");
  337. else
  338. setThemeID(missedFrames, "");
  339. /* ------------------------------------------- */
  340. /* recording/streaming stats */
  341. outputLabels[0].Update(strOutput, false);
  342. outputLabels[1].Update(recOutput, true);
  343. if (obs_output_active(recOutput)) {
  344. long double kbps = outputLabels[1].kbps;
  345. bitrates.push_back(kbps);
  346. }
  347. }
  348. void OBSBasicStats::StartRecTimeLeft()
  349. {
  350. if (recTimeLeft.isActive())
  351. ResetRecTimeLeft();
  352. recordTimeLeft->setText(QTStr("Calculating"));
  353. recTimeLeft.start();
  354. }
  355. void OBSBasicStats::ResetRecTimeLeft()
  356. {
  357. if (recTimeLeft.isActive()) {
  358. bitrates.clear();
  359. recTimeLeft.stop();
  360. recordTimeLeft->setText(QTStr(""));
  361. }
  362. }
  363. void OBSBasicStats::RecordingTimeLeft()
  364. {
  365. if (bitrates.empty())
  366. return;
  367. long double averageBitrate =
  368. accumulate(bitrates.begin(), bitrates.end(), 0.0) /
  369. (long double)bitrates.size();
  370. if (averageBitrate == 0)
  371. return;
  372. long double bytesPerSec = (averageBitrate / 8.0l) * 1000.0l;
  373. long double secondsUntilFull = (long double)num_bytes / bytesPerSec;
  374. bitrates.clear();
  375. int totalMinutes = (int)secondsUntilFull / 60;
  376. int minutes = totalMinutes % 60;
  377. int hours = totalMinutes / 60;
  378. QString text = MakeTimeLeftText(hours, minutes);
  379. recordTimeLeft->setText(text);
  380. recordTimeLeft->setMinimumWidth(recordTimeLeft->width());
  381. }
  382. void OBSBasicStats::Reset()
  383. {
  384. timer.start();
  385. first_encoded = 0xFFFFFFFF;
  386. first_skipped = 0xFFFFFFFF;
  387. first_rendered = 0xFFFFFFFF;
  388. first_lagged = 0xFFFFFFFF;
  389. OBSOutputAutoRelease strOutput = obs_frontend_get_streaming_output();
  390. OBSOutputAutoRelease recOutput = obs_frontend_get_recording_output();
  391. outputLabels[0].Reset(strOutput);
  392. outputLabels[1].Reset(recOutput);
  393. Update();
  394. }
  395. void OBSBasicStats::OutputLabels::Update(obs_output_t *output, bool rec)
  396. {
  397. uint64_t totalBytes = output ? obs_output_get_total_bytes(output) : 0;
  398. uint64_t curTime = os_gettime_ns();
  399. uint64_t bytesSent = totalBytes;
  400. if (bytesSent < lastBytesSent)
  401. bytesSent = 0;
  402. if (bytesSent == 0)
  403. lastBytesSent = 0;
  404. uint64_t bitsBetween = (bytesSent - lastBytesSent) * 8;
  405. long double timePassed =
  406. (long double)(curTime - lastBytesSentTime) / 1000000000.0l;
  407. kbps = (long double)bitsBetween / timePassed / 1000.0l;
  408. if (timePassed < 0.01l)
  409. kbps = 0.0l;
  410. QString str = QTStr("Basic.Stats.Status.Inactive");
  411. QString themeID;
  412. bool active = output ? obs_output_active(output) : false;
  413. if (rec) {
  414. if (active)
  415. str = QTStr("Basic.Stats.Status.Recording");
  416. } else {
  417. if (active) {
  418. bool reconnecting =
  419. output ? obs_output_reconnecting(output)
  420. : false;
  421. if (reconnecting) {
  422. str = QTStr("Basic.Stats.Status.Reconnecting");
  423. themeID = "error";
  424. } else {
  425. str = QTStr("Basic.Stats.Status.Live");
  426. themeID = "good";
  427. }
  428. }
  429. }
  430. status->setText(str);
  431. setThemeID(status, themeID);
  432. long double num = (long double)totalBytes / (1024.0l * 1024.0l);
  433. megabytesSent->setText(
  434. QString("%1 MB").arg(QString::number(num, 'f', 1)));
  435. bitrate->setText(QString("%1 kb/s").arg(QString::number(kbps, 'f', 0)));
  436. if (!rec) {
  437. int total = output ? obs_output_get_total_frames(output) : 0;
  438. int dropped = output ? obs_output_get_frames_dropped(output)
  439. : 0;
  440. if (total < first_total || dropped < first_dropped) {
  441. first_total = 0;
  442. first_dropped = 0;
  443. }
  444. total -= first_total;
  445. dropped -= first_dropped;
  446. num = total ? (long double)dropped / (long double)total * 100.0l
  447. : 0.0l;
  448. str = QString("%1 / %2 (%3%)")
  449. .arg(QString::number(dropped),
  450. QString::number(total),
  451. QString::number(num, 'f', 1));
  452. droppedFrames->setText(str);
  453. if (num > 5.0l)
  454. setThemeID(droppedFrames, "error");
  455. else if (num > 1.0l)
  456. setThemeID(droppedFrames, "warning");
  457. else
  458. setThemeID(droppedFrames, "");
  459. }
  460. lastBytesSent = bytesSent;
  461. lastBytesSentTime = curTime;
  462. }
  463. void OBSBasicStats::OutputLabels::Reset(obs_output_t *output)
  464. {
  465. if (!output)
  466. return;
  467. first_total = obs_output_get_total_frames(output);
  468. first_dropped = obs_output_get_frames_dropped(output);
  469. }
  470. void OBSBasicStats::showEvent(QShowEvent *)
  471. {
  472. timer.start(TIMER_INTERVAL);
  473. }
  474. void OBSBasicStats::hideEvent(QHideEvent *)
  475. {
  476. timer.stop();
  477. }