-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVideoPlayer.cpp
More file actions
1938 lines (1601 loc) · 69.8 KB
/
VideoPlayer.cpp
File metadata and controls
1938 lines (1601 loc) · 69.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "VideoPlayer.h"
#include <QDateTime>
#include <QApplication>
VideoPlayer::VideoPlayer(QWidget *parent)
: QMainWindow(parent)
, m_videoWidget(nullptr)
, m_formatContext(nullptr)
, m_videoCodecContext(nullptr)
, m_audioCodecContext(nullptr)
, m_videoFrame(nullptr)
, m_audioFrame(nullptr)
, m_packet(nullptr)
, m_videoStreamIndex(-1)
, m_audioStreamIndex(-1)
, m_audioProcessor(nullptr)
, m_timer(new QTimer(this))
, m_isPlaying(false)
, m_isPaused(false)
, m_isSeeking(false)
, m_duration(0)
, m_currentPosition(0)
, m_fps(25.0)
, m_volume(0.8f) // 默认音量80%
, m_isPlaybackStable(false)
, m_frameCount(0)
, m_isDragging(false)
, m_aspectRatio(16.0/9.0)
, m_dragPosition(QPoint())
, m_isResizing(false)
, m_resizeDirection(None)
, m_seekDebounceTimer(new QTimer(this))
, m_pendingSeekPosition(0)
, m_hasPendingSeek(false)
, m_helpOverlay(nullptr)
, m_videoInfoOverlay(nullptr)
, m_loadingWidget(nullptr)
, m_streamManager(new NetworkStreamManager(this))
, m_streamUI(new NetworkStreamUI(this))
, m_streamLoader(new NetworkStreamLoader(this))
, m_lastSyncTime(0)
, m_syncAdjustmentCount(0)
, m_isNetworkStream(false)
{
setupUI();
setupFFmpeg();
setupHelpOverlay();
setupVideoInfoOverlay();
connect(m_timer, &QTimer::timeout, this, &VideoPlayer::updatePosition);
// 设置防抖定时器 - 更短的延迟,保持响应性
m_seekDebounceTimer->setSingleShot(true);
m_seekDebounceTimer->setInterval(50); // 减少到50ms,提高响应性
connect(m_seekDebounceTimer, &QTimer::timeout, this, [this]() {
if (m_hasPendingSeek) {
performSeek(m_pendingSeekPosition);
m_hasPendingSeek = false;
}
});
// 连接 VideoWidget 的拖拽信号
connect(m_videoWidget, &VideoWidget::videoFileDropped, this, &VideoPlayer::openVideo);
// 连接网络流管理器信号
connect(m_streamManager, &NetworkStreamManager::streamConnected, this, &VideoPlayer::onStreamConnected);
connect(m_streamManager, &NetworkStreamManager::streamDisconnected, this, &VideoPlayer::onStreamDisconnected);
connect(m_streamManager, &NetworkStreamManager::streamError, this, &VideoPlayer::onStreamError);
connect(m_streamManager, &NetworkStreamManager::statusChanged, this, &VideoPlayer::onStreamStatusChanged);
// 连接网络流UI信号
connect(m_streamUI, &NetworkStreamUI::connectRequested, this, &VideoPlayer::onNetworkStreamRequested);
// 连接异步加载器信号(移除进度更新信号)
connect(m_streamLoader, &NetworkStreamLoader::loadingStarted, this, &VideoPlayer::onStreamLoadingStarted);
connect(m_streamLoader, &NetworkStreamLoader::streamReady, this, &VideoPlayer::onStreamReady);
connect(m_streamLoader, &NetworkStreamLoader::loadingFailed, this, &VideoPlayer::onStreamLoadingFailed);
connect(m_streamLoader, &NetworkStreamLoader::loadingCancelled, this, &VideoPlayer::onStreamLoadingCancelled);
setWindowTitle("Qt FFmpeg Video Player with Audio");
resize(900, 700);
}
VideoPlayer::~VideoPlayer()
{
// 取消正在进行的加载操作
if (m_streamLoader) {
m_streamLoader->cancelLoading();
}
// 断开网络流连接
if (m_streamManager) {
m_streamManager->disconnect();
}
// 关闭视频
closeVideo();
// 清理网络流组件
if (m_streamUI) {
m_streamUI->deleteLater();
m_streamUI = nullptr;
}
if (m_streamManager) {
m_streamManager->deleteLater();
m_streamManager = nullptr;
}
if (m_streamLoader) {
m_streamLoader->deleteLater();
m_streamLoader = nullptr;
}
}
void VideoPlayer::setupUI()
{
setWindowTitle("动漫播放器");
setMinimumSize(320, 240);
// 极简界面 - 只有视频显示区域和圆角样式
m_videoWidget = new VideoWidget(this);
// 创建GIF加载动画组件
m_loadingWidget = new LoadingWidget(this);
// 极简设计 - 直接使用VideoWidget,无圆角,最高性能
setCentralWidget(m_videoWidget);
// 设置窗口属性 - 去除标题栏
setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
// 简单黑色背景,无圆角,无复杂样式
setStyleSheet("QMainWindow { background-color: black; }");
// VideoWidget纯黑背景
m_videoWidget->setStyleSheet("background-color: black;");
// 启用鼠标跟踪和悬停事件以检测边缘位置
setMouseTracking(true);
setAttribute(Qt::WA_Hover, true);
m_videoWidget->setMouseTracking(true);
// 安装事件过滤器
installEventFilter(this);
// UI组件已移除,全部使用快捷键控制
// 设置快捷键
setupShortcuts();
}
void VideoPlayer::setupFFmpeg()
{
// FFmpeg不再需要av_register_all()在新版本中
}
void VideoPlayer::setupShortcuts()
{
// 文件操作快捷键
QShortcut *openShortcut = new QShortcut(QKeySequence("Ctrl+O"), this);
connect(openShortcut, &QShortcut::activated, this, &VideoPlayer::openFile);
// 新增:网络视频快捷键
QShortcut *openUrlShortcut = new QShortcut(QKeySequence("Ctrl+U"), this);
connect(openUrlShortcut, &QShortcut::activated, this, &VideoPlayer::openNetworkUrl);
QShortcut *quitShortcut = new QShortcut(QKeySequence("Ctrl+Q"), this);
connect(quitShortcut, &QShortcut::activated, this, &QWidget::close);
// 播放控制快捷键
QShortcut *playPauseShortcut = new QShortcut(QKeySequence(Qt::Key_Space), this);
connect(playPauseShortcut, &QShortcut::activated, this, &VideoPlayer::playPause);
QShortcut *stopShortcut = new QShortcut(QKeySequence("Ctrl+S"), this);
connect(stopShortcut, &QShortcut::activated, this, &VideoPlayer::stop);
// 音量控制快捷键
QShortcut *volumeUpShortcut = new QShortcut(QKeySequence(Qt::Key_Up), this);
connect(volumeUpShortcut, &QShortcut::activated, this, [this]() {
m_volume = qMin(1.0f, m_volume + 0.05f);
if (m_audioProcessor) {
m_audioProcessor->setVolume(m_volume);
}
qDebug() << "Volume up:" << (int)(m_volume * 100) << "%";
});
QShortcut *volumeDownShortcut = new QShortcut(QKeySequence(Qt::Key_Down), this);
connect(volumeDownShortcut, &QShortcut::activated, this, [this]() {
m_volume = qMax(0.0f, m_volume - 0.05f);
if (m_audioProcessor) {
m_audioProcessor->setVolume(m_volume);
}
qDebug() << "Volume down:" << (int)(m_volume * 100) << "%";
});
QShortcut *muteShortcut = new QShortcut(QKeySequence("M"), this);
connect(muteShortcut, &QShortcut::activated, this, [this]() {
static float lastVolume = m_volume;
if (m_volume > 0) {
lastVolume = m_volume;
m_volume = 0;
} else {
m_volume = lastVolume;
}
if (m_audioProcessor) {
m_audioProcessor->setVolume(m_volume);
}
qDebug() << "Volume:" << (m_volume > 0 ? "unmuted" : "muted") << (int)(m_volume * 100) << "%";
});
// 进度控制快捷键
QShortcut *seekForwardShortcut = new QShortcut(QKeySequence(Qt::Key_Right), this);
// 保留长按功能,但通过防抖机制控制频率
connect(seekForwardShortcut, &QShortcut::activated, this, [this]() {
if (m_formatContext && !m_isSeeking) {
// 简化稳定性检查 - 只在前5帧内限制,提高响应性
if (!m_isPlaybackStable && m_frameCount < 5) {
qDebug() << "Seek ignored - playback not stable yet, frame count:" << m_frameCount;
return;
}
int currentPos = m_currentPosition / AV_TIME_BASE;
int newPos = qMin((int)(m_duration / AV_TIME_BASE), currentPos + 10);
qDebug() << "Seek forward from" << currentPos << "to" << newPos;
seek(newPos);
}
});
QShortcut *seekBackwardShortcut = new QShortcut(QKeySequence(Qt::Key_Left), this);
// 保留长按功能,但通过防抖机制控制频率
connect(seekBackwardShortcut, &QShortcut::activated, this, [this]() {
if (m_formatContext && !m_isSeeking) {
// 简化稳定性检查 - 只在前5帧内限制,提高响应性
if (!m_isPlaybackStable && m_frameCount < 5) {
qDebug() << "Seek ignored - playback not stable yet, frame count:" << m_frameCount;
return;
}
int currentPos = m_currentPosition / AV_TIME_BASE;
int newPos = qMax(0, currentPos - 10);
qDebug() << "Seek backward from" << currentPos << "to" << newPos;
seek(newPos);
}
});
// 移除了Shift快捷键,避免系统冲突,简化用户体验
// 快速seek快捷键 - 30秒步进
QShortcut *seekForwardFastShortcut = new QShortcut(QKeySequence("Ctrl+Right"), this);
// 恢复长按功能,适合快速浏览视频
connect(seekForwardFastShortcut, &QShortcut::activated, this, [this]() {
if (m_formatContext && !m_isSeeking) {
// 添加播放稳定性检查
if (!m_isPlaybackStable && m_frameCount < 5) {
qDebug() << "Fast seek forward ignored - playback not stable yet, frame count:" << m_frameCount;
return;
}
int currentPos = m_currentPosition / AV_TIME_BASE;
int newPos = qMin((int)(m_duration / AV_TIME_BASE), currentPos + 30);
qDebug() << "Fast seek forward from" << currentPos << "to" << newPos;
seek(newPos);
}
});
QShortcut *seekBackwardFastShortcut = new QShortcut(QKeySequence("Ctrl+Left"), this);
// 恢复长按功能,适合快速浏览视频
connect(seekBackwardFastShortcut, &QShortcut::activated, this, [this]() {
if (m_formatContext && !m_isSeeking) {
// 添加播放稳定性检查
if (!m_isPlaybackStable && m_frameCount < 5) {
qDebug() << "Fast seek backward ignored - playback not stable yet, frame count:" << m_frameCount;
return;
}
int currentPos = m_currentPosition / AV_TIME_BASE;
int newPos = qMax(0, currentPos - 30);
qDebug() << "Fast seek backward from" << currentPos << "to" << newPos;
seek(newPos);
}
});
// 窗口控制快捷键
QShortcut *fullscreenShortcut = new QShortcut(QKeySequence("F"), this);
connect(fullscreenShortcut, &QShortcut::activated, this, [this]() {
if (isFullScreen()) {
showNormal();
} else {
showFullScreen();
}
});
QShortcut *escapeShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this);
connect(escapeShortcut, &QShortcut::activated, this, [this]() {
if (m_loadingWidget && m_loadingWidget->isLoading()) {
// 如果正在显示加载动画,取消加载
m_streamLoader->cancelLoading();
} else if (isFullScreen()) {
showNormal();
}
});
// 最小化快捷键
QShortcut *minimizeShortcut = new QShortcut(QKeySequence("Ctrl+M"), this);
connect(minimizeShortcut, &QShortcut::activated, this, &QWidget::showMinimized);
// 最大化/还原快捷键
QShortcut *maximizeShortcut = new QShortcut(QKeySequence("Ctrl+X"), this);
connect(maximizeShortcut, &QShortcut::activated, this, [this]() {
if (isMaximized()) {
showNormal();
} else {
showMaximized();
}
});
// 关闭窗口快捷键
QShortcut *closeShortcut = new QShortcut(QKeySequence("Alt+F4"), this);
connect(closeShortcut, &QShortcut::activated, this, &QWidget::close);
// 显示/隐藏播放信息快捷键
QShortcut *toggleInfoShortcut = new QShortcut(QKeySequence("I"), this);
connect(toggleInfoShortcut, &QShortcut::activated, this, [this]() {
// 临时显示播放信息
if (!m_formatContext) return;
int currentSec = m_currentPosition / AV_TIME_BASE;
int totalSec = m_duration / AV_TIME_BASE;
QString info = QString("播放进度: %1:%2 / %3:%4")
.arg(currentSec / 60, 2, 10, QChar('0'))
.arg(currentSec % 60, 2, 10, QChar('0'))
.arg(totalSec / 60, 2, 10, QChar('0'))
.arg(totalSec % 60, 2, 10, QChar('0'));
// 在状态栏临时显示信息
if (!statusBar()->isVisible()) {
statusBar()->showMessage(info, 3000); // 显示3秒
statusBar()->show();
QTimer::singleShot(3000, this, [this]() {
statusBar()->hide();
});
}
});
// 快捷键帮助
QShortcut *helpShortcut = new QShortcut(QKeySequence("H"), this);
connect(helpShortcut, &QShortcut::activated, this, &VideoPlayer::toggleHelpOverlay);
QShortcut *helpShortcut2 = new QShortcut(QKeySequence("F1"), this);
connect(helpShortcut2, &QShortcut::activated, this, &VideoPlayer::toggleHelpOverlay);
// 视频信息显示快捷键
QShortcut *videoInfoShortcut = new QShortcut(QKeySequence("V"), this);
connect(videoInfoShortcut, &QShortcut::activated, this, &VideoPlayer::toggleVideoInfoOverlay);
}
void VideoPlayer::adaptWindowToVideo()
{
if (!m_videoCodecContext) return;
int videoWidth = m_videoCodecContext->width;
int videoHeight = m_videoCodecContext->height;
// 获取屏幕尺寸
QScreen *screen = QApplication::primaryScreen();
QRect screenGeometry = screen->availableGeometry();
int screenWidth = screenGeometry.width();
int screenHeight = screenGeometry.height();
// 计算合适的窗口尺寸(保持纵横比)
int windowWidth = videoWidth;
int windowHeight = videoHeight;
// 如果视频尺寸超过屏幕的80%,则缩放
double maxWidth = screenWidth * 0.8;
double maxHeight = screenHeight * 0.8;
if (windowWidth > maxWidth || windowHeight > maxHeight) {
double scaleX = maxWidth / windowWidth;
double scaleY = maxHeight / windowHeight;
double scale = qMin(scaleX, scaleY);
windowWidth = (int)(windowWidth * scale);
windowHeight = (int)(windowHeight * scale);
}
// 确保最小尺寸
windowWidth = qMax(320, windowWidth);
windowHeight = qMax(240, windowHeight);
// 设置窗口尺寸并居中
resize(windowWidth, windowHeight);
// 居中显示
int x = (screenWidth - windowWidth) / 2;
int y = (screenHeight - windowHeight) / 2;
move(x, y);
// Window adapted to video size
}
void VideoPlayer::openFile()
{
// 临时隐藏覆盖层,避免覆盖文件选择器
if (m_helpOverlay) {
m_helpOverlay->temporaryHide();
}
if (m_videoInfoOverlay) {
m_videoInfoOverlay->temporaryHide();
}
QString filename = QFileDialog::getOpenFileName(this,
"Select Video File", "",
"Video Files (*.mp4 *.avi *.mkv *.mov *.wmv *.flv);;All Files (*.*)");
// 恢复覆盖层显示状态
if (m_helpOverlay) {
m_helpOverlay->restoreFromTemporaryHide();
}
if (m_videoInfoOverlay) {
m_videoInfoOverlay->restoreFromTemporaryHide();
}
if (!filename.isEmpty()) {
openVideo(filename);
}
}
void VideoPlayer::openNetworkUrl()
{
// 临时隐藏覆盖层,避免覆盖输入对话框
if (m_helpOverlay) {
m_helpOverlay->temporaryHide();
}
if (m_videoInfoOverlay) {
m_videoInfoOverlay->temporaryHide();
}
// 使用新的网络流UI对话框
m_streamUI->setStatus("就绪");
if (m_streamUI->exec() == QDialog::Accepted) {
// 对话框中的连接请求会通过信号处理
// 这里不需要额外处理
}
// 恢复覆盖层显示状态
if (m_helpOverlay) {
m_helpOverlay->restoreFromTemporaryHide();
}
if (m_videoInfoOverlay) {
m_videoInfoOverlay->restoreFromTemporaryHide();
}
}
void VideoPlayer::openNetworkVideo(const QString &url)
{
// Starting async network video loading
// 关闭当前视频
closeVideo();
// 设置网络流标志
m_isNetworkStream = true;
// 如果已经在加载,取消之前的加载
if (m_streamLoader->isLoading()) {
m_streamLoader->cancelLoading();
}
// 设置当前文件URL
m_currentFile = url;
// 开始异步加载
m_streamLoader->loadStreamAsync(url, 15000); // 15秒超时
}
bool VideoPlayer::isNetworkUrl(const QString &path)
{
return path.startsWith("http://", Qt::CaseInsensitive) ||
path.startsWith("https://", Qt::CaseInsensitive) ||
path.startsWith("rtmp://", Qt::CaseInsensitive) ||
path.startsWith("rtsp://", Qt::CaseInsensitive);
}
bool VideoPlayer::openVideo(const QString &filename)
{
closeVideo(); // 使用正确的方法名
// 检测是否为网络流
m_isNetworkStream = filename.startsWith("http://") || filename.startsWith("https://") ||
filename.startsWith("rtmp://") || filename.startsWith("rtsp://");
if (m_isNetworkStream) {
qDebug() << "Opening network stream:" << filename;
} else {
qDebug() << "Opening local file:" << filename;
}
QByteArray ba = filename.toUtf8();
closeVideo();
m_currentFile = filename;
// 打开视频文件 - 使用UTF-8编码支持中文路径
if (avformat_open_input(&m_formatContext, ba.constData(), nullptr, nullptr) != 0) {
QMessageBox::critical(this, "Error", QString("Cannot open video file: %1").arg(filename));
return false;
}
// 继续视频打开流程
continueVideoOpening();
return true;
}
void VideoPlayer::continueVideoOpening()
{
// 获取流信息
if (avformat_find_stream_info(m_formatContext, nullptr) < 0) {
QMessageBox::critical(this, "Error", "Cannot get stream info");
closeVideo();
return;
}
// 查找视频流和音频流
m_videoStreamIndex = -1;
m_audioStreamIndex = -1;
for (unsigned int i = 0; i < m_formatContext->nb_streams; i++) {
if (m_formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && m_videoStreamIndex == -1) {
m_videoStreamIndex = i;
} else if (m_formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && m_audioStreamIndex == -1) {
m_audioStreamIndex = i;
}
}
if (m_videoStreamIndex == -1) {
QMessageBox::critical(this, "Error", "No video stream found");
closeVideo();
return;
}
// 设置视频解码器
AVStream *videoStream = m_formatContext->streams[m_videoStreamIndex];
const AVCodec *videoCodec = avcodec_find_decoder(videoStream->codecpar->codec_id);
if (!videoCodec) {
QMessageBox::critical(this, "Error", "Video decoder not found");
closeVideo();
return;
}
m_videoCodecContext = avcodec_alloc_context3(videoCodec);
if (avcodec_parameters_to_context(m_videoCodecContext, videoStream->codecpar) < 0) {
QMessageBox::critical(this, "Error", "Cannot set video decoder parameters");
closeVideo();
return;
}
if (avcodec_open2(m_videoCodecContext, videoCodec, nullptr) < 0) {
QMessageBox::critical(this, "Error", "Cannot open video decoder");
closeVideo();
return;
}
// 设置音频解码器(如果有音频流)
if (m_audioStreamIndex != -1) {
AVStream *audioStream = m_formatContext->streams[m_audioStreamIndex];
const AVCodec *audioCodec = avcodec_find_decoder(audioStream->codecpar->codec_id);
if (audioCodec) {
m_audioCodecContext = avcodec_alloc_context3(audioCodec);
if (avcodec_parameters_to_context(m_audioCodecContext, audioStream->codecpar) >= 0) {
if (avcodec_open2(m_audioCodecContext, audioCodec, nullptr) >= 0) {
setupAudio();
} else {
qDebug() << "Cannot open audio decoder, playing video only";
avcodec_free_context(&m_audioCodecContext);
m_audioCodecContext = nullptr;
}
} else {
qDebug() << "Cannot set audio decoder parameters, playing video only";
avcodec_free_context(&m_audioCodecContext);
m_audioCodecContext = nullptr;
}
} else {
qDebug() << "Audio decoder not found, playing video only";
}
}
// 分配帧和包
m_videoFrame = av_frame_alloc();
m_audioFrame = av_frame_alloc();
m_packet = av_packet_alloc();
// 获取视频信息
m_duration = m_formatContext->duration;
m_fps = av_q2d(videoStream->r_frame_rate);
// 保存视频原始尺寸和宽高比
m_originalVideoSize = QSize(m_videoCodecContext->width, m_videoCodecContext->height);
m_aspectRatio = (double)m_videoCodecContext->width / m_videoCodecContext->height;
// UI组件已移除,无需更新UI状态
// 自动适配窗口大小到视频尺寸
adaptWindowToVideo();
// 自动开始播放
playPause();
QString displayName = isNetworkUrl(m_currentFile) ? "网络视频" : m_currentFile;
qDebug() << "Video opened successfully:" << displayName;
qDebug() << "Video size:" << m_videoCodecContext->width << "x" << m_videoCodecContext->height;
qDebug() << "FPS:" << m_fps;
qDebug() << "Duration:" << (m_duration / AV_TIME_BASE) << "seconds";
}
void VideoPlayer::setupAudio()
{
if (!m_audioCodecContext) return;
// 创建新的音频处理器
m_audioProcessor = new AudioProcessor(this);
// 连接音频处理器信号 - 使用队列连接避免递归
connect(m_audioProcessor, &AudioProcessor::audioTimeChanged,
this, [this](int64_t timestamp) {
// 更新音频时钟用于同步
syncAudioVideo();
}, Qt::QueuedConnection);
connect(m_audioProcessor, &AudioProcessor::bufferStatusChanged,
this, [this](int bufferLevel, int maxBuffer) {
// 移除缓冲状态日志,减少输出噪音
}, Qt::QueuedConnection);
connect(m_audioProcessor, &AudioProcessor::audioError,
this, [this](const QString& error) {
qDebug() << "Audio error:" << error;
// 可选:显示错误消息给用户
}, Qt::QueuedConnection);
// 初始化音频处理器
if (!m_audioProcessor->initialize(m_audioCodecContext)) {
qDebug() << "Failed to initialize audio processor";
delete m_audioProcessor;
m_audioProcessor = nullptr;
return;
}
// 设置音频流信息用于精确时间计算
if (m_audioStreamIndex >= 0) {
m_audioProcessor->setAudioStreamInfo(m_formatContext->streams[m_audioStreamIndex]);
}
// 设置音量
m_audioProcessor->setVolume(m_volume);
qDebug() << "Audio system initialized successfully";
}
void VideoPlayer::cleanupAudio()
{
if (m_audioProcessor) {
m_audioProcessor->cleanup();
delete m_audioProcessor;
m_audioProcessor = nullptr;
}
}
void VideoPlayer::closeVideo()
{
if (m_isPlaying) {
m_timer->stop();
m_isPlaying = false;
m_isPaused = false;
}
cleanupAudio();
if (m_videoFrame) {
av_frame_free(&m_videoFrame);
m_videoFrame = nullptr;
}
if (m_audioFrame) {
av_frame_free(&m_audioFrame);
m_audioFrame = nullptr;
}
if (m_packet) {
av_packet_free(&m_packet);
m_packet = nullptr;
}
if (m_videoCodecContext) {
avcodec_free_context(&m_videoCodecContext);
m_videoCodecContext = nullptr;
}
if (m_audioCodecContext) {
avcodec_free_context(&m_audioCodecContext);
m_audioCodecContext = nullptr;
}
if (m_formatContext) {
avformat_close_input(&m_formatContext);
m_formatContext = nullptr;
}
m_videoStreamIndex = -1;
m_audioStreamIndex = -1;
m_currentPosition = 0;
m_duration = 0;
// 清理视频显示
m_videoWidget->clearFrame();
}
void VideoPlayer::playPause()
{
if (!m_formatContext) return;
if (m_isPlaying) {
pauseVideo();
} else {
playVideo();
}
}
void VideoPlayer::playVideo()
{
if (!m_formatContext) return;
m_isPlaying = true;
// 重置播放稳定性状态
m_isPlaybackStable = false;
m_frameCount = 0;
m_playStartTime = QTime::currentTime();
// 重置同步状态
m_lastSyncTime = 0;
m_syncAdjustmentCount = 0;
// 启动音频处理器 - 区分首次播放和从暂停恢复
if (m_audioProcessor) {
if (m_isPaused) {
// 从暂停状态恢复
m_audioProcessor->resume();
} else {
// 首次播放或重新播放
m_audioProcessor->start();
}
}
m_isPaused = false;
// 启动高频定时器 - 追求最佳视觉体验
int interval = qMax(8, (int)(1000.0 / m_fps)); // 最小8ms,支持120fps+
m_timer->start(interval);
}
void VideoPlayer::pauseVideo()
{
m_isPlaying = false;
m_isPaused = true;
m_timer->stop();
// 暂停音频处理器
if (m_audioProcessor) {
m_audioProcessor->pause();
}
}
void VideoPlayer::stop()
{
if (!m_formatContext) return;
m_timer->stop();
m_isPlaying = false;
m_isPaused = false;
// 重置播放稳定性状态
m_isPlaybackStable = false;
m_frameCount = 0;
// 停止音频处理器
if (m_audioProcessor) {
m_audioProcessor->stop();
}
// 重置到开头
av_seek_frame(m_formatContext, m_videoStreamIndex, 0, AVSEEK_FLAG_BACKWARD);
m_currentPosition = 0;
m_videoWidget->clearFrame();
}
void VideoPlayer::seek(int position)
{
if (!m_formatContext) return;
QMutexLocker locker(&m_seekMutex);
// 检查是否有正在进行的seek操作
if (m_isSeeking && !m_seekDebounceTimer->isActive()) {
qDebug() << "Seek ignored - another seek operation in progress";
return;
}
// 简化的防抖逻辑 - 只防止真正的快速连击
QTime currentTime = QTime::currentTime();
if (m_lastSeekTime.isValid()) {
int timeDiff = m_lastSeekTime.msecsTo(currentTime);
// 只对极快的连击(<20ms)使用防抖,这种情况通常是意外的
if (timeDiff < 20) {
m_pendingSeekPosition = position;
m_hasPendingSeek = true;
// 重启防抖定时器
m_seekDebounceTimer->stop();
m_seekDebounceTimer->start();
qDebug() << "Seek debounced - position:" << position << "timeDiff:" << timeDiff << "ms";
return;
}
}
// 如果没有频繁操作,直接执行seek
m_lastSeekTime = currentTime;
performSeek(position);
}
void VideoPlayer::performSeek(int position)
{
if (!m_formatContext) return;
// 强制保护 - 如果已经在seek中,忽略后续请求
if (m_isSeeking) {
qDebug() << "PerformSeek ignored - already seeking";
return;
}
// 边界检查 - 确保position在有效范围内
int maxPosition = m_duration / AV_TIME_BASE;
if (position < 0) position = 0;
if (position > maxPosition) position = maxPosition;
qDebug() << "PerformSeek start - Position:" << position
<< "Current:" << (m_currentPosition / AV_TIME_BASE)
<< "Max:" << maxPosition;
// 立即设置seek状态,防止任何干扰
m_isSeeking = true;
// 暂时停止定时器,避免冲突
bool wasPlaying = m_isPlaying;
if (m_isPlaying) {
m_timer->stop();
}
int64_t seekTarget = (int64_t)position * AV_TIME_BASE;
// 执行seek操作
bool seekSuccess = false;
// 对于小步长的seek(15秒以内),尝试更精确的策略
int currentPos = m_currentPosition / AV_TIME_BASE;
int seekDistance = abs(position - currentPos);
if (seekDistance <= 15) {
// 小距离:尝试精确seek
seekSuccess = (av_seek_frame(m_formatContext, -1, seekTarget, 0) >= 0);
} else {
// 大距离:使用关键帧seek
seekSuccess = (av_seek_frame(m_formatContext, -1, seekTarget, AVSEEK_FLAG_BACKWARD) >= 0);
}
if (seekSuccess) {
// 清理解码器缓冲区,避免显示旧帧
if (m_videoCodecContext) {
avcodec_flush_buffers(m_videoCodecContext);
}
if (m_audioCodecContext) {
avcodec_flush_buffers(m_audioCodecContext);
}
// 通知音频处理器进行seek
if (m_audioProcessor) {
m_audioProcessor->seek(seekTarget);
qDebug() << "Audio processor seek completed";
}
// 简化的帧查找逻辑
int attempts = 0;
bool foundFrame = false;
while (attempts < 10 && !foundFrame) {
if (av_read_frame(m_formatContext, m_packet) >= 0) {
if (m_packet->stream_index == m_videoStreamIndex) {
int ret = avcodec_send_packet(m_videoCodecContext, m_packet);
if (ret >= 0) {
ret = avcodec_receive_frame(m_videoCodecContext, m_videoFrame);
if (ret == 0) {
// 显示视频帧
m_videoWidget->displayFrame(m_videoFrame, m_videoCodecContext->width, m_videoCodecContext->height);
// 更新位置
if (m_videoFrame->pts != AV_NOPTS_VALUE) {
AVStream *stream = m_formatContext->streams[m_videoStreamIndex];
m_currentPosition = av_rescale_q(m_videoFrame->pts, stream->time_base, AV_TIME_BASE_Q);
} else {
m_currentPosition = seekTarget;
}
foundFrame = true;
}
}
}
av_packet_unref(m_packet);
} else {
break; // 文件结束
}
attempts++;
}
// 如果没找到帧,使用目标位置
if (!foundFrame) {
m_currentPosition = seekTarget;
}
// UI组件已移除,无需更新UI
qDebug() << "Seek completed - Target:" << position << "s, Actual:" << (m_currentPosition / AV_TIME_BASE) << "s, Distance:" << seekDistance << "s";
} else {
qDebug() << "Seek failed for position:" << position;
}
// 恢复播放状态
if (wasPlaying) {
m_timer->start(1000.0 / m_fps);
}
// 清除seek状态 - 确保状态重置
m_isSeeking = false;
qDebug() << "PerformSeek completed - Final position:" << (m_currentPosition / AV_TIME_BASE) << "s";
}
void VideoPlayer::updatePosition()
{
if (!m_isPlaying || !m_formatContext || m_isSeeking) return;
// 只需要解码帧,UI组件已移除
decodeFrame();
}
bool VideoPlayer::decodeFrame()
{
if (!m_formatContext || !m_videoCodecContext) return false;
bool videoFrameDecoded = false;
while (av_read_frame(m_formatContext, m_packet) >= 0) {
if (m_packet->stream_index == m_videoStreamIndex) {
int ret = avcodec_send_packet(m_videoCodecContext, m_packet);
if (ret < 0) {
av_packet_unref(m_packet);
continue;
}
ret = avcodec_receive_frame(m_videoCodecContext, m_videoFrame);
if (ret == 0) {
// 显示视频帧
m_videoWidget->displayFrame(m_videoFrame, m_videoCodecContext->width, m_videoCodecContext->height);
// 更新当前位置
if (m_videoFrame->pts != AV_NOPTS_VALUE) {
AVStream *stream = m_formatContext->streams[m_videoStreamIndex];
m_currentPosition = av_rescale_q(m_videoFrame->pts, stream->time_base, AV_TIME_BASE_Q);
}
// 跟踪播放稳定性 - 快速稳定,提高响应性
m_frameCount++;
if (!m_isPlaybackStable && m_frameCount >= 5) {
m_isPlaybackStable = true;
// 移除播放稳定性日志,减少输出
}
videoFrameDecoded = true;
// 不要在这里return,继续处理可能的音频包
}
} else if (m_packet->stream_index == m_audioStreamIndex && m_audioCodecContext && m_isPlaying) {
// 发送音频包到音频处理器
if (m_audioProcessor) {
m_audioProcessor->processAudioPacket(m_packet);
}
}