OBSBasicStats.cpp 16 KB

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