test_player_with_ui.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /**
  2. * @file test_player_with_ui.cpp
  3. * @brief 带有视频播放界面的综合测试程序
  4. * @author AI Assistant
  5. * @date 2024
  6. */
  7. #include <chrono>
  8. #include <string>
  9. #include <thread>
  10. #include <iomanip>
  11. #include "code/base/logger.h"
  12. #include "code/player/player_core_v2.h"
  13. #include "code/player/opengl_video_renderer.h"
  14. #include <QApplication>
  15. #include <QWidget>
  16. #include <QVBoxLayout>
  17. #include <QHBoxLayout>
  18. #include <QPushButton>
  19. #include <QLabel>
  20. #include <QSlider>
  21. #include <QFileDialog>
  22. #include <QMessageBox>
  23. #include <QTimer>
  24. #include <QProgressBar>
  25. #include <QGroupBox>
  26. #include <QSpinBox>
  27. #include <QCheckBox>
  28. #include <QComboBox>
  29. #include <QTextEdit>
  30. #include <QSplitter>
  31. #include <QDebug>
  32. using namespace av::player;
  33. using namespace av::utils;
  34. // 播放器事件回调类
  35. class UIPlayerCallback : public PlayerEventCallback {
  36. public:
  37. UIPlayerCallback(QWidget* parent) : m_parent(parent) {}
  38. void onStateChanged(PlayerState newState) override {
  39. std::string stateStr;
  40. switch (newState) {
  41. case PlayerState::Idle: stateStr = "Idle"; break;
  42. case PlayerState::Opening: stateStr = "Opening"; break;
  43. case PlayerState::Stopped: stateStr = "Stopped"; break;
  44. case PlayerState::Playing: stateStr = "Playing"; break;
  45. case PlayerState::Paused: stateStr = "Paused"; break;
  46. case PlayerState::Seeking: stateStr = "Seeking"; break;
  47. case PlayerState::Error: stateStr = "Error"; break;
  48. }
  49. Logger::instance().info("[EVENT] State changed to: " + stateStr);
  50. // 发送信号到UI线程
  51. QMetaObject::invokeMethod(m_parent, "onPlayerStateChanged", Qt::QueuedConnection,
  52. Q_ARG(int, static_cast<int>(newState)));
  53. }
  54. void onPositionChanged(int64_t position) override {
  55. // 发送位置更新到UI线程
  56. QMetaObject::invokeMethod(m_parent, "onPlayerPositionChanged", Qt::QueuedConnection,
  57. Q_ARG(qint64, position));
  58. }
  59. void onMediaInfoChanged(const MediaInfo& info) override {
  60. Logger::instance().info("[EVENT] Media info changed:");
  61. Logger::instance().info(" File: " + info.filename);
  62. Logger::instance().info(" Duration: " + std::to_string(info.duration / 1000000.0) + "s");
  63. Logger::instance().info(" Has Video: " + std::string(info.hasVideo ? "Yes" : "No"));
  64. Logger::instance().info(" Has Audio: " + std::string(info.hasAudio ? "Yes" : "No"));
  65. if (info.hasVideo) {
  66. Logger::instance().info(" Video: " + std::to_string(info.width) + "x" + std::to_string(info.height) + " @ " + std::to_string(info.fps) + " fps");
  67. }
  68. if (info.hasAudio) {
  69. Logger::instance().info(" Audio: " + std::to_string(info.sampleRate) + " Hz, " + std::to_string(info.channels) + " channels");
  70. }
  71. // 发送媒体信息到UI线程
  72. QMetaObject::invokeMethod(m_parent, "onMediaInfoChanged", Qt::QueuedConnection);
  73. }
  74. void onErrorOccurred(const std::string& error) override {
  75. Logger::instance().error("[ERROR] " + error);
  76. QMetaObject::invokeMethod(m_parent, "onPlayerError", Qt::QueuedConnection,
  77. Q_ARG(QString, QString::fromStdString(error)));
  78. }
  79. void onFrameDropped(int64_t totalDropped) override {
  80. Logger::instance().warning("[WARNING] Frame dropped, total: " + std::to_string(totalDropped));
  81. }
  82. void onSyncError(double error, const std::string& reason) override {
  83. Logger::instance().warning("[WARNING] Sync error: " + std::to_string(error * 1000) + "ms, reason: " + reason);
  84. }
  85. void onEndOfFile() override {
  86. Logger::instance().info("[EVENT] End of file reached");
  87. QMetaObject::invokeMethod(m_parent, "onPlayerEndOfFile", Qt::QueuedConnection);
  88. }
  89. private:
  90. QWidget* m_parent;
  91. };
  92. // 主播放器窗口类
  93. class PlayerWindow : public QWidget {
  94. Q_OBJECT
  95. public:
  96. PlayerWindow(QWidget* parent = nullptr) : QWidget(parent) {
  97. setupUI();
  98. setupPlayer();
  99. connectSignals();
  100. // 设置窗口属性
  101. setWindowTitle("AV Player Test with UI");
  102. resize(1200, 800);
  103. // 启动更新定时器
  104. m_updateTimer = new QTimer(this);
  105. connect(m_updateTimer, &QTimer::timeout, this, &PlayerWindow::updateUI);
  106. m_updateTimer->start(100); // 100ms更新一次
  107. m_player->openFile("C:/Users/zhuizhu/Videos/2.mp4");
  108. // playPause();
  109. }
  110. ~PlayerWindow() {
  111. if (m_player) {
  112. m_player->stop();
  113. }
  114. }
  115. public slots:
  116. void onPlayerStateChanged(int state) {
  117. PlayerState playerState = static_cast<PlayerState>(state);
  118. switch (playerState) {
  119. case PlayerState::Idle:
  120. m_stateLabel->setText("状态: 空闲");
  121. m_playButton->setText("播放");
  122. m_playButton->setEnabled(false);
  123. break;
  124. case PlayerState::Opening:
  125. m_stateLabel->setText("状态: 打开中...");
  126. m_playButton->setEnabled(false);
  127. break;
  128. case PlayerState::Stopped:
  129. m_stateLabel->setText("状态: 已停止");
  130. m_playButton->setText("播放");
  131. m_playButton->setEnabled(true);
  132. break;
  133. case PlayerState::Playing:
  134. m_stateLabel->setText("状态: 播放中");
  135. m_playButton->setText("暂停");
  136. m_playButton->setEnabled(true);
  137. break;
  138. case PlayerState::Paused:
  139. m_stateLabel->setText("状态: 已暂停");
  140. m_playButton->setText("播放");
  141. m_playButton->setEnabled(true);
  142. break;
  143. case PlayerState::Seeking:
  144. m_stateLabel->setText("状态: 跳转中...");
  145. break;
  146. case PlayerState::Error:
  147. m_stateLabel->setText("状态: 错误");
  148. m_playButton->setEnabled(false);
  149. break;
  150. }
  151. }
  152. void onPlayerPositionChanged(qint64 position) {
  153. if (!m_seeking) {
  154. double seconds = position / 1000000.0;
  155. m_positionLabel->setText(QString("位置: %1s").arg(seconds, 0, 'f', 2));
  156. if (m_duration > 0) {
  157. int progress = static_cast<int>((position * 100) / m_duration);
  158. m_progressSlider->setValue(progress);
  159. }
  160. }
  161. }
  162. void onMediaInfoChanged() {
  163. if (m_player) {
  164. auto info = m_player->getMediaInfo();
  165. m_duration = info.duration;
  166. QString infoText = QString("文件: %1\n")
  167. .arg(QString::fromStdString(info.filename));
  168. if (info.duration > 0) {
  169. double durationSec = info.duration / 1000000.0;
  170. infoText += QString("时长: %1s\n").arg(durationSec, 0, 'f', 2);
  171. }
  172. if (info.hasVideo) {
  173. infoText += QString("视频: %1x%2 @ %3fps\n")
  174. .arg(info.width).arg(info.height).arg(info.fps, 0, 'f', 2);
  175. // 初始化视频渲染器
  176. // if (m_videoRenderer && !m_videoRenderer->isInitialized()) {
  177. // m_videoRenderer->initialize(info.width, info.height, AV_PIX_FMT_YUV420P, info.fps);
  178. // }
  179. }
  180. if (info.hasAudio) {
  181. infoText += QString("音频: %1Hz, %2ch\n")
  182. .arg(info.sampleRate).arg(info.channels);
  183. }
  184. m_infoLabel->setText(infoText);
  185. m_playButton->setEnabled(true);
  186. }
  187. }
  188. void onPlayerError(const QString& error) {
  189. QMessageBox::critical(this, "播放器错误", error);
  190. }
  191. void onPlayerEndOfFile() {
  192. m_playButton->setText("播放");
  193. }
  194. private slots:
  195. void openFile() {
  196. QString fileName = QFileDialog::getOpenFileName(this,
  197. "选择媒体文件", "",
  198. "媒体文件 (*.mp4 *.avi *.mkv *.mov *.wmv *.flv *.webm *.mp3 *.wav *.aac *.flac);;所有文件 (*.*)");
  199. if (!fileName.isEmpty()) {
  200. loadFile(fileName.toStdString());
  201. }
  202. }
  203. void playPause() {
  204. if (!m_player) return;
  205. auto state = m_player->getState();
  206. if (state == PlayerState::Playing) {
  207. m_player->pause();
  208. } else if (state == PlayerState::Paused || state == PlayerState::Stopped) {
  209. m_player->play();
  210. }
  211. }
  212. void stop() {
  213. if (m_player) {
  214. m_player->stop();
  215. }
  216. }
  217. void onProgressSliderPressed() {
  218. m_seeking = true;
  219. }
  220. void onProgressSliderReleased() {
  221. if (m_player && m_duration > 0) {
  222. int value = m_progressSlider->value();
  223. int64_t position = (m_duration * value) / 100;
  224. m_player->seek(position);
  225. }
  226. m_seeking = false;
  227. }
  228. void onVolumeChanged(int value) {
  229. if (m_player) {
  230. double volume = value / 100.0;
  231. m_player->setVolume(volume);
  232. m_volumeLabel->setText(QString("音量: %1%").arg(value));
  233. }
  234. }
  235. void updateUI() {
  236. if (m_player) {
  237. // 更新统计信息
  238. auto stats = m_player->getStats();
  239. QString statsText = QString("帧数: %1\n丢帧: %2\n重复帧: %3\n速度: %4x")
  240. .arg(stats.totalFrames)
  241. .arg(stats.droppedFrames)
  242. .arg(stats.duplicatedFrames)
  243. .arg(stats.playbackSpeed, 0, 'f', 2);
  244. m_statsLabel->setText(statsText);
  245. }
  246. }
  247. private:
  248. void setupUI() {
  249. auto* mainLayout = new QHBoxLayout(this);
  250. // 左侧视频区域
  251. auto* leftWidget = new QWidget;
  252. auto* leftLayout = new QVBoxLayout(leftWidget);
  253. // 视频渲染器
  254. m_videoRenderer = new OpenGLVideoWidget;
  255. m_videoRenderer->setMinimumSize(640, 480);
  256. leftLayout->addWidget(m_videoRenderer, 1);
  257. // 控制按钮
  258. auto* controlLayout = new QHBoxLayout;
  259. m_openButton = new QPushButton("打开文件");
  260. m_playButton = new QPushButton("播放");
  261. m_stopButton = new QPushButton("停止");
  262. m_playButton->setEnabled(false);
  263. controlLayout->addWidget(m_openButton);
  264. controlLayout->addWidget(m_playButton);
  265. controlLayout->addWidget(m_stopButton);
  266. controlLayout->addStretch();
  267. leftLayout->addLayout(controlLayout);
  268. // 进度条
  269. m_progressSlider = new QSlider(Qt::Horizontal);
  270. m_progressSlider->setRange(0, 100);
  271. leftLayout->addWidget(m_progressSlider);
  272. // 音量控制
  273. auto* volumeLayout = new QHBoxLayout;
  274. volumeLayout->addWidget(new QLabel("音量:"));
  275. m_volumeSlider = new QSlider(Qt::Horizontal);
  276. m_volumeSlider->setRange(0, 100);
  277. m_volumeSlider->setValue(100);
  278. m_volumeSlider->setMaximumWidth(200);
  279. m_volumeLabel = new QLabel("音量: 100%");
  280. volumeLayout->addWidget(m_volumeSlider);
  281. volumeLayout->addWidget(m_volumeLabel);
  282. volumeLayout->addStretch();
  283. leftLayout->addLayout(volumeLayout);
  284. mainLayout->addWidget(leftWidget, 2);
  285. // 右侧信息面板
  286. auto* rightWidget = new QWidget;
  287. auto* rightLayout = new QVBoxLayout(rightWidget);
  288. rightWidget->setMaximumWidth(300);
  289. // 状态信息
  290. auto* statusGroup = new QGroupBox("状态信息");
  291. auto* statusLayout = new QVBoxLayout(statusGroup);
  292. m_stateLabel = new QLabel("状态: 空闲");
  293. m_positionLabel = new QLabel("位置: 0s");
  294. statusLayout->addWidget(m_stateLabel);
  295. statusLayout->addWidget(m_positionLabel);
  296. rightLayout->addWidget(statusGroup);
  297. // 媒体信息
  298. auto* infoGroup = new QGroupBox("媒体信息");
  299. auto* infoLayout = new QVBoxLayout(infoGroup);
  300. m_infoLabel = new QLabel("未加载文件");
  301. m_infoLabel->setWordWrap(true);
  302. infoLayout->addWidget(m_infoLabel);
  303. rightLayout->addWidget(infoGroup);
  304. // 统计信息
  305. auto* statsGroup = new QGroupBox("播放统计");
  306. auto* statsLayout = new QVBoxLayout(statsGroup);
  307. m_statsLabel = new QLabel("帧数: 0\n丢帧: 0\n重复帧: 0\n速度: 1.0x");
  308. statsLayout->addWidget(m_statsLabel);
  309. rightLayout->addWidget(statsGroup);
  310. rightLayout->addStretch();
  311. mainLayout->addWidget(rightWidget);
  312. }
  313. void setupPlayer() {
  314. // 创建同步配置
  315. SyncConfigV2 syncConfig;
  316. syncConfig.syncStrategy = SyncStrategy::ADAPTIVE;
  317. syncConfig.audioSyncThreshold = 0.040;
  318. syncConfig.videoSyncThreshold = 0.020;
  319. syncConfig.maxSyncError = 0.200;
  320. syncConfig.clockUpdateInterval = 10;
  321. syncConfig.smoothingWindow = 10;
  322. syncConfig.enableAdaptiveSync = true;
  323. syncConfig.enableFrameDrop = true;
  324. syncConfig.enableFrameDuplicate = true;
  325. syncConfig.enablePrediction = true;
  326. syncConfig.enableErrorRecovery = true;
  327. // 创建播放器实例
  328. m_player = std::make_unique<PlayerCoreV2>(syncConfig);
  329. // 设置视频渲染器
  330. m_player->setOpenGLVideoRenderer(m_videoRenderer);
  331. // 创建事件回调
  332. m_callback = std::make_unique<UIPlayerCallback>(this);
  333. m_player->setEventCallback(m_callback.get());
  334. m_duration = 0;
  335. m_seeking = false;
  336. }
  337. void connectSignals() {
  338. connect(m_openButton, &QPushButton::clicked, this, &PlayerWindow::openFile);
  339. connect(m_playButton, &QPushButton::clicked, this, &PlayerWindow::playPause);
  340. connect(m_stopButton, &QPushButton::clicked, this, &PlayerWindow::stop);
  341. connect(m_progressSlider, &QSlider::sliderPressed, this, &PlayerWindow::onProgressSliderPressed);
  342. connect(m_progressSlider, &QSlider::sliderReleased, this, &PlayerWindow::onProgressSliderReleased);
  343. connect(m_volumeSlider, &QSlider::valueChanged, this, &PlayerWindow::onVolumeChanged);
  344. }
  345. void loadFile(const std::string& filename) {
  346. if (!m_player) return;
  347. Logger::instance().info("Loading file: " + filename);
  348. auto result = m_player->openFile(filename);
  349. if (result != ErrorCode::SUCCESS) {
  350. QString error = QString("无法打开文件: %1\n错误代码: %2")
  351. .arg(QString::fromStdString(filename))
  352. .arg(static_cast<int>(result));
  353. QMessageBox::critical(this, "文件打开失败", error);
  354. Logger::instance().error("Failed to open file: " + std::to_string(static_cast<int>(result)));
  355. }
  356. }
  357. private:
  358. // UI组件
  359. OpenGLVideoWidget* m_videoRenderer;
  360. QPushButton* m_openButton;
  361. QPushButton* m_playButton;
  362. QPushButton* m_stopButton;
  363. QSlider* m_progressSlider;
  364. QSlider* m_volumeSlider;
  365. QLabel* m_stateLabel;
  366. QLabel* m_positionLabel;
  367. QLabel* m_infoLabel;
  368. QLabel* m_statsLabel;
  369. QLabel* m_volumeLabel;
  370. QTimer* m_updateTimer;
  371. // 播放器相关
  372. std::unique_ptr<PlayerCoreV2> m_player;
  373. std::unique_ptr<UIPlayerCallback> m_callback;
  374. int64_t m_duration;
  375. bool m_seeking;
  376. };
  377. int main(int argc, char* argv[]) {
  378. QApplication app(argc, argv);
  379. // 初始化日志系统
  380. Logger::instance().initialize("test.log", LogLevel::DEBUG, false, false);
  381. Logger::instance().info("PlayerCoreV2 Example Started");
  382. try {
  383. // 创建播放器窗口
  384. PlayerWindow window;
  385. window.show();
  386. // 如果有命令行参数,自动加载文件
  387. // if (argc > 1) {
  388. // QTimer::singleShot(500, [&window, argv]() {
  389. // QMetaObject::invokeMethod(&window, "loadFile", Qt::QueuedConnection,
  390. // Q_ARG(std::string, std::string(argv[1])));
  391. // });
  392. // } else {
  393. // // 默认加载测试文件
  394. // QTimer::singleShot(500, [&window]() {
  395. // std::string testFile = "C:/Users/zhuizhu/Videos/2.mp4";
  396. // QMetaObject::invokeMethod(&window, "loadFile", Qt::QueuedConnection,
  397. // Q_ARG(std::string, testFile));
  398. // });
  399. // }
  400. return app.exec();
  401. } catch (const std::exception& e) {
  402. Logger::instance().error("Exception: " + std::string(e.what()));
  403. QMessageBox::critical(nullptr, "错误", QString("发生异常: %1").arg(e.what()));
  404. return 1;
  405. } catch (...) {
  406. Logger::instance().error("Unknown exception occurred");
  407. QMessageBox::critical(nullptr, "错误", "发生未知异常");
  408. return 1;
  409. }
  410. }
  411. #include "test_player_with_ui.moc"