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