window-basic-stats.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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. : QWidget(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 newPointSize = ol.status->font().pointSize();
  198. newPointSize *= 13;
  199. newPointSize /= 10;
  200. QString qss =
  201. QString("font-size: %1pt").arg(QString::number(newPointSize));
  202. ol.status->setStyleSheet(qss);
  203. int col = 0;
  204. int row = outputLabels.size() + 1;
  205. outputLayout->addWidget(ol.name, row, col++);
  206. outputLayout->addWidget(ol.status, row, col++);
  207. outputLayout->addWidget(ol.droppedFrames, row, col++);
  208. outputLayout->addWidget(ol.megabytesSent, row, col++);
  209. outputLayout->addWidget(ol.bitrate, row, col++);
  210. outputLabels.push_back(ol);
  211. }
  212. static uint32_t first_encoded = 0xFFFFFFFF;
  213. static uint32_t first_skipped = 0xFFFFFFFF;
  214. static uint32_t first_rendered = 0xFFFFFFFF;
  215. static uint32_t first_lagged = 0xFFFFFFFF;
  216. void OBSBasicStats::InitializeValues()
  217. {
  218. video_t *video = obs_get_video();
  219. first_encoded = video_output_get_total_frames(video);
  220. first_skipped = video_output_get_skipped_frames(video);
  221. first_rendered = obs_get_total_frames();
  222. first_lagged = obs_get_lagged_frames();
  223. }
  224. void OBSBasicStats::Update()
  225. {
  226. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  227. /* TODO: Un-hardcode */
  228. struct obs_video_info ovi = {};
  229. obs_get_video_info(&ovi);
  230. OBSOutputAutoRelease strOutput = obs_frontend_get_streaming_output();
  231. OBSOutputAutoRelease recOutput = obs_frontend_get_recording_output();
  232. if (!strOutput && !recOutput)
  233. return;
  234. /* ------------------------------------------- */
  235. /* general usage */
  236. double curFPS = obs_get_active_fps();
  237. double obsFPS = (double)ovi.fps_num / (double)ovi.fps_den;
  238. QString str = QString::number(curFPS, 'f', 2);
  239. fps->setText(str);
  240. if (curFPS < (obsFPS * 0.8))
  241. setThemeID(fps, "error");
  242. else if (curFPS < (obsFPS * 0.95))
  243. setThemeID(fps, "warning");
  244. else
  245. setThemeID(fps, "");
  246. /* ------------------ */
  247. double usage = os_cpu_usage_info_query(cpu_info);
  248. str = QString::number(usage, 'g', 2) + QStringLiteral("%");
  249. cpuUsage->setText(str);
  250. /* ------------------ */
  251. const char *path = main->GetCurrentOutputPath();
  252. #define MBYTE (1024ULL * 1024ULL)
  253. #define GBYTE (1024ULL * 1024ULL * 1024ULL)
  254. #define TBYTE (1024ULL * 1024ULL * 1024ULL * 1024ULL)
  255. num_bytes = os_get_free_disk_space(path);
  256. QString abrv = QStringLiteral(" MB");
  257. long double num;
  258. num = (long double)num_bytes / (1024.0l * 1024.0l);
  259. if (num_bytes > TBYTE) {
  260. num /= 1024.0l * 1024.0l;
  261. abrv = QStringLiteral(" TB");
  262. } else if (num_bytes > GBYTE) {
  263. num /= 1024.0l;
  264. abrv = QStringLiteral(" GB");
  265. }
  266. str = QString::number(num, 'f', 1) + abrv;
  267. hddSpace->setText(str);
  268. if (num_bytes < GBYTE)
  269. setThemeID(hddSpace, "error");
  270. else if (num_bytes < (5 * GBYTE))
  271. setThemeID(hddSpace, "warning");
  272. else
  273. setThemeID(hddSpace, "");
  274. /* ------------------ */
  275. num = (long double)os_get_proc_resident_size() / (1024.0l * 1024.0l);
  276. str = QString::number(num, 'f', 1) + QStringLiteral(" MB");
  277. memUsage->setText(str);
  278. /* ------------------ */
  279. num = (long double)obs_get_average_frame_time_ns() / 1000000.0l;
  280. str = QString::number(num, 'f', 1) + QStringLiteral(" ms");
  281. renderTime->setText(str);
  282. long double fpsFrameTime =
  283. (long double)ovi.fps_den * 1000.0l / (long double)ovi.fps_num;
  284. if (num > fpsFrameTime)
  285. setThemeID(renderTime, "error");
  286. else if (num > fpsFrameTime * 0.75l)
  287. setThemeID(renderTime, "warning");
  288. else
  289. setThemeID(renderTime, "");
  290. /* ------------------ */
  291. video_t *video = obs_get_video();
  292. uint32_t total_encoded = video_output_get_total_frames(video);
  293. uint32_t total_skipped = video_output_get_skipped_frames(video);
  294. if (total_encoded < first_encoded || total_skipped < first_skipped) {
  295. first_encoded = total_encoded;
  296. first_skipped = total_skipped;
  297. }
  298. total_encoded -= first_encoded;
  299. total_skipped -= first_skipped;
  300. num = total_encoded
  301. ? (long double)total_skipped / (long double)total_encoded
  302. : 0.0l;
  303. num *= 100.0l;
  304. str = QString("%1 / %2 (%3%)")
  305. .arg(QString::number(total_skipped),
  306. QString::number(total_encoded),
  307. QString::number(num, 'f', 1));
  308. skippedFrames->setText(str);
  309. if (num > 5.0l)
  310. setThemeID(skippedFrames, "error");
  311. else if (num > 1.0l)
  312. setThemeID(skippedFrames, "warning");
  313. else
  314. setThemeID(skippedFrames, "");
  315. /* ------------------ */
  316. uint32_t total_rendered = obs_get_total_frames();
  317. uint32_t total_lagged = obs_get_lagged_frames();
  318. if (total_rendered < first_rendered || total_lagged < first_lagged) {
  319. first_rendered = total_rendered;
  320. first_lagged = total_lagged;
  321. }
  322. total_rendered -= first_rendered;
  323. total_lagged -= first_lagged;
  324. num = total_rendered
  325. ? (long double)total_lagged / (long double)total_rendered
  326. : 0.0l;
  327. num *= 100.0l;
  328. str = MakeMissedFramesText(total_lagged, total_rendered, num);
  329. missedFrames->setText(str);
  330. if (num > 5.0l)
  331. setThemeID(missedFrames, "error");
  332. else if (num > 1.0l)
  333. setThemeID(missedFrames, "warning");
  334. else
  335. setThemeID(missedFrames, "");
  336. /* ------------------------------------------- */
  337. /* recording/streaming stats */
  338. outputLabels[0].Update(strOutput, false);
  339. outputLabels[1].Update(recOutput, true);
  340. if (obs_output_active(recOutput)) {
  341. long double kbps = outputLabels[1].kbps;
  342. bitrates.push_back(kbps);
  343. }
  344. }
  345. void OBSBasicStats::StartRecTimeLeft()
  346. {
  347. if (recTimeLeft.isActive())
  348. ResetRecTimeLeft();
  349. recordTimeLeft->setText(QTStr("Calculating"));
  350. recTimeLeft.start();
  351. }
  352. void OBSBasicStats::ResetRecTimeLeft()
  353. {
  354. if (recTimeLeft.isActive()) {
  355. bitrates.clear();
  356. recTimeLeft.stop();
  357. recordTimeLeft->setText(QTStr(""));
  358. }
  359. }
  360. void OBSBasicStats::RecordingTimeLeft()
  361. {
  362. long double averageBitrate =
  363. accumulate(bitrates.begin(), bitrates.end(), 0.0) /
  364. (long double)bitrates.size();
  365. long double bytesPerSec = (averageBitrate / 8.0l) * 1000.0l;
  366. long double secondsUntilFull = (long double)num_bytes / bytesPerSec;
  367. bitrates.clear();
  368. int totalMinutes = (int)secondsUntilFull / 60;
  369. int minutes = totalMinutes % 60;
  370. int hours = totalMinutes / 60;
  371. QString text = MakeTimeLeftText(hours, minutes);
  372. recordTimeLeft->setText(text);
  373. recordTimeLeft->setMinimumWidth(recordTimeLeft->width());
  374. }
  375. void OBSBasicStats::Reset()
  376. {
  377. timer.start();
  378. first_encoded = 0xFFFFFFFF;
  379. first_skipped = 0xFFFFFFFF;
  380. first_rendered = 0xFFFFFFFF;
  381. first_lagged = 0xFFFFFFFF;
  382. OBSOutputAutoRelease strOutput = obs_frontend_get_streaming_output();
  383. OBSOutputAutoRelease recOutput = obs_frontend_get_recording_output();
  384. outputLabels[0].Reset(strOutput);
  385. outputLabels[1].Reset(recOutput);
  386. Update();
  387. }
  388. void OBSBasicStats::OutputLabels::Update(obs_output_t *output, bool rec)
  389. {
  390. uint64_t totalBytes = output ? obs_output_get_total_bytes(output) : 0;
  391. uint64_t curTime = os_gettime_ns();
  392. uint64_t bytesSent = totalBytes;
  393. if (bytesSent < lastBytesSent)
  394. bytesSent = 0;
  395. if (bytesSent == 0)
  396. lastBytesSent = 0;
  397. uint64_t bitsBetween = (bytesSent - lastBytesSent) * 8;
  398. long double timePassed =
  399. (long double)(curTime - lastBytesSentTime) / 1000000000.0l;
  400. kbps = (long double)bitsBetween / timePassed / 1000.0l;
  401. if (timePassed < 0.01l)
  402. kbps = 0.0l;
  403. QString str = QTStr("Basic.Stats.Status.Inactive");
  404. QString themeID;
  405. bool active = output ? obs_output_active(output) : false;
  406. if (rec) {
  407. if (active)
  408. str = QTStr("Basic.Stats.Status.Recording");
  409. } else {
  410. if (active) {
  411. bool reconnecting =
  412. output ? obs_output_reconnecting(output)
  413. : false;
  414. if (reconnecting) {
  415. str = QTStr("Basic.Stats.Status.Reconnecting");
  416. themeID = "error";
  417. } else {
  418. str = QTStr("Basic.Stats.Status.Live");
  419. themeID = "good";
  420. }
  421. }
  422. }
  423. status->setText(str);
  424. setThemeID(status, themeID);
  425. long double num = (long double)totalBytes / (1024.0l * 1024.0l);
  426. megabytesSent->setText(
  427. QString("%1 MB").arg(QString::number(num, 'f', 1)));
  428. bitrate->setText(QString("%1 kb/s").arg(QString::number(kbps, 'f', 0)));
  429. if (!rec) {
  430. int total = output ? obs_output_get_total_frames(output) : 0;
  431. int dropped = output ? obs_output_get_frames_dropped(output)
  432. : 0;
  433. if (total < first_total || dropped < first_dropped) {
  434. first_total = 0;
  435. first_dropped = 0;
  436. }
  437. total -= first_total;
  438. dropped -= first_dropped;
  439. num = total ? (long double)dropped / (long double)total * 100.0l
  440. : 0.0l;
  441. str = QString("%1 / %2 (%3%)")
  442. .arg(QString::number(dropped),
  443. QString::number(total),
  444. QString::number(num, 'f', 1));
  445. droppedFrames->setText(str);
  446. if (num > 5.0l)
  447. setThemeID(droppedFrames, "error");
  448. else if (num > 1.0l)
  449. setThemeID(droppedFrames, "warning");
  450. else
  451. setThemeID(droppedFrames, "");
  452. }
  453. lastBytesSent = bytesSent;
  454. lastBytesSentTime = curTime;
  455. }
  456. void OBSBasicStats::OutputLabels::Reset(obs_output_t *output)
  457. {
  458. if (!output)
  459. return;
  460. first_total = obs_output_get_total_frames(output);
  461. first_dropped = obs_output_get_frames_dropped(output);
  462. }
  463. void OBSBasicStats::showEvent(QShowEvent *)
  464. {
  465. timer.start(TIMER_INTERVAL);
  466. }
  467. void OBSBasicStats::hideEvent(QHideEvent *)
  468. {
  469. timer.stop();
  470. }