window-basic-stats.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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. default:
  27. break;
  28. }
  29. }
  30. static QString MakeTimeLeftText(int hours, int minutes)
  31. {
  32. return QString::asprintf("%d %s, %d %s", hours,
  33. QT_TO_UTF8(QTStr("Hours")), minutes,
  34. QT_TO_UTF8(QTStr("Minutes")));
  35. }
  36. static QString MakeMissedFramesText(uint32_t total_lagged,
  37. uint32_t total_rendered, long double num)
  38. {
  39. return QString("%1 / %2 (%3%)")
  40. .arg(QString::number(total_lagged),
  41. QString::number(total_rendered),
  42. QString::number(num, 'f', 1));
  43. }
  44. OBSBasicStats::OBSBasicStats(QWidget *parent, bool closeable)
  45. : QFrame(parent),
  46. cpu_info(os_cpu_usage_info_start()),
  47. timer(this),
  48. recTimeLeft(this)
  49. {
  50. QVBoxLayout *mainLayout = new QVBoxLayout();
  51. QGridLayout *topLayout = new QGridLayout();
  52. outputLayout = new QGridLayout();
  53. bitrates.reserve(REC_TIME_LEFT_INTERVAL / TIMER_INTERVAL);
  54. int row = 0;
  55. auto newStatBare = [&](QString name, QWidget *label, int col) {
  56. QLabel *typeLabel = new QLabel(name, this);
  57. topLayout->addWidget(typeLabel, row, col);
  58. topLayout->addWidget(label, row++, col + 1);
  59. };
  60. auto newStat = [&](const char *strLoc, QWidget *label, int col) {
  61. std::string str = "Basic.Stats.";
  62. str += strLoc;
  63. newStatBare(QTStr(str.c_str()), label, col);
  64. };
  65. /* --------------------------------------------- */
  66. cpuUsage = new QLabel(this);
  67. hddSpace = new QLabel(this);
  68. recordTimeLeft = new QLabel(this);
  69. memUsage = new QLabel(this);
  70. QString str = MakeTimeLeftText(99999, 59);
  71. int textWidth = recordTimeLeft->fontMetrics().boundingRect(str).width();
  72. recordTimeLeft->setMinimumWidth(textWidth);
  73. newStat("CPUUsage", cpuUsage, 0);
  74. newStat("HDDSpaceAvailable", hddSpace, 0);
  75. newStat("DiskFullIn", recordTimeLeft, 0);
  76. newStat("MemoryUsage", memUsage, 0);
  77. fps = new QLabel(this);
  78. renderTime = new QLabel(this);
  79. skippedFrames = new QLabel(this);
  80. missedFrames = new QLabel(this);
  81. str = MakeMissedFramesText(999999, 999999, 99.99);
  82. textWidth = missedFrames->fontMetrics().boundingRect(str).width();
  83. missedFrames->setMinimumWidth(textWidth);
  84. row = 0;
  85. newStatBare("FPS", fps, 2);
  86. newStat("AverageTimeToRender", renderTime, 2);
  87. newStat("MissedFrames", missedFrames, 2);
  88. newStat("SkippedFrames", skippedFrames, 2);
  89. /* --------------------------------------------- */
  90. QPushButton *closeButton = nullptr;
  91. if (closeable)
  92. closeButton = new QPushButton(QTStr("Close"));
  93. QPushButton *resetButton = new QPushButton(QTStr("Reset"));
  94. QHBoxLayout *buttonLayout = new QHBoxLayout;
  95. buttonLayout->addStretch();
  96. buttonLayout->addWidget(resetButton);
  97. if (closeable)
  98. buttonLayout->addWidget(closeButton);
  99. /* --------------------------------------------- */
  100. int col = 0;
  101. auto addOutputCol = [&](const char *loc) {
  102. QLabel *label = new QLabel(QTStr(loc), this);
  103. label->setStyleSheet("font-weight: bold");
  104. outputLayout->addWidget(label, 0, col++);
  105. };
  106. addOutputCol("Basic.Settings.Output");
  107. addOutputCol("Basic.Stats.Status");
  108. addOutputCol("Basic.Stats.DroppedFrames");
  109. addOutputCol("Basic.Stats.MegabytesSent");
  110. addOutputCol("Basic.Stats.Bitrate");
  111. /* --------------------------------------------- */
  112. AddOutputLabels(QTStr("Basic.Stats.Output.Stream"));
  113. AddOutputLabels(QTStr("Basic.Stats.Output.Recording"));
  114. /* --------------------------------------------- */
  115. QVBoxLayout *outputContainerLayout = new QVBoxLayout();
  116. outputContainerLayout->addLayout(outputLayout);
  117. outputContainerLayout->addStretch();
  118. QWidget *widget = new QWidget(this);
  119. widget->setLayout(outputContainerLayout);
  120. QScrollArea *scrollArea = new QScrollArea(this);
  121. scrollArea->setWidget(widget);
  122. scrollArea->setWidgetResizable(true);
  123. /* --------------------------------------------- */
  124. mainLayout->addLayout(topLayout);
  125. mainLayout->addWidget(scrollArea);
  126. mainLayout->addLayout(buttonLayout);
  127. setLayout(mainLayout);
  128. /* --------------------------------------------- */
  129. if (closeable)
  130. connect(closeButton, &QPushButton::clicked,
  131. [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(
  140. QIcon::fromTheme("obs", QIcon(":/res/images/obs_256x256.png")));
  141. #else
  142. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  143. #endif
  144. setWindowModality(Qt::NonModal);
  145. setAttribute(Qt::WA_DeleteOnClose, true);
  146. QObject::connect(&timer, &QTimer::timeout, this,
  147. &OBSBasicStats::Update);
  148. timer.setInterval(TIMER_INTERVAL);
  149. if (isVisible())
  150. timer.start();
  151. Update();
  152. QObject::connect(&recTimeLeft, &QTimer::timeout, this,
  153. &OBSBasicStats::RecordingTimeLeft);
  154. recTimeLeft.setInterval(REC_TIME_LEFT_INTERVAL);
  155. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  156. const char *geometry =
  157. config_get_string(main->Config(), "Stats", "geometry");
  158. if (geometry != NULL) {
  159. QByteArray byteArray =
  160. QByteArray::fromBase64(QByteArray(geometry));
  161. restoreGeometry(byteArray);
  162. QRect windowGeometry = normalGeometry();
  163. if (!WindowPositionValid(windowGeometry)) {
  164. QRect rect =
  165. QGuiApplication::primaryScreen()->geometry();
  166. setGeometry(QStyle::alignedRect(Qt::LeftToRight,
  167. Qt::AlignCenter, size(),
  168. rect));
  169. }
  170. }
  171. obs_frontend_add_event_callback(OBSFrontendEvent, this);
  172. if (obs_frontend_recording_active())
  173. StartRecTimeLeft();
  174. }
  175. void OBSBasicStats::closeEvent(QCloseEvent *event)
  176. {
  177. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  178. if (isVisible()) {
  179. config_set_string(main->Config(), "Stats", "geometry",
  180. saveGeometry().toBase64().constData());
  181. config_save_safe(main->Config(), "tmp", nullptr);
  182. }
  183. QWidget::closeEvent(event);
  184. }
  185. OBSBasicStats::~OBSBasicStats()
  186. {
  187. obs_frontend_remove_event_callback(OBSFrontendEvent, this);
  188. delete shortcutFilter;
  189. os_cpu_usage_info_destroy(cpu_info);
  190. }
  191. void OBSBasicStats::AddOutputLabels(QString name)
  192. {
  193. OutputLabels ol;
  194. ol.name = new QLabel(name, this);
  195. ol.status = new QLabel(this);
  196. ol.droppedFrames = new QLabel(this);
  197. ol.megabytesSent = new QLabel(this);
  198. ol.bitrate = new QLabel(this);
  199. int col = 0;
  200. int row = outputLabels.size() + 1;
  201. outputLayout->addWidget(ol.name, row, col++);
  202. outputLayout->addWidget(ol.status, row, col++);
  203. outputLayout->addWidget(ol.droppedFrames, row, col++);
  204. outputLayout->addWidget(ol.megabytesSent, row, col++);
  205. outputLayout->addWidget(ol.bitrate, row, col++);
  206. outputLabels.push_back(ol);
  207. }
  208. static uint32_t first_encoded = 0xFFFFFFFF;
  209. static uint32_t first_skipped = 0xFFFFFFFF;
  210. static uint32_t first_rendered = 0xFFFFFFFF;
  211. static uint32_t first_lagged = 0xFFFFFFFF;
  212. void OBSBasicStats::InitializeValues()
  213. {
  214. video_t *video = obs_get_video();
  215. first_encoded = video_output_get_total_frames(video);
  216. first_skipped = video_output_get_skipped_frames(video);
  217. first_rendered = obs_get_total_frames();
  218. first_lagged = obs_get_lagged_frames();
  219. }
  220. void OBSBasicStats::Update()
  221. {
  222. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  223. /* TODO: Un-hardcode */
  224. struct obs_video_info ovi = {};
  225. obs_get_video_info(&ovi);
  226. OBSOutputAutoRelease strOutput = obs_frontend_get_streaming_output();
  227. OBSOutputAutoRelease recOutput = obs_frontend_get_recording_output();
  228. if (!strOutput && !recOutput)
  229. return;
  230. /* ------------------------------------------- */
  231. /* general usage */
  232. double curFPS = obs_get_active_fps();
  233. double obsFPS = (double)ovi.fps_num / (double)ovi.fps_den;
  234. QString str = QString::number(curFPS, 'f', 2);
  235. fps->setText(str);
  236. if (curFPS < (obsFPS * 0.8))
  237. setThemeID(fps, "error");
  238. else if (curFPS < (obsFPS * 0.95))
  239. setThemeID(fps, "warning");
  240. else
  241. setThemeID(fps, "");
  242. /* ------------------ */
  243. double usage = os_cpu_usage_info_query(cpu_info);
  244. str = QString::number(usage, 'g', 2) + QStringLiteral("%");
  245. cpuUsage->setText(str);
  246. /* ------------------ */
  247. const char *path = main->GetCurrentOutputPath();
  248. #define MBYTE (1024ULL * 1024ULL)
  249. #define GBYTE (1024ULL * 1024ULL * 1024ULL)
  250. #define TBYTE (1024ULL * 1024ULL * 1024ULL * 1024ULL)
  251. num_bytes = os_get_free_disk_space(path);
  252. QString abrv = QStringLiteral(" MB");
  253. long double num;
  254. num = (long double)num_bytes / (1024.0l * 1024.0l);
  255. if (num_bytes > TBYTE) {
  256. num /= 1024.0l * 1024.0l;
  257. abrv = QStringLiteral(" TB");
  258. } else if (num_bytes > GBYTE) {
  259. num /= 1024.0l;
  260. abrv = QStringLiteral(" GB");
  261. }
  262. str = QString::number(num, 'f', 1) + abrv;
  263. hddSpace->setText(str);
  264. if (num_bytes < GBYTE)
  265. setThemeID(hddSpace, "error");
  266. else if (num_bytes < (5 * GBYTE))
  267. setThemeID(hddSpace, "warning");
  268. else
  269. setThemeID(hddSpace, "");
  270. /* ------------------ */
  271. num = (long double)os_get_proc_resident_size() / (1024.0l * 1024.0l);
  272. str = QString::number(num, 'f', 1) + QStringLiteral(" MB");
  273. memUsage->setText(str);
  274. /* ------------------ */
  275. num = (long double)obs_get_average_frame_time_ns() / 1000000.0l;
  276. str = QString::number(num, 'f', 1) + QStringLiteral(" ms");
  277. renderTime->setText(str);
  278. long double fpsFrameTime =
  279. (long double)ovi.fps_den * 1000.0l / (long double)ovi.fps_num;
  280. if (num > fpsFrameTime)
  281. setThemeID(renderTime, "error");
  282. else if (num > fpsFrameTime * 0.75l)
  283. setThemeID(renderTime, "warning");
  284. else
  285. setThemeID(renderTime, "");
  286. /* ------------------ */
  287. video_t *video = obs_get_video();
  288. uint32_t total_encoded = video_output_get_total_frames(video);
  289. uint32_t total_skipped = video_output_get_skipped_frames(video);
  290. if (total_encoded < first_encoded || total_skipped < first_skipped) {
  291. first_encoded = total_encoded;
  292. first_skipped = total_skipped;
  293. }
  294. total_encoded -= first_encoded;
  295. total_skipped -= first_skipped;
  296. num = total_encoded
  297. ? (long double)total_skipped / (long double)total_encoded
  298. : 0.0l;
  299. num *= 100.0l;
  300. str = QString("%1 / %2 (%3%)")
  301. .arg(QString::number(total_skipped),
  302. QString::number(total_encoded),
  303. QString::number(num, 'f', 1));
  304. skippedFrames->setText(str);
  305. if (num > 5.0l)
  306. setThemeID(skippedFrames, "error");
  307. else if (num > 1.0l)
  308. setThemeID(skippedFrames, "warning");
  309. else
  310. setThemeID(skippedFrames, "");
  311. /* ------------------ */
  312. uint32_t total_rendered = obs_get_total_frames();
  313. uint32_t total_lagged = obs_get_lagged_frames();
  314. if (total_rendered < first_rendered || total_lagged < first_lagged) {
  315. first_rendered = total_rendered;
  316. first_lagged = total_lagged;
  317. }
  318. total_rendered -= first_rendered;
  319. total_lagged -= first_lagged;
  320. num = total_rendered
  321. ? (long double)total_lagged / (long double)total_rendered
  322. : 0.0l;
  323. num *= 100.0l;
  324. str = MakeMissedFramesText(total_lagged, total_rendered, num);
  325. missedFrames->setText(str);
  326. if (num > 5.0l)
  327. setThemeID(missedFrames, "error");
  328. else if (num > 1.0l)
  329. setThemeID(missedFrames, "warning");
  330. else
  331. setThemeID(missedFrames, "");
  332. /* ------------------------------------------- */
  333. /* recording/streaming stats */
  334. outputLabels[0].Update(strOutput, false);
  335. outputLabels[1].Update(recOutput, true);
  336. if (obs_output_active(recOutput)) {
  337. long double kbps = outputLabels[1].kbps;
  338. bitrates.push_back(kbps);
  339. }
  340. }
  341. void OBSBasicStats::StartRecTimeLeft()
  342. {
  343. if (recTimeLeft.isActive())
  344. ResetRecTimeLeft();
  345. recordTimeLeft->setText(QTStr("Calculating"));
  346. recTimeLeft.start();
  347. }
  348. void OBSBasicStats::ResetRecTimeLeft()
  349. {
  350. if (recTimeLeft.isActive()) {
  351. bitrates.clear();
  352. recTimeLeft.stop();
  353. recordTimeLeft->setText(QTStr(""));
  354. }
  355. }
  356. void OBSBasicStats::RecordingTimeLeft()
  357. {
  358. if (bitrates.empty())
  359. return;
  360. long double averageBitrate =
  361. accumulate(bitrates.begin(), bitrates.end(), 0.0) /
  362. (long double)bitrates.size();
  363. if (averageBitrate == 0)
  364. return;
  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. }