test_player_with_ui.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. #include <chrono>
  2. #include <string>
  3. #include <thread>
  4. #include <iomanip>
  5. #include "code/base/logger.h"
  6. #include "code/player/player_core_v2.h"
  7. #include <QApplication>
  8. #include <QWidget>
  9. #include <QVBoxLayout>
  10. #include <QHBoxLayout>
  11. #include <QPushButton>
  12. #include <QLabel>
  13. #include <QSlider>
  14. #include <QFileDialog>
  15. #include <QMessageBox>
  16. #include <QTimer>
  17. #include <QProgressBar>
  18. #include <QGroupBox>
  19. #include <QSpinBox>
  20. #include <QCheckBox>
  21. #include <QComboBox>
  22. #include <QTextEdit>
  23. #include <QSplitter>
  24. #include <QDebug>
  25. #include <QDateTime>
  26. #include <QFile>
  27. #include <QTextStream>
  28. using namespace av::player;
  29. using namespace av::utils;
  30. // 播放器事件回调类
  31. class UIPlayerCallback : public PlayerEventCallback {
  32. public:
  33. UIPlayerCallback(QWidget* parent) : m_parent(parent) {}
  34. void onStateChanged(PlayerState newState) override {
  35. std::string stateStr;
  36. switch (newState) {
  37. case PlayerState::Idle: stateStr = "Idle"; break;
  38. case PlayerState::Opening: stateStr = "Opening"; break;
  39. case PlayerState::Stopped: stateStr = "Stopped"; break;
  40. case PlayerState::Playing: stateStr = "Playing"; break;
  41. case PlayerState::Paused: stateStr = "Paused"; break;
  42. case PlayerState::Seeking: stateStr = "Seeking"; break;
  43. case PlayerState::Error: stateStr = "Error"; break;
  44. }
  45. Logger::instance().info("[EVENT] State changed to: " + stateStr);
  46. // 发送信号到UI线程
  47. QMetaObject::invokeMethod(m_parent, "onPlayerStateChanged", Qt::QueuedConnection,
  48. Q_ARG(int, static_cast<int>(newState)));
  49. }
  50. void onPositionChanged(int64_t position) override {
  51. // 发送位置更新到UI线程
  52. QMetaObject::invokeMethod(m_parent, "onPlayerPositionChanged", Qt::QueuedConnection,
  53. Q_ARG(qint64, position));
  54. }
  55. void onMediaInfoChanged(const MediaInfo& info) override {
  56. Logger::instance().info("[EVENT] Media info changed:");
  57. Logger::instance().info(" File: " + info.filename);
  58. Logger::instance().info(" Duration: " + std::to_string(info.duration / 1000000.0) + "s");
  59. Logger::instance().info(" Has Video: " + std::string(info.hasVideo ? "Yes" : "No"));
  60. Logger::instance().info(" Has Audio: " + std::string(info.hasAudio ? "Yes" : "No"));
  61. if (info.hasVideo) {
  62. Logger::instance().info(" Video: " + std::to_string(info.width) + "x" + std::to_string(info.height) + " @ " + std::to_string(info.fps) + " fps");
  63. }
  64. if (info.hasAudio) {
  65. Logger::instance().info(" Audio: " + std::to_string(info.sampleRate) + " Hz, " + std::to_string(info.channels) + " channels");
  66. }
  67. // 发送媒体信息到UI线程
  68. QMetaObject::invokeMethod(m_parent, "onMediaInfoChanged", Qt::QueuedConnection);
  69. }
  70. void onErrorOccurred(const std::string& error) override {
  71. Logger::instance().error("[ERROR] " + error);
  72. QMetaObject::invokeMethod(m_parent, "onPlayerError", Qt::QueuedConnection,
  73. Q_ARG(QString, QString::fromStdString(error)));
  74. }
  75. void onFrameDropped(int64_t totalDropped) override {
  76. Logger::instance().warning("[WARNING] Frame dropped, total: " + std::to_string(totalDropped));
  77. }
  78. void onSyncError(double error, const std::string& reason) override {
  79. Logger::instance().warning("[WARNING] Sync error: " + std::to_string(error * 1000) + "ms, reason: " + reason);
  80. }
  81. void onEndOfFile() override {
  82. Logger::instance().info("[EVENT] End of file reached");
  83. QMetaObject::invokeMethod(m_parent, "onPlayerEndOfFile", Qt::QueuedConnection);
  84. }
  85. private:
  86. QWidget* m_parent;
  87. };
  88. // 主播放器窗口类
  89. class PlayerWindow : public QWidget {
  90. Q_OBJECT
  91. public:
  92. PlayerWindow(QWidget* parent = nullptr) : QWidget(parent) {
  93. setupUI();
  94. setupPlayer();
  95. connectSignals();
  96. // 设置窗口属性
  97. setWindowTitle("AV Player Test with UI");
  98. resize(1280, 900); // 增加窗口大小以适应更多统计信息
  99. // 启动更新定时器
  100. m_updateTimer = new QTimer(this);
  101. connect(m_updateTimer, &QTimer::timeout, this, &PlayerWindow::updateUI);
  102. m_updateTimer->start(100); // 100ms更新一次
  103. m_player->openFile("C:/Users/zhuizhu/Videos/2.mp4");
  104. // playPause();
  105. }
  106. ~PlayerWindow() {
  107. if (m_player) {
  108. m_player->stop();
  109. }
  110. }
  111. public slots:
  112. void onPlayerStateChanged(int state) {
  113. PlayerState playerState = static_cast<PlayerState>(state);
  114. switch (playerState) {
  115. case PlayerState::Idle:
  116. m_stateLabel->setText("状态: 空闲");
  117. m_playButton->setText("播放");
  118. m_playButton->setEnabled(false);
  119. break;
  120. case PlayerState::Opening:
  121. m_stateLabel->setText("状态: 打开中...");
  122. m_playButton->setEnabled(false);
  123. break;
  124. case PlayerState::Stopped:
  125. m_stateLabel->setText("状态: 已停止");
  126. m_playButton->setText("播放");
  127. m_playButton->setEnabled(true);
  128. break;
  129. case PlayerState::Playing:
  130. m_stateLabel->setText("状态: 播放中");
  131. m_playButton->setText("暂停");
  132. m_playButton->setEnabled(true);
  133. break;
  134. case PlayerState::Paused:
  135. m_stateLabel->setText("状态: 已暂停");
  136. m_playButton->setText("播放");
  137. m_playButton->setEnabled(true);
  138. break;
  139. case PlayerState::Seeking:
  140. m_stateLabel->setText("状态: 跳转中...");
  141. break;
  142. case PlayerState::Error:
  143. m_stateLabel->setText("状态: 错误");
  144. m_playButton->setEnabled(false);
  145. break;
  146. }
  147. }
  148. void onPlayerPositionChanged(qint64 position) {
  149. if (!m_seeking) {
  150. // 更新位置标签(秒数显示)
  151. double seconds = position / 1000000.0;
  152. m_positionLabel->setText(QString("位置: %1s").arg(seconds, 0, 'f', 2));
  153. // 我们不在这里更新进度条和时间标签,而是在updateUI中统一更新
  154. // 这样可以避免UI更新过于频繁
  155. }
  156. }
  157. void onMediaInfoChanged() {
  158. if (m_player) {
  159. auto info = m_player->getMediaInfo();
  160. m_duration = info.duration;
  161. QString infoText = QString("文件: %1\n")
  162. .arg(QString::fromStdString(info.filename));
  163. if (info.duration > 0) {
  164. double durationSec = info.duration / 1000000.0;
  165. infoText += QString("时长: %1s\n").arg(durationSec, 0, 'f', 2);
  166. // 更新时间标签显示总时长
  167. m_timeLabel->setText(QString("00:00:00 / %1").arg(formatTime(info.duration)));
  168. }
  169. // 更新视频流复选框状态
  170. m_videoStreamCheckBox->setEnabled(info.hasVideo);
  171. if (!info.hasVideo) {
  172. m_videoStreamCheckBox->setChecked(false);
  173. }
  174. if (info.hasVideo) {
  175. infoText += QString("视频: %1x%2 @ %3fps\n")
  176. .arg(info.width).arg(info.height).arg(info.fps, 0, 'f', 2);
  177. // 初始化视频渲染器
  178. // if (m_videoRenderer && !m_videoRenderer->isInitialized()) {
  179. // m_videoRenderer->initialize(info.width, info.height, AV_PIX_FMT_YUV420P, info.fps);
  180. // }
  181. }
  182. // 更新音频流复选框状态
  183. m_audioStreamCheckBox->setEnabled(info.hasAudio);
  184. if (!info.hasAudio) {
  185. m_audioStreamCheckBox->setChecked(false);
  186. }
  187. if (info.hasAudio) {
  188. infoText += QString("音频: %1Hz, %2ch\n")
  189. .arg(info.sampleRate).arg(info.channels);
  190. }
  191. m_infoLabel->setText(infoText);
  192. m_playButton->setEnabled(true);
  193. }
  194. }
  195. void onPlayerError(const QString& error) {
  196. QMessageBox::critical(this, "播放器错误", error);
  197. }
  198. void onPlayerEndOfFile() {
  199. m_playButton->setText("播放");
  200. // 重置进度条和时间显示
  201. m_progressSlider->setValue(0);
  202. // 如果有持续时间,显示0/总时长;否则显示0/0
  203. if (m_duration > 0) {
  204. m_timeLabel->setText(QString("00:00:00 / %1").arg(formatTime(m_duration)));
  205. } else {
  206. m_timeLabel->setText("00:00:00 / 00:00:00");
  207. }
  208. }
  209. private slots:
  210. void openFile() {
  211. QString fileName = QFileDialog::getOpenFileName(this,
  212. "选择媒体文件", "",
  213. "媒体文件 (*.mp4 *.avi *.mkv *.mov *.wmv *.flv *.webm *.mp3 *.wav *.aac *.flac);;所有文件 (*.*)");
  214. if (!fileName.isEmpty()) {
  215. loadFile(fileName.toStdString());
  216. }
  217. }
  218. void refreshStats() {
  219. if (m_player) {
  220. // 调用播放器的dumpStats方法输出详细统计信息到日志
  221. m_player->dumpStats();
  222. // 强制更新UI显示
  223. updateUI();
  224. // 显示提示信息
  225. QMessageBox::information(this, "统计信息", "统计信息已刷新,详细信息已写入日志文件。");
  226. }
  227. }
  228. void exportStats() {
  229. if (!m_player) return;
  230. // 获取保存文件名
  231. QString fileName = QFileDialog::getSaveFileName(this,
  232. "导出统计信息", "player_stats.txt",
  233. "文本文件 (*.txt);;所有文件 (*.*)");
  234. if (fileName.isEmpty()) return;
  235. // 获取统计信息
  236. auto stats = m_player->getStats();
  237. auto mediaInfo = m_player->getMediaInfo();
  238. auto debugInfo = QString::fromStdString(m_player->getDebugInfo());
  239. // 创建文件
  240. QFile file(fileName);
  241. if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
  242. QMessageBox::critical(this, "错误", "无法创建文件: " + fileName);
  243. return;
  244. }
  245. QTextStream out(&file);
  246. // 写入时间戳
  247. auto now = QDateTime::currentDateTime();
  248. out << "播放器统计信息导出 - " << now.toString("yyyy-MM-dd HH:mm:ss") << "\n\n";
  249. // 写入媒体信息
  250. out << "=== 媒体信息 ===\n";
  251. out << "文件: " << QString::fromStdString(mediaInfo.filename) << "\n";
  252. out << "时长: " << (mediaInfo.duration / 1000000.0) << " 秒\n";
  253. if (mediaInfo.hasVideo) {
  254. out << "视频: " << mediaInfo.width << "x" << mediaInfo.height << " @ " << mediaInfo.fps << " fps\n";
  255. }
  256. if (mediaInfo.hasAudio) {
  257. out << "音频: " << mediaInfo.sampleRate << " Hz, " << mediaInfo.channels << " 通道\n";
  258. }
  259. out << "比特率: " << (mediaInfo.bitrate / 1000.0) << " kbps\n\n";
  260. // 写入播放统计
  261. out << "=== 播放统计 ===\n";
  262. out << "当前位置: " << (stats.currentTime / 1000000.0) << " 秒\n";
  263. out << "总帧数: " << stats.totalFrames << "\n";
  264. out << "丢帧数: " << stats.droppedFrames;
  265. if (stats.totalFrames > 0) {
  266. out << " (" << (stats.droppedFrames * 100.0 / stats.totalFrames) << "%)";
  267. }
  268. out << "\n";
  269. out << "重复帧数: " << stats.duplicatedFrames << "\n";
  270. out << "播放速度: " << stats.playbackSpeed << "x\n\n";
  271. // 写入队列状态
  272. out << "=== 队列状态 ===\n";
  273. out << "视频帧队列: " << stats.queuedVideoFrames << "\n";
  274. out << "音频帧队列: " << stats.queuedAudioFrames << "\n";
  275. out << "数据包队列: " << stats.queuedPackets << "\n\n";
  276. // 写入同步状态
  277. out << "=== 同步状态 ===\n";
  278. out << "当前同步误差: " << (stats.syncError * 1000) << " ms\n";
  279. out << "平均同步误差: " << (stats.avgSyncError * 1000) << " ms\n";
  280. out << "最大同步误差: " << (stats.maxSyncError * 1000) << " ms\n\n";
  281. // 写入详细时钟信息
  282. out << "=== 时钟信息 ===\n";
  283. if (m_player) {
  284. auto debugInfo = QString::fromStdString(m_player->getDebugInfo());
  285. QStringList lines = debugInfo.split('\n');
  286. for (const QString& line : lines) {
  287. if (line.trimmed().startsWith("Audio:")) {
  288. QStringList parts = line.split(":");
  289. if (parts.size() >= 2) {
  290. bool ok;
  291. double value = parts[1].trimmed().toDouble(&ok);
  292. if (ok) {
  293. out << "音频时钟: " << value << " 秒\n";
  294. }
  295. }
  296. } else if (line.trimmed().startsWith("Video:")) {
  297. QStringList parts = line.split(":");
  298. if (parts.size() >= 2) {
  299. bool ok;
  300. double value = parts[1].trimmed().toDouble(&ok);
  301. if (ok) {
  302. out << "视频时钟: " << value << " 秒\n";
  303. }
  304. }
  305. } else if (line.trimmed().startsWith("External:")) {
  306. QStringList parts = line.split(":");
  307. if (parts.size() >= 2) {
  308. bool ok;
  309. double value = parts[1].trimmed().toDouble(&ok);
  310. if (ok) {
  311. out << "外部时钟: " << value << " 秒\n";
  312. }
  313. }
  314. } else if (line.trimmed().startsWith("Master:")) {
  315. QStringList parts = line.split(":");
  316. if (parts.size() >= 2) {
  317. bool ok;
  318. double value = parts[1].trimmed().toDouble(&ok);
  319. if (ok) {
  320. out << "主时钟: " << value << " 秒\n";
  321. }
  322. }
  323. } else if (line.contains("Master Clock Type:")) {
  324. QStringList parts = line.split(":");
  325. if (parts.size() >= 2) {
  326. out << "主时钟类型: " << parts[1].trimmed() << "\n";
  327. }
  328. } else if (line.contains("Sync Strategy:")) {
  329. QStringList parts = line.split(":");
  330. if (parts.size() >= 2) {
  331. out << "同步策略: " << parts[1].trimmed() << "\n";
  332. }
  333. }
  334. }
  335. }
  336. out << "\n";
  337. // 写入性能统计
  338. out << "=== 性能统计 ===\n";
  339. out << "CPU使用率: " << stats.cpuUsage << "%\n";
  340. out << "内存使用: " << stats.memoryUsage << " MB\n";
  341. out << "比特率: " << stats.bitrate << " kbps\n\n";
  342. // 写入调试信息
  343. out << "=== 调试信息 ===\n";
  344. out << debugInfo << "\n";
  345. file.close();
  346. QMessageBox::information(this, "导出成功", "统计信息已成功导出到: " + fileName);
  347. }
  348. void playPause() {
  349. if (!m_player) return;
  350. auto state = m_player->getState();
  351. if (state == PlayerState::Playing) {
  352. m_player->pause();
  353. } else if (state == PlayerState::Paused || state == PlayerState::Stopped) {
  354. m_player->play();
  355. }
  356. }
  357. void stop() {
  358. if (m_player) {
  359. m_player->stop();
  360. }
  361. }
  362. void onProgressSliderPressed() {
  363. m_seeking = true;
  364. }
  365. void onProgressSliderReleased() {
  366. if (m_player && m_duration > 0) {
  367. int value = m_progressSlider->value();
  368. int64_t position = (m_duration * value) / 100;
  369. m_player->seek(position);
  370. // 添加一个延迟后再设置m_seeking为false
  371. // 这样可以让seek操作有足够时间完成初始化和缓冲
  372. QTimer::singleShot(500, this, [this]() {
  373. m_seeking = false;
  374. });
  375. return; // 不要立即设置m_seeking为false
  376. }
  377. m_seeking = false;
  378. }
  379. void onProgressSliderMoved(int value) {
  380. if (m_player && m_duration > 0) {
  381. // 计算预览位置
  382. int64_t previewPosition = (m_duration * value) / 100;
  383. // 更新时间标签显示预览时间
  384. QString timeText = QString("%1 / %2")
  385. .arg(formatTime(previewPosition))
  386. .arg(formatTime(m_duration));
  387. m_timeLabel->setText(timeText);
  388. }
  389. }
  390. void onVolumeChanged(int value) {
  391. if (m_player) {
  392. double volume = value / 100.0;
  393. m_player->setVolume(volume);
  394. m_volumeLabel->setText(QString("音量: %1%").arg(value));
  395. }
  396. }
  397. // 将微秒转换为时间字符串 (HH:MM:SS)
  398. QString formatTime(int64_t timeUs) {
  399. int totalSeconds = static_cast<int>(timeUs / 1000000);
  400. int hours = totalSeconds / 3600;
  401. int minutes = (totalSeconds % 3600) / 60;
  402. int seconds = totalSeconds % 60;
  403. return QString("%1:%2:%3")
  404. .arg(hours, 2, 10, QChar('0'))
  405. .arg(minutes, 2, 10, QChar('0'))
  406. .arg(seconds, 2, 10, QChar('0'));
  407. }
  408. void updateUI() {
  409. if (m_player) {
  410. // 更新统计信息
  411. auto stats = m_player->getStats();
  412. // 基本播放统计
  413. QString statsText = QString("帧数: %1\n丢帧: %2 (%3%)\n重复帧: %4\n速度: %5x")
  414. .arg(stats.totalFrames)
  415. .arg(stats.droppedFrames)
  416. .arg(stats.totalFrames > 0 ? (stats.droppedFrames * 100.0 / stats.totalFrames) : 0, 0, 'f', 1)
  417. .arg(stats.duplicatedFrames)
  418. .arg(stats.playbackSpeed, 0, 'f', 2);
  419. // 队列状态
  420. statsText += QString("\n\n队列状态:\n视频帧: %1\n音频帧: %2\n数据包: %3")
  421. .arg(stats.queuedVideoFrames)
  422. .arg(stats.queuedAudioFrames)
  423. .arg(stats.queuedPackets);
  424. // 同步统计 - 获取更详细的同步信息
  425. QString syncText = "\n\n同步状态:\n当前误差: %1 ms\n平均误差: %2 ms\n最大误差: %3 ms";
  426. // 如果播放器有同步器,获取详细的时钟信息
  427. if (m_player) {
  428. auto debugInfo = QString::fromStdString(m_player->getDebugInfo());
  429. // 解析调试信息中的时钟数据
  430. QStringList lines = debugInfo.split('\n');
  431. QString audioClockStr = "N/A", videoClockStr = "N/A", externalClockStr = "N/A", masterClockStr = "N/A";
  432. QString masterTypeStr = "N/A", syncStrategyStr = "N/A";
  433. for (const QString& line : lines) {
  434. if (line.trimmed().startsWith("Audio:")) {
  435. QStringList parts = line.split(":");
  436. if (parts.size() >= 2) {
  437. bool ok;
  438. double value = parts[1].trimmed().toDouble(&ok);
  439. if (ok) {
  440. audioClockStr = QString::number(value, 'f', 3) + "s";
  441. }
  442. }
  443. } else if (line.trimmed().startsWith("Video:")) {
  444. QStringList parts = line.split(":");
  445. if (parts.size() >= 2) {
  446. bool ok;
  447. double value = parts[1].trimmed().toDouble(&ok);
  448. if (ok) {
  449. videoClockStr = QString::number(value, 'f', 3) + "s";
  450. }
  451. }
  452. } else if (line.trimmed().startsWith("External:")) {
  453. QStringList parts = line.split(":");
  454. if (parts.size() >= 2) {
  455. bool ok;
  456. double value = parts[1].trimmed().toDouble(&ok);
  457. if (ok) {
  458. externalClockStr = QString::number(value, 'f', 3) + "s";
  459. }
  460. }
  461. } else if (line.trimmed().startsWith("Master:")) {
  462. QStringList parts = line.split(":");
  463. if (parts.size() >= 2) {
  464. bool ok;
  465. double value = parts[1].trimmed().toDouble(&ok);
  466. if (ok) {
  467. masterClockStr = QString::number(value, 'f', 3) + "s";
  468. }
  469. }
  470. } else if (line.contains("Master Clock Type:")) {
  471. QStringList parts = line.split(":");
  472. if (parts.size() >= 2) {
  473. masterTypeStr = parts[1].trimmed();
  474. }
  475. } else if (line.contains("Sync Strategy:")) {
  476. QStringList parts = line.split(":");
  477. if (parts.size() >= 2) {
  478. syncStrategyStr = parts[1].trimmed();
  479. }
  480. }
  481. }
  482. syncText = QString("\n\n同步状态:\n当前误差: %1 ms\n平均误差: %2 ms\n最大误差: %3 ms\n\n时钟信息:\n音频时钟: %4\n视频时钟: %5\n外部时钟: %6\n主时钟: %7\n\n同步配置:\n主时钟类型: %8\n同步策略: %9")
  483. .arg(stats.syncError * 1000, 0, 'f', 1)
  484. .arg(stats.avgSyncError * 1000, 0, 'f', 1)
  485. .arg(stats.maxSyncError * 1000, 0, 'f', 1)
  486. .arg(audioClockStr)
  487. .arg(videoClockStr)
  488. .arg(externalClockStr)
  489. .arg(masterClockStr)
  490. .arg(masterTypeStr)
  491. .arg(syncStrategyStr);
  492. } else {
  493. syncText = syncText.arg(stats.syncError * 1000, 0, 'f', 1)
  494. .arg(stats.avgSyncError * 1000, 0, 'f', 1)
  495. .arg(stats.maxSyncError * 1000, 0, 'f', 1);
  496. }
  497. statsText += syncText;
  498. // 性能统计
  499. statsText += QString("\n\n性能:\nCPU: %1%\n内存: %2 MB\n比特率: %3 kbps")
  500. .arg(stats.cpuUsage, 0, 'f', 1)
  501. .arg(stats.memoryUsage, 0, 'f', 1)
  502. .arg(stats.bitrate, 0, 'f', 0);
  503. m_statsLabel->setText(statsText);
  504. // 更新时间显示和进度条
  505. if (!m_seeking && m_duration > 0) {
  506. int64_t currentPosition = m_player->getCurrentTime();
  507. // 更新进度条
  508. int progress = static_cast<int>((currentPosition * 100) / m_duration);
  509. m_progressSlider->setValue(progress);
  510. // 更新时间标签
  511. QString timeText = QString("%1 / %2")
  512. .arg(formatTime(currentPosition))
  513. .arg(formatTime(m_duration));
  514. m_timeLabel->setText(timeText);
  515. }
  516. }
  517. }
  518. void onVideoStreamToggled(bool enabled) {
  519. if (m_player) {
  520. m_player->enableVideoStream(enabled);
  521. Logger::instance().info(QString("视频流%1").arg(enabled ? "启用" : "禁用").toStdString());
  522. }
  523. }
  524. void onAudioStreamToggled(bool enabled) {
  525. if (m_player) {
  526. m_player->enableAudioStream(enabled);
  527. Logger::instance().info(QString("音频流%1").arg(enabled ? "启用" : "禁用").toStdString());
  528. }
  529. }
  530. private:
  531. void setupUI() {
  532. auto* mainLayout = new QHBoxLayout(this);
  533. // 左侧视频区域
  534. auto* leftWidget = new QWidget;
  535. auto* leftLayout = new QVBoxLayout(leftWidget);
  536. // 视频渲染器
  537. m_videoRenderer = new OpenGLVideoWidget;
  538. m_videoRenderer->setMinimumSize(640, 480);
  539. leftLayout->addWidget(m_videoRenderer, 1);
  540. // 控制按钮
  541. auto* controlLayout = new QHBoxLayout;
  542. m_openButton = new QPushButton("打开文件");
  543. m_playButton = new QPushButton("播放");
  544. m_stopButton = new QPushButton("停止");
  545. m_playButton->setEnabled(false);
  546. controlLayout->addWidget(m_openButton);
  547. controlLayout->addWidget(m_playButton);
  548. controlLayout->addWidget(m_stopButton);
  549. controlLayout->addStretch();
  550. leftLayout->addLayout(controlLayout);
  551. // 进度条和时间显示
  552. auto* progressLayout = new QHBoxLayout;
  553. m_progressSlider = new QSlider(Qt::Horizontal);
  554. m_progressSlider->setRange(0, 100);
  555. m_timeLabel = new QLabel("00:00:00 / 00:00:00");
  556. progressLayout->addWidget(m_progressSlider);
  557. progressLayout->addWidget(m_timeLabel);
  558. leftLayout->addLayout(progressLayout);
  559. // 音量控制
  560. auto* volumeLayout = new QHBoxLayout;
  561. volumeLayout->addWidget(new QLabel("音量:"));
  562. m_volumeSlider = new QSlider(Qt::Horizontal);
  563. m_volumeSlider->setRange(0, 100);
  564. m_volumeSlider->setValue(100);
  565. m_volumeSlider->setMaximumWidth(200);
  566. m_volumeLabel = new QLabel("音量: 100%");
  567. volumeLayout->addWidget(m_volumeSlider);
  568. volumeLayout->addWidget(m_volumeLabel);
  569. volumeLayout->addStretch();
  570. leftLayout->addLayout(volumeLayout);
  571. // 流控制
  572. auto* streamControlLayout = new QHBoxLayout;
  573. m_videoStreamCheckBox = new QCheckBox("启用视频");
  574. m_audioStreamCheckBox = new QCheckBox("启用音频");
  575. m_videoStreamCheckBox->setChecked(true);
  576. m_audioStreamCheckBox->setChecked(true);
  577. streamControlLayout->addWidget(m_videoStreamCheckBox);
  578. streamControlLayout->addWidget(m_audioStreamCheckBox);
  579. streamControlLayout->addStretch();
  580. leftLayout->addLayout(streamControlLayout);
  581. mainLayout->addWidget(leftWidget, 2);
  582. // 右侧信息面板
  583. auto* rightWidget = new QWidget;
  584. auto* rightLayout = new QVBoxLayout(rightWidget);
  585. rightWidget->setMinimumWidth(300);
  586. rightWidget->setMaximumWidth(350);
  587. // 状态信息
  588. auto* statusGroup = new QGroupBox("状态信息");
  589. auto* statusLayout = new QVBoxLayout(statusGroup);
  590. m_stateLabel = new QLabel("状态: 空闲");
  591. m_positionLabel = new QLabel("位置: 0s");
  592. statusLayout->addWidget(m_stateLabel);
  593. statusLayout->addWidget(m_positionLabel);
  594. rightLayout->addWidget(statusGroup);
  595. // 媒体信息
  596. auto* infoGroup = new QGroupBox("媒体信息");
  597. auto* infoLayout = new QVBoxLayout(infoGroup);
  598. m_infoLabel = new QLabel("未加载文件");
  599. m_infoLabel->setWordWrap(true);
  600. infoLayout->addWidget(m_infoLabel);
  601. rightLayout->addWidget(infoGroup);
  602. // 统计信息
  603. auto* statsGroup = new QGroupBox("播放统计");
  604. auto* statsLayout = new QVBoxLayout(statsGroup);
  605. // 添加刷新和导出按钮
  606. auto* refreshLayout = new QHBoxLayout();
  607. m_refreshStatsButton = new QPushButton("刷新统计");
  608. m_exportStatsButton = new QPushButton("导出统计");
  609. refreshLayout->addWidget(m_refreshStatsButton);
  610. refreshLayout->addWidget(m_exportStatsButton);
  611. refreshLayout->addStretch();
  612. statsLayout->addLayout(refreshLayout);
  613. m_statsLabel = new QLabel("帧数: 0\n丢帧: 0 (0.0%)\n重复帧: 0\n速度: 1.0x\n\n队列状态:\n视频帧: 0\n音频帧: 0\n数据包: 0\n\n同步状态:\n当前误差: 0.0 ms\n平均误差: 0.0 ms\n最大误差: 0.0 ms\n\n时钟信息:\n音频时钟: N/A\n视频时钟: N/A\n外部时钟: N/A\n主时钟: N/A\n\n同步配置:\n主时钟类型: N/A\n同步策略: N/A\n\n性能:\nCPU: 0.0%\n内存: 0.0 MB\n比特率: 0 kbps");
  614. m_statsLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
  615. m_statsLabel->setWordWrap(true);
  616. m_statsLabel->setMinimumHeight(450); // 增加最小高度以显示更多同步信息
  617. statsLayout->addWidget(m_statsLabel);
  618. rightLayout->addWidget(statsGroup);
  619. rightLayout->addStretch();
  620. mainLayout->addWidget(rightWidget);
  621. }
  622. void setupPlayer() {
  623. // 创建同步配置
  624. SyncConfigV2 syncConfig;
  625. syncConfig.strategy = SyncStrategy::VIDEO_MASTER;
  626. syncConfig.syncThresholdMin = 0.040;
  627. syncConfig.syncThresholdMax = 0.100;
  628. syncConfig.frameDropThreshold = 0.100;
  629. syncConfig.frameDupThreshold = 0.100;
  630. syncConfig.audioDiffThreshold = 0.100;
  631. syncConfig.audioDiffAvgCoef = 0.01;
  632. syncConfig.audioDiffAvgCount = 20;
  633. syncConfig.clockSpeedMin = 0.9;
  634. syncConfig.clockSpeedMax = 1.1;
  635. syncConfig.clockSpeedStep = 0.001;
  636. syncConfig.minFramesForSync = 2;
  637. syncConfig.maxFramesForSync = 10;
  638. syncConfig.noSyncThreshold = 10.0;
  639. // 创建播放器实例
  640. m_player = std::make_unique<PlayerCoreV2>(syncConfig);
  641. // 设置视频渲染器
  642. m_player->setOpenGLVideoRenderer(m_videoRenderer);
  643. // 设置初始音量
  644. m_player->setVolume(m_volumeSlider->value() / 100.0);
  645. // 创建事件回调
  646. m_callback = std::make_unique<UIPlayerCallback>(this);
  647. m_player->setEventCallback(m_callback.get());
  648. m_duration = 0;
  649. m_seeking = false;
  650. }
  651. void connectSignals() {
  652. connect(m_openButton, &QPushButton::clicked, this, &PlayerWindow::openFile);
  653. connect(m_playButton, &QPushButton::clicked, this, &PlayerWindow::playPause);
  654. connect(m_stopButton, &QPushButton::clicked, this, &PlayerWindow::stop);
  655. // 进度条信号连接
  656. connect(m_progressSlider, &QSlider::sliderPressed, this, &PlayerWindow::onProgressSliderPressed);
  657. connect(m_progressSlider, &QSlider::sliderReleased, this, &PlayerWindow::onProgressSliderReleased);
  658. connect(m_progressSlider, &QSlider::sliderMoved, this, &PlayerWindow::onProgressSliderMoved);
  659. // 添加进度条点击跳转功能
  660. connect(m_progressSlider, &QSlider::valueChanged, [this](int value) {
  661. if (m_seeking && m_player && m_duration > 0) {
  662. onProgressSliderMoved(value);
  663. }
  664. });
  665. connect(m_volumeSlider, &QSlider::valueChanged, this, &PlayerWindow::onVolumeChanged);
  666. // 连接流控制复选框信号
  667. connect(m_videoStreamCheckBox, &QCheckBox::toggled, this, &PlayerWindow::onVideoStreamToggled);
  668. connect(m_audioStreamCheckBox, &QCheckBox::toggled, this, &PlayerWindow::onAudioStreamToggled);
  669. // 连接统计按钮信号
  670. connect(m_refreshStatsButton, &QPushButton::clicked, this, &PlayerWindow::refreshStats);
  671. connect(m_exportStatsButton, &QPushButton::clicked, this, &PlayerWindow::exportStats);
  672. }
  673. void loadFile(const std::string& filename) {
  674. if (!m_player) return;
  675. Logger::instance().info("Loading file: " + filename);
  676. // 在打开文件前,根据复选框状态设置流启用状态
  677. m_player->enableVideoStream(m_videoStreamCheckBox->isChecked());
  678. m_player->enableAudioStream(m_audioStreamCheckBox->isChecked());
  679. auto result = m_player->openFile(filename);
  680. if (result != ErrorCode::SUCCESS) {
  681. QString error = QString("无法打开文件: %1\n错误代码: %2")
  682. .arg(QString::fromStdString(filename))
  683. .arg(static_cast<int>(result));
  684. QMessageBox::critical(this, "文件打开失败", error);
  685. Logger::instance().error("Failed to open file: " + std::to_string(static_cast<int>(result)));
  686. }
  687. }
  688. private:
  689. // UI组件
  690. OpenGLVideoWidget* m_videoRenderer;
  691. QPushButton* m_openButton;
  692. QPushButton* m_playButton;
  693. QPushButton* m_stopButton;
  694. QPushButton* m_refreshStatsButton;
  695. QPushButton* m_exportStatsButton;
  696. QSlider* m_progressSlider;
  697. QSlider* m_volumeSlider;
  698. QLabel* m_stateLabel;
  699. QLabel* m_positionLabel;
  700. QLabel* m_infoLabel;
  701. QLabel* m_statsLabel;
  702. QLabel* m_volumeLabel;
  703. QLabel* m_timeLabel;
  704. QCheckBox* m_videoStreamCheckBox;
  705. QCheckBox* m_audioStreamCheckBox;
  706. QTimer* m_updateTimer;
  707. // 播放器相关
  708. std::unique_ptr<PlayerCoreV2> m_player;
  709. std::unique_ptr<UIPlayerCallback> m_callback;
  710. int64_t m_duration;
  711. bool m_seeking;
  712. };
  713. int main(int argc, char* argv[]) {
  714. QApplication app(argc, argv);
  715. // 初始化日志系统
  716. Logger::instance().initialize("test.log", LogLevel::DEBUG, false, false);
  717. Logger::instance().info("PlayerCoreV2 Example Started");
  718. try {
  719. // 创建播放器窗口
  720. PlayerWindow window;
  721. window.show();
  722. // 如果有命令行参数,自动加载文件
  723. // if (argc > 1) {
  724. // QTimer::singleShot(500, [&window, argv]() {
  725. // QMetaObject::invokeMethod(&window, "loadFile", Qt::QueuedConnection,
  726. // Q_ARG(std::string, std::string(argv[1])));
  727. // });
  728. // } else {
  729. // // 默认加载测试文件
  730. // QTimer::singleShot(500, [&window]() {
  731. // std::string testFile = "C:/Users/zhuizhu/Videos/2.mp4";
  732. // QMetaObject::invokeMethod(&window, "loadFile", Qt::QueuedConnection,
  733. // Q_ARG(std::string, testFile));
  734. // });
  735. // }
  736. return app.exec();
  737. } catch (const std::exception& e) {
  738. Logger::instance().error("Exception: " + std::string(e.what()));
  739. QMessageBox::critical(nullptr, "错误", QString("发生异常: %1").arg(e.what()));
  740. return 1;
  741. } catch (...) {
  742. Logger::instance().error("Unknown exception occurred");
  743. QMessageBox::critical(nullptr, "错误", "发生未知异常");
  744. return 1;
  745. }
  746. }
  747. #include "test_player_with_ui.moc"