window-basic-stats.cpp 15 KB

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