window-basic-stats.cpp 15 KB

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