-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFFMpegDecoder.cpp
More file actions
786 lines (697 loc) · 25.3 KB
/
Copy pathFFMpegDecoder.cpp
File metadata and controls
786 lines (697 loc) · 25.3 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
#include "FFMpegDecoder.h"
#include <chrono>
namespace {
AVFramePtr make_avframe() { return AVFramePtr(av_frame_alloc()); }
AVPacketPtr make_avpacket() { return AVPacketPtr(av_packet_alloc()); }
AVCodecContextPtr make_avcodec_ctx(AVCodec *codec) {
return AVCodecContextPtr(avcodec_alloc_context3(codec));
}
// 查找解码器
AVCodec *find_decoder(AVCodecID id, AVMediaType type) {
AVCodec *iter = av_codec_next(nullptr);
while (iter) {
if (iter->id == id && iter->decode != nullptr && iter->type == type) {
if (QString(iter->name).contains("rk", Qt::CaseInsensitive)) {
iter = av_codec_next(iter);
continue;
}
return iter;
}
iter = av_codec_next(iter);
}
return nullptr;
}
} // namespace
// 构造函数,初始化 FFMpegDecoder 对象
FFMpegDecoder::FFMpegDecoder(QObject *parent) : QObject(parent) {
// 注册所有的 FFMpeg 组件
av_register_all();
// 注册 QSharedPointer<QImage> 类型,以便在信号槽中使用
qRegisterMetaType<QSharedPointer<QImage>>("QSharedPointer<QImage>");
}
FFMpegDecoder::~FFMpegDecoder() { stop(); }
void FFMpegDecoder::start(const QString &path) {
// 停止解码器
stop();
// 设置解码器路径
m_path = path;
// 设置停止标志为 false
m_stop = false;
// 设置暂停标志为 false
m_pause = false;
// 设置 seek 标志为 false
m_seeking = false;
// 设置视频 seek 处理标志为 false
m_videoSeekHandled = false;
// 设置音频 seek 处理标志为 false
m_audioSeekHandled = false;
// 设置 eof 标志为 false
m_eof = false;
// 创建视频解码线程
m_videoThread = std::thread(&FFMpegDecoder::videoDecodeLoop, this);
// 创建音频解码线程
m_audioThread = std::thread(&FFMpegDecoder::audioDecodeLoop, this);
}
void FFMpegDecoder::stop() {
m_stop = true;
m_eof = false;
m_cond.notify_all();
if (m_videoThread.joinable())
m_videoThread.join();
if (m_audioThread.joinable())
m_audioThread.join();
}
void FFMpegDecoder::seek(qint64 ms) {
m_seekTarget = ms;
m_seeking = true;
m_videoSeekHandled = false;
m_audioSeekHandled = false;
m_eof = false;
m_cond.notify_all();
}
void FFMpegDecoder::togglePause() {
m_pause = !m_pause;
if (!m_pause) {
// 从暂停状态恢复时,重置音频同步器以确保平滑播放
m_cond.notify_all();
}
}
bool FFMpegDecoder::isPaused() const { return m_pause; }
void FFMpegDecoder::setAudioTrack(int index) {
std::lock_guard<std::mutex> lk(m_mutex);
if (index < -1 || index >= static_cast<int>(m_audioStreamIndices.size()))
return;
if (m_audioTrackIndex != index) {
// 保存当前播放位置
qint64 currentPosition = m_audioClockMs.load();
m_audioTrackIndex = index;
m_seeking = true;
m_seekTarget = currentPosition; // 使用保存的位置作为seek目标
m_videoSeekHandled = false;
m_audioSeekHandled = false;
m_eof = false;
m_cond.notify_all();
}
}
int FFMpegDecoder::audioTrackCount() const {
return static_cast<int>(m_audioStreamIndices.size());
}
int FFMpegDecoder::currentAudioTrack() const { return m_audioTrackIndex; }
QString FFMpegDecoder::audioTrackName(int idx) const {
if (idx < 0 || idx >= static_cast<int>(m_audioStreamNames.size()))
return QString();
return m_audioStreamNames[idx];
}
void FFMpegDecoder::setVideoTrack(int index) {
std::lock_guard<std::mutex> lk(m_mutex);
// 允许 index == -1,表示空轨道
if (index < -1 || index >= static_cast<int>(m_videoStreamIndices.size()))
return;
if (m_videoTrackIndex != index) {
// 保存当前播放位置
qint64 currentPosition = m_audioClockMs.load();
m_videoTrackIndex = index;
if (index == -1) {
m_seeking = true;
m_seekTarget = currentPosition; // 使用保存的位置作为seek目标
m_videoSeekHandled = false;
m_cond.notify_all();
emit frameReady(QSharedPointer<QImage>());
} else {
m_seeking = true;
m_seekTarget = currentPosition; // 使用保存的位置作为seek目标
m_videoSeekHandled = false;
m_audioSeekHandled = false;
m_eof = false;
m_cond.notify_all();
}
}
}
int FFMpegDecoder::videoTrackCount() const {
return static_cast<int>(m_videoStreamIndices.size());
}
int FFMpegDecoder::currentVideoTrack() const { return m_videoTrackIndex; }
QString FFMpegDecoder::videoTrackName(int idx) const {
if (idx < 0 || idx >= static_cast<int>(m_videoStreamNames.size()))
return QString();
return m_videoStreamNames[idx];
}
void FFMpegDecoder::videoDecodeLoop() {
while (!m_stop) {
// 打开输入文件
AVFormatContext *raw_fmt_ctx = nullptr;
AVDictionary *opts = nullptr;
av_dict_set(&opts, "probe_size", "1048576", 0);
av_dict_set(&opts, "analyzeduration", "1000000", 0);
if (avformat_open_input(&raw_fmt_ctx, m_path.toUtf8().constData(), nullptr,
&opts) < 0) {
qWarning() << "Failed to open input file:" << m_path;
emit errorOccurred(tr("无法打开文件: %1").arg(m_path));
av_dict_free(&opts);
return;
}
av_dict_free(&opts);
AVFormatContextPtr fmt_ctx(raw_fmt_ctx);
if (avformat_find_stream_info(fmt_ctx.get(), nullptr) < 0) {
qWarning() << "Failed to get stream info";
emit errorOccurred(tr("无法获取媒体流信息"));
return;
}
// 获取所有视频流索引和名称
m_videoStreamIndices.clear();
m_videoStreamNames.clear();
for (unsigned i = 0; i < fmt_ctx->nb_streams; i++) {
AVCodecParameters *p = fmt_ctx->streams[i]->codecpar;
if (p->codec_type == AVMEDIA_TYPE_VIDEO) {
m_videoStreamIndices.push_back(i);
QString name = QString("Track %1").arg(m_videoStreamIndices.size());
if (fmt_ctx->streams[i]->metadata) {
AVDictionaryEntry *lang = av_dict_get(fmt_ctx->streams[i]->metadata,
"language", nullptr, 0);
if (lang && lang->value)
name += QString(" [%1]").arg(lang->value);
}
m_videoStreamNames.push_back(name);
}
}
if (m_videoTrackIndex >= static_cast<int>(m_videoStreamIndices.size()))
m_videoTrackIndex = m_videoStreamIndices.empty() ? -1 : 0;
// 简化为主循环:统一处理空轨道和视频轨道
qint64 duration_ms =
fmt_ctx->duration >= 0 ? fmt_ctx->duration / (AV_TIME_BASE / 1000) : 0;
emit durationChanged(duration_ms);
// 资源初始化(移出循环)
AVCodec *vcodec = nullptr;
AVCodecContextPtr vctx;
int vwidth = 0, vheight = 0;
AVRational vtime_base = {0, 1};
int sws_src_pix_fmt = -1;
SwsContext *sws_ctx = nullptr;
int rgb_stride = 0;
uint8_t *rgb_buf = nullptr;
int rgb_buf_size = 0;
AVPacketPtr pkt = make_avpacket();
AVFramePtr frame = make_avframe();
using clock = std::chrono::steady_clock;
clock::time_point playback_start_time = clock::now();
while (!m_stop) {
// 获取当前视频轨道索引
int vid_idx = -1;
{
std::lock_guard<std::mutex> lk(m_mutex);
if (m_videoTrackIndex >= 0 &&
m_videoTrackIndex < static_cast<int>(m_videoStreamIndices.size()))
vid_idx = m_videoStreamIndices[m_videoTrackIndex];
}
// 处理空轨道
if (vid_idx < 0) {
// 清空画面
emit frameReady(QSharedPointer<QImage>());
// 暂停或等待状态变化
if (m_pause) {
std::unique_lock<std::mutex> lk(m_mutex);
m_cond.wait(lk, [&] {
return m_stop || !m_pause || m_seeking || m_videoTrackIndex != -1;
});
if (m_stop)
break;
}
// 处理 seek
if (m_seeking) {
m_audioClockMs.store(m_seekTarget);
std::lock_guard<std::mutex> lk(m_mutex);
m_videoSeekHandled = true;
if (m_audioSeekHandled)
m_seeking = false;
continue;
}
// 推进位置(基于音频时钟)
emit positionChanged(m_audioClockMs.load());
std::this_thread::sleep_for(std::chrono::milliseconds(40));
continue;
}
// 初始化/重置视频解码资源(如果轨道变化)
if (!vctx || vid_idx !=
m_videoStreamIndices
[m_videoTrackIndex]) { // 假设轨道变化时重新初始化
vcodec = find_decoder(fmt_ctx->streams[vid_idx]->codecpar->codec_id,
AVMEDIA_TYPE_VIDEO);
if (!vcodec) {
qWarning() << "Video decoder not found";
emit errorOccurred(tr("未找到视频解码器"));
break;
}
vctx = make_avcodec_ctx(vcodec);
if (!vctx) {
qWarning() << "Failed to allocate video decoder context";
emit errorOccurred(tr("无法分配视频解码器上下文"));
break;
}
if (avcodec_parameters_to_context(
vctx.get(), fmt_ctx->streams[vid_idx]->codecpar) < 0) {
qWarning() << "Failed to copy video decoder parameters";
emit errorOccurred(tr("无法复制视频解码器参数"));
break;
}
if (avcodec_open2(vctx.get(), vcodec, nullptr) < 0) {
qWarning() << "Failed to open video decoder";
emit errorOccurred(tr("无法打开视频解码器"));
break;
}
vwidth = vctx->width;
vheight = vctx->height;
vtime_base = fmt_ctx->streams[vid_idx]->time_base;
if (sws_ctx)
sws_freeContext(sws_ctx);
sws_ctx = nullptr;
if (rgb_buf)
av_free(rgb_buf);
rgb_buf = nullptr;
rgb_buf_size = 0;
if (vwidth && vheight) {
rgb_buf_size =
av_image_get_buffer_size(AV_PIX_FMT_RGB24, vwidth, vheight, 1);
rgb_buf = (uint8_t *)av_malloc(rgb_buf_size);
}
}
// 暂停处理
if (m_pause) {
std::unique_lock<std::mutex> lk(m_mutex);
m_cond.wait(lk, [&] { return m_stop || !m_pause || m_seeking; });
if (m_stop)
break;
playback_start_time = clock::now();
}
// 跳转处理
if (m_seeking) {
int64_t ts = m_seekTarget * (AV_TIME_BASE / 1000);
av_seek_frame(fmt_ctx.get(), -1, ts, AVSEEK_FLAG_BACKWARD);
avcodec_flush_buffers(vctx.get());
playback_start_time = clock::now();
av_packet_unref(pkt.get());
av_frame_unref(frame.get());
{
std::lock_guard<std::mutex> lk(m_mutex);
m_videoSeekHandled = true;
if (m_audioSeekHandled)
m_seeking = false;
}
continue;
}
// 读取视频帧
if (av_read_frame(fmt_ctx.get(), pkt.get()) < 0) {
m_eof = true;
std::unique_lock<std::mutex> lk(m_mutex);
m_cond.wait_for(lk, std::chrono::milliseconds(50),
[&] { return m_stop || m_seeking || m_eof == false; });
if (m_stop)
break;
if (m_seeking) {
m_eof = false;
continue;
}
continue;
}
// 判断是否为视频流
if (pkt->stream_index != vid_idx) {
av_packet_unref(pkt.get());
continue;
}
// 发送视频帧到解码器
avcodec_send_packet(vctx.get(), pkt.get());
// 接收解码后的视频帧
while (!m_stop && !m_seeking &&
avcodec_receive_frame(vctx.get(), frame.get()) == 0) {
double speed = m_playbackSpeed.load();
int64_t pts = frame->best_effort_timestamp;
if (pts == AV_NOPTS_VALUE)
pts = frame->pts;
if (pts == AV_NOPTS_VALUE)
pts = 0;
int64_t ms = pts * vtime_base.num * 1000LL / vtime_base.den;
qint64 audioClock = m_audioClockMs.load();
qint64 diff = ms - audioClock;
bool hasAudio = (m_audioTrackIndex != -1);
int frame_interval = 40;
if (vctx->framerate.num && vctx->framerate.den) {
frame_interval = 1000 * vctx->framerate.den / vctx->framerate.num;
frame_interval = std::max(10, std::min(frame_interval, 80));
}
int max_wait = frame_interval * 2;
// 倍速播放时使用跳帧策略
static int frameSkipCounter = 0;
if (speed > 1.0) {
// 计算跳帧间隔,速度越快跳帧越多
int skipInterval = static_cast<int>(speed);
if (frameSkipCounter++ % skipInterval != 0) {
// 跳过当前帧,但更新时钟
if (!hasAudio) {
static qint64 last_video_pts = 0;
static auto last_wall_clock = clock::now();
static float last_video_speed = 1.0f;
float speed = m_playbackSpeed.load();
bool speed_changed = fabs(speed - last_video_speed) > 0.1f;
if (speed_changed) {
last_video_pts = 0;
last_video_speed = speed;
}
if (last_video_pts == 0 || ms < last_video_pts || speed_changed) {
last_video_pts = ms;
last_wall_clock = clock::now();
} else {
qint64 pts_diff = ms - last_video_pts;
auto now = clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_wall_clock).count();
if (!m_stop && !m_seeking && !m_pause && elapsed < pts_diff / speed) {
std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int>((pts_diff / speed) - elapsed)));
}
if (!m_stop && !m_seeking) {
last_video_pts = ms;
last_wall_clock = clock::now();
}
}
}
av_frame_unref(frame.get());
continue;
}
} else {
frameSkipCounter = 0; // 正常速度时重置跳帧计数器
}
if (hasAudio && audioClock > 0) {
if (diff > frame_interval) {
int waited = 0;
if (diff > 20 && waited < max_wait && !m_stop && !m_pause &&
!m_seeking) {
int sleep_time = static_cast<int>(diff * 0.8 / speed);
std::this_thread::sleep_for(
std::chrono::milliseconds(sleep_time));
waited += sleep_time;
audioClock = m_audioClockMs.load();
diff = ms - audioClock;
}
while (diff > 5 && waited < max_wait && !m_stop && !m_pause &&
!m_seeking) {
std::this_thread::sleep_for(std::chrono::milliseconds(5));
waited += 5;
audioClock = m_audioClockMs.load();
diff = ms - audioClock;
}
if (m_stop || m_seeking || m_pause)
break;
if (diff > frame_interval)
continue;
} else if (diff < -frame_interval * 6) {
continue;
}
}
if (!hasAudio) {
static qint64 last_video_pts = 0;
static auto last_wall_clock = clock::now();
static float last_video_speed = 1.0f;
float speed = m_playbackSpeed.load(); // 加入倍速控制
// 检测速度变化,如果速度变化超过阈值,重置视频同步参考点
bool speed_changed = fabs(speed - last_video_speed) > 0.1f;
if (speed_changed) {
last_video_pts = 0; // 强制重置参考点
last_video_speed = speed;
}
if (last_video_pts == 0 || ms < last_video_pts || speed_changed) {
last_video_pts = ms;
last_wall_clock = clock::now();
} else {
qint64 pts_diff = ms - last_video_pts;
auto now = clock::now();
auto elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(
now - last_wall_clock)
.count();
if (!m_stop && !m_seeking && !m_pause &&
elapsed < pts_diff / speed) {
std::this_thread::sleep_for(std::chrono::milliseconds(
static_cast<int>((pts_diff / speed) - elapsed)));
}
if (!m_stop && !m_seeking) {
last_video_pts = ms;
last_wall_clock = clock::now();
}
}
}
if (m_stop || m_seeking)
break;
// 初始化 SwsContext
if (!sws_ctx || sws_src_pix_fmt != frame->format ||
frame->width != vwidth || frame->height != vheight) {
if (sws_ctx)
sws_freeContext(sws_ctx);
vwidth = frame->width;
vheight = frame->height;
rgb_stride = vwidth * 3;
int new_buf_size =
av_image_get_buffer_size(AV_PIX_FMT_RGB24, vwidth, vheight, 1);
if (new_buf_size != rgb_buf_size) {
if (rgb_buf)
av_free(rgb_buf);
rgb_buf = (uint8_t *)av_malloc(new_buf_size);
rgb_buf_size = new_buf_size;
}
sws_ctx = sws_getCachedContext(
nullptr, vwidth, vheight, (AVPixelFormat)frame->format, vwidth,
vheight, AV_PIX_FMT_RGB24, SWS_BILINEAR, nullptr, nullptr,
nullptr);
sws_src_pix_fmt = frame->format;
if (!sws_ctx)
continue;
}
if (!rgb_buf) {
rgb_buf_size =
av_image_get_buffer_size(AV_PIX_FMT_RGB24, vwidth, vheight, 1);
rgb_buf = (uint8_t *)av_malloc(rgb_buf_size);
if (!rgb_buf)
continue;
}
// 转换格式
uint8_t *dst[1] = {rgb_buf};
int dst_linesize[1] = {rgb_stride};
sws_scale(sws_ctx, frame->data, frame->linesize, 0, vheight, dst,
dst_linesize);
// 创建 QImage
struct RGBBufferDeleter {
void operator()(QImage *img) { delete img; }
};
QSharedPointer<QImage> imgPtr;
if (rgb_buf) {
QImage *rawImg = new QImage(
rgb_buf, vwidth, vheight, rgb_stride, QImage::Format_RGB888,
[](void *buf) { av_free(buf); }, rgb_buf);
if (!rawImg->isNull()) {
imgPtr = QSharedPointer<QImage>(rawImg, RGBBufferDeleter());
rgb_buf = nullptr;
} else {
delete rawImg;
QImage tempImg(rgb_buf, vwidth, vheight, rgb_stride,
QImage::Format_RGB888);
imgPtr = QSharedPointer<QImage>(new QImage(tempImg.copy()));
av_free(rgb_buf);
rgb_buf = nullptr;
}
}
emit frameReady(imgPtr);
emit positionChanged(ms);
}
av_packet_unref(pkt.get());
}
// 清理资源
if (rgb_buf)
av_free(rgb_buf);
if (sws_ctx)
sws_freeContext(sws_ctx);
}
}
void FFMpegDecoder::setPlaybackSpeed(float speed) {
// 限制播放速度范围在 0.25 - 4.0 之间
float newSpeed = std::max(0.25f, std::min(speed, 4.0f));
float oldSpeed = m_playbackSpeed.load();
// 只有当速度真正变化时才更新和发送信号
if (fabs(newSpeed - oldSpeed) > 0.01f) {
m_playbackSpeed.store(newSpeed);
}
}
// ===== 音频解码循环:工具函数 =====
bool FFMpegDecoder::openInputFile(AVFormatContextPtr &m_fmtCtx) {
AVDictionary *opts = nullptr;
av_dict_set(&opts, "probe_size", "1048576", 0);
av_dict_set(&opts, "analyzeduration", "1000000", 0);
AVFormatContext *raw_fmt_ctx = nullptr;
if (avformat_open_input(&raw_fmt_ctx, m_path.toUtf8().constData(), nullptr,
&opts) < 0) {
qWarning() << "Failed to open input file:" << m_path;
emit errorOccurred(tr("无法打开文件: %1").arg(m_path));
av_dict_free(&opts);
return false;
}
av_dict_free(&opts);
m_fmtCtx.reset(raw_fmt_ctx);
if (avformat_find_stream_info(m_fmtCtx.get(), nullptr) < 0) {
qWarning() << "Failed to get stream info";
emit errorOccurred(tr("无法获取媒体流信息"));
return false;
}
return true;
}
void FFMpegDecoder::scanAudioStreams(AVFormatContextPtr &m_fmtCtx) {
std::lock_guard<std::mutex> lk(m_mutex);
m_audioStreamIndices.clear();
m_audioStreamNames.clear();
for (unsigned i = 0; i < m_fmtCtx->nb_streams; i++) {
if (m_fmtCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
m_audioStreamIndices.push_back(i);
QString name = QString("Track %1").arg(m_audioStreamIndices.size());
AVDictionaryEntry *lang =
av_dict_get(m_fmtCtx->streams[i]->metadata, "language", nullptr, 0);
if (lang && lang->value)
name += QString(" [%1]").arg(lang->value);
m_audioStreamNames.push_back(name);
}
}
if (m_audioTrackIndex >= static_cast<int>(m_audioStreamIndices.size())) {
m_audioTrackIndex = m_audioStreamIndices.empty() ? -1 : 0;
}
}
bool FFMpegDecoder::initDecoder(int streamIndex, AVCodecContextPtr &actx,
SwrBuffer &resampler, AVRational &timeBase) {
AVStream *stream = m_fmtCtx->streams[streamIndex];
const AVCodec *acodec = avcodec_find_decoder(stream->codecpar->codec_id);
if (!acodec) {
qWarning() << "Audio decoder not found";
return false;
}
AVCodecContext *new_ctx = avcodec_alloc_context3(acodec);
if (!new_ctx)
return false;
actx.reset(new_ctx);
if (avcodec_parameters_to_context(actx.get(), stream->codecpar) < 0)
return false;
if (avcodec_open2(actx.get(), acodec, nullptr) < 0)
return false;
if (actx->channel_layout == 0)
actx->channel_layout = av_get_default_channel_layout(actx->channels);
timeBase = stream->time_base;
return resampler.init(actx.get());
}
bool FFMpegDecoder::handlePauseOrSeek(AVCodecContextPtr &actx) {
if (m_pause) {
std::unique_lock<std::mutex> lk(m_mutex);
m_cond.wait(lk, [&] { return m_stop || !m_pause || m_seeking; });
// 从暂停恢复时,不需要额外处理,同步器会处理时间参考点
return true;
}
if (m_seeking) {
int64_t ts = m_seekTarget * (AV_TIME_BASE / 1000);
// 使用更精确的 seek 标志,提高 seek 准确性
av_seek_frame(m_fmtCtx.get(), -1, ts, AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY);
if (actx) {
avcodec_flush_buffers(actx.get());
}
// 立即更新音频时钟,避免等待下一帧
m_audioClockMs.store(m_seekTarget);
m_audioSeekHandled = true;
if (m_videoSeekHandled)
m_seeking = false;
return true;
}
return false;
}
void FFMpegDecoder::emitSilence() {
static QByteArray silence(2048, 0);
emit audioReady(silence);
std::this_thread::sleep_for(std::chrono::milliseconds(23));
}
int FFMpegDecoder::getCurrentAudioStream() {
std::lock_guard<std::mutex> lk(m_mutex);
if (m_audioTrackIndex >= 0 &&
m_audioTrackIndex < int(m_audioStreamIndices.size()))
return m_audioStreamIndices[m_audioTrackIndex];
return -1;
}
void FFMpegDecoder::handleEOF() {
m_eof = true;
std::unique_lock<std::mutex> lk(m_mutex);
m_cond.wait_for(lk, std::chrono::milliseconds(50),
[&] { return m_stop || m_seeking || m_eof == false; });
if (m_seeking)
m_eof = false;
}
// 音频解码循环:主循环
void FFMpegDecoder::audioDecodeLoop() {
if (!openInputFile(m_fmtCtx))
return;
scanAudioStreams(m_fmtCtx);
AVCodecContextPtr actx = nullptr;
AVPacketPtr pkt = make_avpacket();
AVFramePtr frame = make_avframe();
SwrBuffer resampler;
AudioSynchronizer synchronizer;
int lastStream = -1;
AVRational timeBase = {1, 1000};
while (!m_stop) {
if (handlePauseOrSeek(actx)) {
synchronizer.reset(m_playbackSpeed.load());
// seek 后清空当前帧,避免播放旧数据
av_frame_unref(frame.get());
av_packet_unref(pkt.get());
continue;
}
int streamId = getCurrentAudioStream();
if (streamId < 0) {
emitSilence();
continue;
}
if (!actx || streamId != lastStream) {
if (!initDecoder(streamId, actx, resampler, timeBase))
break;
lastStream = streamId;
synchronizer.reset(m_playbackSpeed.load());
}
if (av_read_frame(m_fmtCtx.get(), pkt.get()) < 0) {
handleEOF();
continue;
}
if (pkt->stream_index != streamId) {
av_packet_unref(pkt.get());
continue;
}
if (avcodec_send_packet(actx.get(), pkt.get()) < 0) {
av_packet_unref(pkt.get());
continue;
}
av_packet_unref(pkt.get());
while (!m_stop) {
// 解码音频帧
int ret = avcodec_receive_frame(actx.get(), frame.get());
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
break;
if (ret < 0 || frame->nb_samples == 0)
break;
int64_t pts = frame->pts != AV_NOPTS_VALUE ? frame->pts
: frame->best_effort_timestamp;
int64_t ms = av_rescale_q(pts, timeBase, {1, 1000});
m_audioClockMs.store(ms);
// 音频同步
synchronizer.sync(ms, m_playbackSpeed.load());
// 重采样音频
int outSamples = av_rescale_rnd(
swr_get_delay(resampler.ctx(), actx->sample_rate) + frame->nb_samples,
OUT_SAMPLE_RATE, actx->sample_rate, AV_ROUND_UP);
uint8_t **out = resampler.getBuffer(outSamples);
int converted =
swr_convert(resampler.ctx(), out, outSamples,
(const uint8_t **)frame->data, frame->nb_samples);
int dataSize = av_samples_get_buffer_size(nullptr, OUT_CHANNELS,
converted, OUT_SAMPLE_FMT, 1);
QByteArray pcm = QByteArray::fromRawData((const char *)out[0], dataSize);
emit audioReady(pcm);
emit positionChanged(ms);
av_frame_unref(frame.get());
}
}
}