window-basic-stats.cpp 15 KB

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