| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063 |
- #include "playercontroller.h"
- #include "common.h"
- #include <QApplication>
- #include <QElapsedTimer>
- #include <QStatusBar>
- #include <cassert>
- #include <memory>
- #include "audio_decode_thread.h"
- #include "audio_effect_helper.h"
- #include "audio_play_thread.h"
- #include "ffmpeg_init.h"
- #include "play_control_window.h"
- #include "read_thread.h"
- #include "start_play_thread.h"
- #include "stopplay_waiting_thread.h"
- #include "subtitle_decode_thread.h"
- #include "video_decode_thread.h"
- #include "video_play_thread.h"
- #include "video_state.h"
- Q_LOGGING_CATEGORY(playerControllerLog, "player.controller")
- PlayerController::PlayerController(QWidget* parent)
- : QObject(parent)
- {
- ffmpeg_init();
- m_state = PlayerState::Idle;
- }
- PlayerController::~PlayerController()
- {
- if (m_initThread.joinable()) {
- m_initThread.join();
- }
- stopPlay();
- }
- void PlayerController::startToPlay(const QString& file)
- {
- // 使用局部变量保存当前状态,避免在锁外使用成员变量
- PlayerState currentState = m_state;
- QString currentFile = m_currentFile;
- {
- std::lock_guard<std::mutex> lock(m_stopMutex);
- qCDebug(playerControllerLog) << "[PlayerController] m_state" << (int) m_state.load();
-
- // 自愈:如果状态为Playing但所有线程都已退出,强制Idle
- if (m_state == PlayerState::Playing && areAllThreadsStopped()) {
- stopAndResetThreads();
- m_videoState.reset();
- m_currentFile.clear();
- m_state = PlayerState::Idle;
- qCDebug(playerControllerLog)
- << "[PlayerController] All threads stopped, force reset to Idle.";
- }
-
- currentState = m_state;
- currentFile = m_currentFile;
- }
- // 初始化中,忽略新请求
- if (currentState == PlayerState::Initializing) {
- qCDebug(playerControllerLog) << "Player is initializing. Ignoring request.";
- return;
- }
- // 正在播放中,检查是否需要切换文件
- if (currentState == PlayerState::Playing) {
- // if (currentFile == file) {
- // qCDebug(playerControllerLog) << "Already playing the same file. Ignoring request.";
- // return;
- // } else
- {
- qCDebug(playerControllerLog)
- << "Player is busy with another file, stopping and switching to:" << file;
- // 在锁外调用stopPlay,避免死锁
- stopPlay();
- // 停止后重新获取状态
- currentState = PlayerState::Idle; // 假设stopPlay会将状态设为Idle
- }
- }
- // 空闲状态,开始新播放
- if (currentState == PlayerState::Idle) {
- std::lock_guard<std::mutex> lock(m_stopMutex);
-
- // 再次检查状态,确保在获取锁的过程中状态没有改变
- if (m_state != PlayerState::Idle) {
- qCDebug(playerControllerLog) << "State changed while waiting for lock. Current state:" << (int)m_state.load();
- return;
- }
-
- // 确保所有线程已停止
- if (!areAllThreadsStopped()) {
- qCDebug(playerControllerLog) << "Some threads still running, stopping them first";
- stopAndResetThreads();
- }
- // 重置状态
- m_videoState.reset();
- m_currentFile.clear();
- qCDebug(playerControllerLog) << "Player is idle. Starting playback for:" << file;
- m_state = PlayerState::Initializing;
- m_currentFile = file;
- // 启动异步初始化线程
- if (m_initThread.joinable()) {
- m_initThread.join();
- }
- m_initThread = std::thread(&PlayerController::asyncInit, this, file);
- }
- }
- void PlayerController::asyncInit(const QString& file)
- {
- bool success = false;
- QElapsedTimer timer;
- timer.start();
- qCDebug(playerControllerLog) << "[Init] asyncInit started";
- // 检查文件有效性
- if (file.isEmpty()) {
- qCWarning(playerControllerLog) << "Filename is invalid. Please select a valid media file.";
- success = false;
- } else {
- // 检查文件是否存在和可访问
- // QFileInfo fileInfo(file);
- // if (!fileInfo.exists() || !fileInfo.isReadable()) {
- // qCWarning(playerControllerLog)
- // << "File does not exist or is not readable:" << toNativePath(file);
- // success = false;
- // } else {
- // qCInfo(playerControllerLog) << "File check passed:" << toNativePath(file);
- // success = true;
- // }
- success = true;
- }
- m_initSuccess = success;
- onAsyncInitFinished(file, success);
- qCDebug(playerControllerLog) << "[Init] asyncInit finished in " << timer.elapsed() << " ms";
- }
- void PlayerController::onAsyncInitFinished(const QString& file, bool success)
- {
- // 移除互斥锁,避免与stopPlay产生死锁
- QElapsedTimer timer;
- timer.start();
- // 初始化失败处理
- if (!success) {
- playFailed(m_currentFile);
- m_state = PlayerState::Idle;
- return;
- }
- // 创建视频状态对象
- qCDebug(playerControllerLog) << "[Init] createVideoState...";
- if (!createVideoState(m_currentFile)) {
- qCWarning(playerControllerLog) << "Video state creation failed";
- readPacketStopped();
- playFailed(m_currentFile);
- m_state = PlayerState::Idle;
- return;
- }
- // 检查状态有效性
- assert(m_videoState);
- if (!m_videoState) {
- qCWarning(playerControllerLog) << "Video state initialization error";
- playFailed(m_currentFile);
- m_state = PlayerState::Idle;
- return;
- }
- // 创建数据包读取线程
- qCDebug(playerControllerLog) << "[Init] createReadThread...";
- if (!createReadThread()) {
- qCWarning(playerControllerLog) << "Packet read thread creation failed";
- playFailed(m_currentFile);
- m_state = PlayerState::Idle;
- return;
- }
- // 设置视频状态
- m_packetReadThread->set_video_state(m_videoState->get_state());
- // 检查媒体流类型
- const bool hasVideo = playingHasVideo();
- const bool hasAudio = playingHasAudio();
- const bool hasSubtitle = playingHasSubtitle();
- // 创建视频相关线程
- if (hasVideo) {
- if (!createDecodeVideoThread() || !createVideoPlayThread()) {
- qCWarning(playerControllerLog) << "Video processing setup failed";
- playFailed(m_currentFile);
- stopPlay();
- m_state = PlayerState::Idle;
- return;
- }
- }
- // 创建音频相关线程
- if (hasAudio) {
- if (!createDecodeAudioThread() || !createAudioPlayThread()) {
- qCWarning(playerControllerLog) << "Audio processing setup failed";
- playFailed(m_currentFile);
- stopPlay();
- m_state = PlayerState::Idle;
- return;
- }
- }
- // 创建字幕线程
- if (hasSubtitle && !createDecodeSubtitleThread()) {
- qCWarning(playerControllerLog) << "Subtitle processing setup failed";
- playFailed(m_currentFile);
- stopPlay();
- m_state = PlayerState::Idle;
- return;
- }
- // 开始播放
- if (hasAudio) {
- startPlayThread(); // 异步启动(处理音频设备初始化)
- } else {
- playStarted(); // 同步启动(无音频流)
- }
- emit startToPlaySignal();
- m_state = PlayerState::Playing;
- qCDebug(playerControllerLog) << "Playback initialized in " << timer.elapsed() << " ms";
- }
- void PlayerController::stopPlay()
- {
- // 移除互斥锁,避免与startToPlay中的锁冲突
- if (m_state == PlayerState::Idle)
- return;
- qCDebug(playerControllerLog) << "Stopping playback...";
- m_state = PlayerState::Stopping;
- // 停止并重置所有线程
- stopAndResetThreads();
- // 清理视频状态
- m_videoState.reset();
- m_currentFile.clear();
- m_state = PlayerState::Idle;
- qCDebug(playerControllerLog) << "Playback stopped.";
- }
- void PlayerController::pausePlay()
- {
- if (!m_videoState)
- return;
- if (auto state = m_videoState->get_state())
- toggle_pause(state, !state->paused);
- emit updatePlayControlStatus();
- }
- void PlayerController::playMute(bool mute)
- {
- if (!m_videoState)
- return;
- if (auto state = m_videoState->get_state())
- toggle_mute(state, mute);
- }
- void PlayerController::playStartSeek()
- {
- pausePlay();
- }
- void PlayerController::playSeekPre()
- {
- videoSeekInc(-0.5); // 将步长从2秒减小到0.5秒,提高精度
- }
- void PlayerController::playSeekNext()
- {
- videoSeekInc(0.5); // 将步长从2秒减小到0.5秒,提高精度
- }
- void PlayerController::setVolume(int volume, int maxValue)
- {
- if (!m_audioPlayThread)
- return;
- const float vol = static_cast<float>(volume) / maxValue;
- m_audioPlayThread->set_device_volume(vol);
- }
- void PlayerController::setPlaySpeed(double speed)
- {
- if (m_videoState) {
- if (auto state = m_videoState->get_state()) {
- #if USE_AVFILTER_AUDIO
- set_audio_playspeed(state, speed);
- #endif
- }
- }
- }
- // 状态访问接口
- QString PlayerController::playingFile() const
- {
- return isPlaying() ? m_currentFile : QString();
- }
- bool PlayerController::isPlaying() const
- {
- // 不仅检查状态标志,还检查线程是否实际运行
- if (m_state != PlayerState::Playing) {
- return false;
- }
- // 如果状态是Playing但所有线程都已停止,则实际上不是在播放状态
- if (areAllThreadsStopped()) {
- qCDebug(playerControllerLog) << "[isPlaying] State is Playing but all threads stopped";
- return false;
- }
- return true;
- }
- bool PlayerController::playingHasVideo()
- {
- return m_videoState ? m_videoState->has_video() : false;
- }
- bool PlayerController::playingHasAudio()
- {
- return m_videoState ? m_videoState->has_audio() : false;
- }
- bool PlayerController::playingHasSubtitle()
- {
- return m_videoState ? m_videoState->has_subtitle() : false;
- }
- VideoState* PlayerController::state()
- {
- return m_videoState ? m_videoState->get_state() : nullptr;
- }
- float PlayerController::deviceVolume() const
- {
- return m_audioPlayThread ? m_audioPlayThread->get_device_volume() : 0.0f;
- }
- void PlayerController::setDeviceVolume(float volume)
- {
- if (m_audioPlayThread)
- m_audioPlayThread->set_device_volume(volume);
- }
- // 播放状态回调槽函数
- void PlayerController::playStarted(bool success)
- {
- if (!success) {
- qCWarning(playerControllerLog) << "Audio device initialization failed!";
- return;
- }
- allThreadStart();
- setThreads();
- }
- void PlayerController::playFailed(const QString& file)
- {
- dump();
- qCWarning(playerControllerLog) << "Playback failed for file:" << toNativePath(file);
- // 确保状态一致性
- if (m_state != PlayerState::Idle) {
- // 检查线程状态并重置
- if (!areAllThreadsStopped()) {
- qCDebug(playerControllerLog) << "Some threads still running, stopping them first";
- stopAndResetThreads();
- }
- }
- emit showMessage(QString("Playback failed: %1").arg(toNativePath(file)), "Warning", "");
- }
- // 线程 finished 槽函数只做日志和信号
- void PlayerController::readPacketStopped()
- {
- dump();
- qCDebug(playerControllerLog) << "************* Read packets thread stopped signal received.";
- // 不在这里调用delete_video_state,避免与stopAndResetThreads中的调用重复
- // 资源清理统一由stopAndResetThreads处理
-
- emit audioStopped();
- }
- void PlayerController::decodeVideoStopped()
- {
- dump();
- qCDebug(playerControllerLog) << "************* Video decode thread stopped.";
- }
- void PlayerController::decodeAudioStopped()
- {
- dump();
- qCDebug(playerControllerLog) << "************* Audio decode thread stopped.";
- }
- void PlayerController::decodeSubtitleStopped()
- {
- dump();
- qCDebug(playerControllerLog) << "************* Subtitle decode thread stopped.";
- }
- void PlayerController::audioPlayStopped()
- {
- dump();
- qCDebug(playerControllerLog) << "************* Audio play thread stopped.";
- emit audioStopped();
- }
- void PlayerController::videoPlayStopped()
- {
- dump();
- qCDebug(playerControllerLog) << "************* Video play thread stopped.";
- emit videoStopped();
- }
- // 线程管理槽函数
- void PlayerController::setThreads()
- {
- if (!m_videoState)
- return;
- Threads threads;
- threads.read_tid = m_packetReadThread.get();
- threads.video_decode_tid = m_decodeVideoThread.get();
- threads.audio_decode_tid = m_decodeAudioThread.get();
- threads.video_play_tid = m_videoPlayThread.get();
- threads.audio_play_tid = m_audioPlayThread.get();
- threads.subtitle_decode_tid = m_decodeSubtitleThread.get();
- m_videoState->threads_setting(m_videoState->get_state(), threads);
- }
- void PlayerController::startSendData(bool send)
- {
- if (m_audioPlayThread)
- m_audioPlayThread->send_visual_open(send);
- }
- void PlayerController::videoSeek(double position, double increment)
- {
- if (!m_videoState)
- return;
- auto state = m_videoState->get_state();
- if (!state)
- return;
- if (state->ic->start_time != AV_NOPTS_VALUE
- && position < state->ic->start_time / static_cast<double>(AV_TIME_BASE)) {
- position = state->ic->start_time / static_cast<double>(AV_TIME_BASE);
- }
- // 边界检查:防止seek到超出视频时长的位置
- double max_position = state->ic->duration / static_cast<double>(AV_TIME_BASE);
- if (state->ic->start_time != AV_NOPTS_VALUE)
- max_position += state->ic->start_time / static_cast<double>(AV_TIME_BASE);
- qDebug() << "[videoSeek] 边界检查: position=" << position << ", max_position=" << max_position
- << ", duration=" << state->ic->duration << ", start_time=" << state->ic->start_time;
- // 更保守的边界检查:减去3秒作为安全边界
- double safe_boundary = 3.0;
- if (position > max_position - safe_boundary) {
- qDebug() << "[videoSeek] 调整seek位置: 原始position=" << position
- << ", 最大position=" << max_position;
- position = max_position - safe_boundary;
- if (position < 0)
- position = 0;
- qDebug() << "[videoSeek] 调整后position=" << position;
- }
- // 添加量化操作,精确到0.01秒
- qDebug() << "position:" << position
- << "position * AV_TIME_BASE:" << static_cast<int64_t>(position * AV_TIME_BASE)
- << "increment * AV_TIME_BASE:" << static_cast<int64_t>(increment * AV_TIME_BASE);
- // 启用精确帧定位
- int64_t target_pts = static_cast<int64_t>(position * AV_TIME_BASE);
- // if (state->video_st) {
- // // 将目标时间转换为视频流的时间基准
- // target_pts = av_rescale_q(target_pts,
- // AV_TIME_BASE_Q,
- // state->video_st->time_base);
- // qDebug() << "[精确帧定位] 设置目标PTS:" << target_pts
- // << "原始位置(秒):" << position
- // << "视频时间基准:" << state->video_st->time_base.num << "/" << state->video_st->time_base.den;
- // state->exact_seek = 1;
- // state->target_pts = target_pts;
- // }
- stream_seek(state,
- static_cast<int64_t>(position * AV_TIME_BASE),
- static_cast<int64_t>(increment * AV_TIME_BASE),
- 0);
- }
- void PlayerController::videoSeekEx(double value, double maxValue)
- {
- if (!m_videoState)
- return;
- auto state = m_videoState->get_state();
- if (!state)
- return;
- auto cur_stream = state;
- auto x = value;
- double frac;
- if (m_videoState->seekByBytes() || cur_stream->ic->duration <= 0) {
- uint64_t size = avio_size(cur_stream->ic->pb);
- stream_seek(cur_stream, size * x / maxValue, 0, 1);
- } else {
- int64_t ts;
- int ns, hh, mm, ss;
- int tns, thh, tmm, tss;
- tns = cur_stream->ic->duration / 1000000LL;
- thh = tns / 3600;
- tmm = (tns % 3600) / 60;
- tss = (tns % 60);
- frac = x / maxValue;
- ns = frac * tns;
- hh = ns / 3600;
- mm = (ns % 3600) / 60;
- ss = (ns % 60);
- av_log(NULL,
- AV_LOG_INFO,
- "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n",
- frac * 100,
- hh,
- mm,
- ss,
- thh,
- tmm,
- tss);
- qDebug("Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d)",
- frac * 100,
- hh,
- mm,
- ss,
- thh,
- tmm,
- tss);
- ts = frac * cur_stream->ic->duration;
- if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
- ts += cur_stream->ic->start_time;
- // 边界检查:防止seek到超出视频时长的位置
- int64_t max_ts = cur_stream->ic->duration;
- if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
- max_ts += cur_stream->ic->start_time;
- qDebug() << "[videoSeekEx] 边界检查: ts=" << ts << ", max_ts=" << max_ts
- << ", duration=" << cur_stream->ic->duration
- << ", start_time=" << cur_stream->ic->start_time
- << ", 请求位置(秒)=" << ts / (double) AV_TIME_BASE
- << ", 最大位置(秒)=" << max_ts / (double) AV_TIME_BASE;
- // 更保守的边界检查:减去3秒作为安全边界
- int64_t safe_boundary = 3 * AV_TIME_BASE;
- if (ts > max_ts - safe_boundary) {
- qDebug() << "[videoSeekEx] 调整seek位置: 原始ts=" << ts << ", 最大ts=" << max_ts;
- ts = max_ts - safe_boundary;
- if (ts < 0)
- ts = 0;
- qDebug() << "[videoSeekEx] 调整后ts=" << ts
- << ", 调整后位置(秒)=" << ts / (double) AV_TIME_BASE;
- }
- // // 启用精确帧定位
- // if (cur_stream->video_st) {
- // int64_t target_pts = av_rescale_q(ts,
- // AV_TIME_BASE_Q,
- // cur_stream->video_st->time_base);
- // qDebug() << "[精确帧定位Ex] 设置目标PTS:" << target_pts
- // << "原始位置(秒):" << ts / (double)AV_TIME_BASE
- // << "视频时间基准:" << cur_stream->video_st->time_base.num << "/" << cur_stream->video_st->time_base.den;
- // state->exact_seek = 1;
- // state->target_pts = target_pts;
- // }
- stream_seek(cur_stream, ts, 0, 0);
- }
- return;
- }
- // 线程管理辅助方法
- void PlayerController::stopAndResetThreads()
- {
- qDebug() << "++++++++++ stopAndResetThreads";
- auto stopAndReset = [](auto& threadPtr, const QString& threadName) {
- if (threadPtr) {
- qCDebug(playerControllerLog)
- << "[stopAndReset] [" << threadName
- << "] try stop/join thread, isRunning=" << threadPtr->isRunning();
- threadPtr->stop();
- // 添加超时等待机制
- const int MAX_WAIT_MS = 500; // 最多等待500毫秒
- auto startTime = std::chrono::steady_clock::now();
- while (threadPtr->isRunning()) {
- auto now = std::chrono::steady_clock::now();
- auto elapsed
- = std::chrono::duration_cast<std::chrono::milliseconds>(now - startTime).count();
- if (elapsed > MAX_WAIT_MS) {
- qCWarning(playerControllerLog)
- << "[stopAndReset] [" << threadName << "] Thread stop timeout after"
- << elapsed << "ms";
- break;
- }
- std::this_thread::sleep_for(std::chrono::milliseconds(10));
- }
- // 只有线程已停止才join
- if (!threadPtr->isRunning()) {
- threadPtr->join();
- qCDebug(playerControllerLog)
- << "[stopAndReset] [" << threadName << "] thread joined and will reset.";
- }
- threadPtr.reset();
- }
- };
- // 按依赖顺序停止线程
- stopAndReset(m_beforePlayThread, "BeforePlay");
- stopAndReset(m_videoPlayThread, "VideoPlay");
- stopAndReset(m_audioPlayThread, "AudioPlay");
- // 解码前先 关闭流 不然会卡死异常
- // 注意:这里是唯一调用delete_video_state的地方,readPacketStopped不再调用
- // 以避免重复关闭导致的异常
- if (m_videoState && m_videoState->get_state()) {
- m_videoState->delete_video_state();
- }
- stopAndReset(m_packetReadThread, "PacketRead");
- stopAndReset(m_decodeVideoThread, "DecodeVideo");
- stopAndReset(m_decodeAudioThread, "DecodeAudio");
- stopAndReset(m_decodeSubtitleThread, "DecodeSubtitle");
- }
- bool PlayerController::areAllThreadsStopped() const
- {
- // 检查所有线程是否已停止
- return (!m_packetReadThread || !m_packetReadThread->isRunning())
- && (!m_decodeVideoThread || !m_decodeVideoThread->isRunning())
- && (!m_decodeAudioThread || !m_decodeAudioThread->isRunning())
- && (!m_audioPlayThread || !m_audioPlayThread->isRunning())
- && (!m_videoPlayThread || !m_videoPlayThread->isRunning())
- && (!m_decodeSubtitleThread || !m_decodeSubtitleThread->isRunning());
- }
- void PlayerController::allThreadStart()
- {
- // 启动所有创建的线程
- if (m_packetReadThread) {
- if (!m_videoState || !m_videoState->get_state()) {
- qCWarning(playerControllerLog) << "VideoState invalid, skip starting read thread";
- } else {
- m_packetReadThread->start();
- }
- qCDebug(playerControllerLog) << "++++++++++ Read packets thread started";
- }
- if (m_decodeVideoThread) {
- m_decodeVideoThread->start();
- qCDebug(playerControllerLog) << "++++++++++ Video decode thread started";
- }
- if (m_decodeAudioThread) {
- m_decodeAudioThread->start();
- qCDebug(playerControllerLog) << "++++++++++ Audio decode thread started";
- }
- if (m_decodeSubtitleThread) {
- m_decodeSubtitleThread->start();
- qCDebug(playerControllerLog) << "++++++++++ Subtitle decode thread started";
- }
- if (m_videoPlayThread) {
- m_videoPlayThread->start();
- qCDebug(playerControllerLog) << "++++++++++ Video play thread started";
- }
- if (m_audioPlayThread) {
- m_audioPlayThread->start();
- qCDebug(playerControllerLog) << "++++++++++ Audio play thread started";
- }
- // 通知UI更新
- emit setPlayControlWnd(true);
- emit updatePlayControlVolume();
- emit updatePlayControlStatus();
- }
- // 辅助函数
- void PlayerController::videoSeekInc(double increment)
- {
- if (!m_videoState)
- return;
- auto state = m_videoState->get_state();
- if (!state)
- return;
- double position = get_master_clock(state);
- if (std::isnan(position)) {
- position = static_cast<double>(state->seek_pos) / AV_TIME_BASE;
- }
- position += increment;
- videoSeek(position, increment);
- }
- // 线程创建方法
- bool PlayerController::createVideoState(const QString& file)
- {
- const bool useHardware = false; // 待实现:来自UI设置
- const bool loop = false; // 待实现:来自UI设置
- if (m_videoState)
- return false;
- m_videoState = std::make_unique<VideoStateData>(useHardware, loop);
- const int ret = m_videoState->create_video_state(file.toUtf8().constData());
- if (ret < 0) {
- m_videoState.reset();
- qCWarning(playerControllerLog) << "Video state creation failed (error: " << ret << ")";
- return false;
- }
- return true;
- }
- bool PlayerController::createReadThread()
- {
- if (m_packetReadThread)
- return false;
- m_packetReadThread = std::make_unique<ReadThread>(m_videoState ? m_videoState->get_state()
- : nullptr);
- m_packetReadThread->setOnFinished([this]() { readPacketStopped(); });
- return true;
- }
- bool PlayerController::createDecodeVideoThread()
- {
- if (!m_videoState || m_decodeVideoThread)
- return false;
- auto state = m_videoState->get_state();
- if (!state)
- return false;
- m_decodeVideoThread = std::make_unique<VideoDecodeThread>(state);
- m_decodeVideoThread->setOnFinished([this]() { decodeVideoStopped(); });
- auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
- // 初始化视频解码器
- int ret = decoder_init(&state->viddec,
- codecContext,
- &state->videoq,
- state->continue_read_thread);
- if (ret < 0) {
- qCWarning(playerControllerLog)
- << "Video decoder initialization failed (error: " << ret << ")";
- return false;
- }
- ret = decoder_start(&state->viddec, m_decodeVideoThread.get(), "video_decoder");
- if (ret < 0) {
- qCWarning(playerControllerLog) << "Video decoder start failed (error: " << ret << ")";
- return false;
- }
- state->queue_attachments_req = 1;
- return true;
- }
- bool PlayerController::createDecodeAudioThread()
- {
- if (!m_videoState || m_decodeAudioThread)
- return false;
- auto state = m_videoState->get_state();
- if (!state)
- return false;
- m_decodeAudioThread = std::make_unique<AudioDecodeThread>(state);
- m_decodeAudioThread->setOnFinished([this]() { decodeAudioStopped(); });
- auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_AUDIO);
- // 初始化音频解码器
- int ret = decoder_init(&state->auddec,
- codecContext,
- &state->audioq,
- state->continue_read_thread);
- if (ret < 0) {
- qCWarning(playerControllerLog)
- << "Audio decoder initialization failed (error: " << ret << ")";
- return false;
- }
- ret = decoder_start(&state->auddec, m_decodeAudioThread.get(), "audio_decoder");
- if (ret < 0) {
- qCWarning(playerControllerLog) << "Audio decoder start failed (error: " << ret << ")";
- return false;
- }
- return true;
- }
- bool PlayerController::createDecodeSubtitleThread()
- {
- if (!m_videoState || m_decodeSubtitleThread)
- return false;
- auto state = m_videoState->get_state();
- if (!state)
- return false;
- m_decodeSubtitleThread = std::make_unique<SubtitleDecodeThread>(state);
- m_decodeSubtitleThread->setOnFinished([this]() { decodeSubtitleStopped(); });
- auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_SUBTITLE);
- // 初始化字幕解码器
- int ret = decoder_init(&state->subdec,
- codecContext,
- &state->subtitleq,
- state->continue_read_thread);
- if (ret < 0) {
- qCWarning(playerControllerLog)
- << "Subtitle decoder initialization failed (error: " << ret << ")";
- return false;
- }
- ret = decoder_start(&state->subdec, m_decodeSubtitleThread.get(), "subtitle_decoder");
- if (ret < 0) {
- qCWarning(playerControllerLog) << "Subtitle decoder start failed (error: " << ret << ")";
- return false;
- }
- return true;
- }
- bool PlayerController::createVideoPlayThread()
- {
- if (!m_videoState || m_videoPlayThread)
- return false;
- auto state = m_videoState->get_state();
- if (!state)
- return false;
- m_videoPlayThread = std::make_unique<VideoPlayThread>(state);
- m_videoPlayThread->setOnFinished([this]() { videoPlayStopped(); });
- m_videoPlayThread->setOnFrameReady([this](AVFrame* frame) { this->onFrameReady(frame); });
- m_videoPlayThread->setOnSubtitleReady([](const QString& text) {
- // onSubtitleReady(text);
- });
- // 初始化参数
- auto videoContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
- const bool useHardware = m_videoState->is_hardware_decode();
- if (!m_videoPlayThread->init_resample_param(videoContext, useHardware)) {
- qCWarning(playerControllerLog) << "Video resample parameters initialization failed";
- return false;
- }
- return true;
- }
- bool PlayerController::createAudioPlayThread()
- {
- if (!m_videoState || m_audioPlayThread)
- return false;
- auto state = m_videoState->get_state();
- if (!state)
- return false;
- m_audioPlayThread = std::make_unique<AudioPlayThread>(state);
- m_audioPlayThread->setOnFinished([this]() { audioPlayStopped(); });
- m_audioPlayThread->setOnUpdatePlayTime([this]() {
- // TODO: 实现 PlayerController::onUpdatePlayTime() 处理播放时间更新
- emit updatePlayTime();
- });
- m_audioPlayThread->setOnDataVisualReady([this](const AudioData& data) {
- // 异步 ?
- emit audioData(data);
- });
- // 音频设备初始化在独立线程中完成
- return true;
- }
- bool PlayerController::startPlayThread()
- {
- if (m_beforePlayThread)
- return false;
- m_beforePlayThread = std::make_unique<StartPlayThread>(m_audioPlayThread.get(),
- m_videoState.get());
- m_beforePlayThread->setOnFinished([this]() {
- qCDebug(playerControllerLog) << "[StartPlayThread] finished, call playStarted()";
- playStarted();
- });
- m_beforePlayThread->start();
- qCDebug(playerControllerLog) << "++++++++++ StartPlay thread (audio init) started";
- return true;
- }
- // 调试辅助函数
- void PlayerController::printDecodeContext(const AVCodecContext* codecCtx, bool isVideo) const
- {
- if (!codecCtx)
- return;
- qCInfo(playerControllerLog) << (isVideo ? "Video" : "Audio")
- << " codec: " << codecCtx->codec->name;
- qCInfo(playerControllerLog) << " Type:" << codecCtx->codec_type << "ID:" << codecCtx->codec_id
- << "Tag:" << codecCtx->codec_tag;
- if (isVideo) {
- qCInfo(playerControllerLog)
- << " Dimensions: " << codecCtx->width << "x" << codecCtx->height;
- } else {
- qCInfo(playerControllerLog) << " Sample rate: " << codecCtx->sample_rate
- << " Hz, Channels: " << codecCtx->ch_layout.nb_channels
- << ", Format: " << codecCtx->sample_fmt;
- qCInfo(playerControllerLog) << " Frame size: " << codecCtx->frame_size
- << ", Block align: " << codecCtx->block_align;
- }
- }
- // 在合适位置实现 onFrameReady
- void PlayerController::onFrameReady(AVFrame* frame)
- {
- // 这里可以做帧处理、缓存、同步等操作
- emit frameReady(frame); // 直接转发给 UI 层
- }
- void PlayerController::dump() const
- {
- qCInfo(playerControllerLog) << "=== PlayerController Thread Status Dump ===";
- qCInfo(playerControllerLog) << "Current State:" << static_cast<int>(m_state.load());
- qCInfo(playerControllerLog) << "Current File:" << m_currentFile;
- // 检查数据包读取线程
- if (m_packetReadThread) {
- qCInfo(playerControllerLog)
- << "ReadThread: exists, isRunning:" << m_packetReadThread->isRunning()
- << ", isFinished:" << m_packetReadThread->isExit();
- } else {
- qCInfo(playerControllerLog) << "ReadThread: null";
- }
- // 检查视频解码线程
- if (m_decodeVideoThread) {
- qCInfo(playerControllerLog)
- << "VideoDecodeThread: exists, isRunning:" << m_decodeVideoThread->isRunning()
- << ", isFinished:" << m_decodeVideoThread->isExit();
- } else {
- qCInfo(playerControllerLog) << "VideoDecodeThread: null";
- }
- // 检查音频解码线程
- if (m_decodeAudioThread) {
- qCInfo(playerControllerLog)
- << "AudioDecodeThread: exists, isRunning:" << m_decodeAudioThread->isRunning()
- << ", isFinished:" << m_decodeAudioThread->isExit();
- } else {
- qCInfo(playerControllerLog) << "AudioDecodeThread: null";
- }
- // 检查字幕解码线程
- if (m_decodeSubtitleThread) {
- qCInfo(playerControllerLog)
- << "SubtitleDecodeThread: exists, isRunning:" << m_decodeSubtitleThread->isRunning()
- << ", isFinished:" << m_decodeSubtitleThread->isExit();
- } else {
- qCInfo(playerControllerLog) << "SubtitleDecodeThread: null";
- }
- // 检查音频播放线程
- if (m_audioPlayThread) {
- qCInfo(playerControllerLog)
- << "AudioPlayThread: exists, isRunning:" << m_audioPlayThread->isRunning()
- << ", isFinished:" << m_audioPlayThread->isExit();
- } else {
- qCInfo(playerControllerLog) << "AudioPlayThread: null";
- }
- // 检查视频播放线程
- if (m_videoPlayThread) {
- qCInfo(playerControllerLog)
- << "VideoPlayThread: exists, isRunning:" << m_videoPlayThread->isRunning()
- << ", isFinished:" << m_videoPlayThread->isExit();
- } else {
- qCInfo(playerControllerLog) << "VideoPlayThread: null";
- }
- // 检查播放前准备线程
- if (m_beforePlayThread) {
- qCInfo(playerControllerLog)
- << "StartPlayThread: exists, isRunning:" << m_beforePlayThread->isRunning()
- << ", isFinished:" << m_beforePlayThread->isExit();
- } else {
- qCInfo(playerControllerLog) << "StartPlayThread: null";
- }
- // 检查初始化线程
- if (m_initThread.joinable()) {
- qCInfo(playerControllerLog) << "InitThread: joinable (running)";
- } else {
- qCInfo(playerControllerLog) << "InitThread: not joinable (stopped or not started)";
- }
- // 检查事件线程
- if (m_eventThread.joinable()) {
- qCInfo(playerControllerLog) << "EventThread: joinable (running)";
- } else {
- qCInfo(playerControllerLog) << "EventThread: not joinable (stopped or not started)";
- }
- qCInfo(playerControllerLog) << "=== End of Thread Status Dump ===";
- }
|