window-basic-stats.cpp 16 KB

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