Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
Add shared demux session for network and server sources (C2/C3/C4/C7 core)
Veyra Goal Agentc6d933c8bd56
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 3d73abd9..4f2d85b7 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -497,6 +497,7 @@ endif()if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformat.h")add_library(veyra_media STATICsrc/media/FFmpegDemuxer.cpp+ src/media/DemuxSession.cppsrc/media/FFmpegVideoDecoder.cppsrc/media/FFmpegDeinterlacer.cpp)@@ -562,7 +563,8 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_include_directories(veyra_sinks PRIVATE "${VEYRA_NVENC_HEADERS_ROOT}/include")target_compile_definitions(veyra_sinks PRIVATE VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")add_dependencies(veyra_sinks veyra_shader_rgb_nv12)- target_link_libraries(veyra_sinks PUBLIC veyra_base veyra_gfx ole32 windowscodecs mmdevapi avrt mfplat mfuuid mf)+ # veyra_media: AudioPipeline reads packets from the shared network demux session (#48).+ target_link_libraries(veyra_sinks PUBLIC veyra_base veyra_gfx veyra_media ole32 windowscodecs mmdevapi avrt mfplat mfuuid mf)add_subdirectory(third_party/soundtouch EXCLUDE_FROM_ALL)target_link_libraries(veyra_sinks PRIVATE ${FFMPEG_LIBRARIES} veyra_soundtouch)if(FFMPEG_INCLUDE_DIRS)diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 2e02cfab..f6077e74 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -23,6 +23,7 @@#include "veyra/source/XboxSessionSource.h"#endif#include "veyra/media/AudioTrack.h"+#include "veyra/media/NetworkSettings.h"#include "veyra/sink/VideoEncoder.h"#include "veyra/engine/ExportOptions.h"namespace veyra::source { struct RemotePlayConnectDesc; class RemotePlaySessionSource; struct MoonlightConnectDesc; class MoonlightSessionSource; struct XboxConnectDesc; class XboxSessionSource; }@@ -45,6 +46,7 @@ struct PlayerOptions { bool nr=false,sr=false,fg=false,realtime=true; uint32_t fbool softwareDecode=false; // user setting: files skip D3D12VA and decode on the CPUbool deinterlace=true; // automatic file deinterlace, preserves progressive bypassbool hardwareDecodeOnly=false; // user setting "强制硬解": files fail instead of falling back to software+ media::NetworkSettings network; // buffering / reconnect / damaged-picture choices for network sources and serversEnhancementSettings snapshot()const{auto s=settings;s.nr=nr;s.sr=sr;s.multiplier=fg?fgMultiplier:1;s.nrPolicy=realtime?(settings.nrPolicy==pipeline::NrSizePolicy::Native?pipeline::NrSizePolicy::Realtime:settings.nrPolicy):pipeline::NrSizePolicy::Native;return s;}static PlayerOptions from(EnhancementSettings s,std::optional<ChainRuntimeOrder> order=std::nullopt){PlayerOptions o;o.nr=s.nr;o.sr=s.sr;o.fg=s.multiplier>1;o.fgMultiplier=std::max(2u,s.multiplier);o.realtime=s.nrPolicy!=pipeline::NrSizePolicy::Native;o.settings=s;o.nodeOrder=order;return o;}};@@ -82,6 +84,9 @@ struct PlayerSnapshot {int selectedAudioTrack=-1;bool audioRebuffering=false;uint64_t audioVideoWaits=0;+ // Network sources and files on a server (#48): buffered seconds, rates, reconnects,+ // whether playback is paused for buffering and why. active=false for local files.+ media::NetworkStats network;bool audioEndpointRecovering=false;HRESULT audioEndpointError=S_OK;uint64_t audioEndpointRecoveries=0;uint64_t seekRequested=0,seekPresented=0;double seekTarget=0;double position=0,duration=0,fps=0,lateMs=0,lateP95Ms=0;diff --git a/include/veyra/media/DemuxSession.h b/include/veyra/media/DemuxSession.hnew file mode 100644index 00000000..b8a029f2--- /dev/null+++ b/include/veyra/media/DemuxSession.h@@ -0,0 +1,217 @@+#pragma once+// DemuxSession: one connection, one demux thread, bounded packet queues for the+// video and the selected audio stream (#48, docs/NETWORK_BUFFER_48_PLAN_2026-10-17.md).+//+// Network sources (http/https/rtsp) and files on a server (UNC paths, mapped+// drives) used to be opened twice - FFmpegDemuxer for the picture, AudioPipeline for+// the sound - so every byte crossed the link twice and a stall of either blocked the+// engine. A session owns the only AVFormatContext: its thread reads packets ahead of+// playback, so a slow or briefly broken link is absorbed by the queue, an interrupted+// connection is re-established behind the queue, and the player can pause for+// buffering instead of failing. Local drives never use it.+//+// Threading: the demux thread owns the AVFormatContext. Consumers (the engine thread+// for video, the audio thread for sound) only pop packets and read the stream+// description copied at open, which stays valid across reconnects.+#include <atomic>+#include <chrono>+#include <condition_variable>+#include <cstdint>+#include <deque>+#include <memory>+#include <mutex>+#include <string>+#include <thread>+#include <vector>++#include "veyra/media/NetworkInput.h"+#include "veyra/media/NetworkSettings.h"++namespace veyra::media {++struct CodecParametersDeleter { void operator()(AVCodecParameters*) const; };++// What the consumers need from a stream, copied at open (AVStream pointers do not+// survive a reconnect).+struct SessionStreamInfo {+ int index = -1;+ int type = -1; // AVMediaType+ std::unique_ptr<AVCodecParameters, CodecParametersDeleter> parameters;+ int timeBaseNum = 0, timeBaseDen = 1;+ int avgRateNum = 0, avgRateDen = 0; // avg_frame_rate+ int nominalRateNum = 0, nominalRateDen = 0; // r_frame_rate+ int sarNum = 0, sarDen = 0;+ int64_t duration = INT64_MIN; // stream time base, AV_NOPTS_VALUE when unknown+ std::string language, title, rotate;+};++class DemuxSession {+public:+ struct OpenParams {+ std::wstring path;+ NetworkSettings settings;+ const std::atomic<bool>* cancelled = nullptr; // owner stop (engine): aborts every blocking call+ int audioStream = -2; // -2 best audio, -1 none, >=0 explicit+ };+ // Connects and probes (bounded by the connect/probe limits and `cancelled`),+ // then starts the demux thread. Null with `error` set on failure.+ static std::shared_ptr<DemuxSession> open(const OpenParams& params, std::wstring* error = nullptr);+ ~DemuxSession();+ DemuxSession(const DemuxSession&) = delete;+ DemuxSession& operator=(const DemuxSession&) = delete;++ // ---- description (immutable after open) -----------------------------------+ const std::vector<SessionStreamInfo>& streams() const { return streams_; }+ const SessionStreamInfo* stream(int index) const { return index >= 0 && size_t(index) < streams_.size() ? &streams_[size_t(index)] : nullptr; }+ int videoStream() const { return videoIndex_; }+ int audioStream() const { return audioIndex_.load(); }+ bool live() const { return live_; }+ bool seekable() const { return !live_; }+ int64_t durationUs() const { return durationUs_; }+ int64_t containerBitRate() const { return containerBitRate_; }+ const std::string& formatName() const { return formatName_; }+ const std::wstring& path() const { return path_; }+ const NetworkSettings& settings() const { return settings_; }+ const NetworkBufferPlan& plan() const { return plan_; }++ // ---- consumers --------------------------------------------------------------+ enum class Pop { Packet, Empty, Eof, Failed, Cancelled };+ struct Meta {+ bool discontinuity = false; // first packet after a live reconnect: reset the decoder+ uint32_t generation = 0; // seek counter the packet belongs to+ };+ // Moves the next packet into `dst` (which must be unreferenced), waiting up to+ // waitMs for one. Video honours the buffering hold (Empty while playback is+ // paused for buffering) only when asked: offline readers pass false.+ Pop popVideo(AVPacket* dst, Meta& meta, int waitMs, bool honourHold);+ Pop popAudio(AVPacket* dst, Meta& meta, int waitMs);+ // Audio packets are queued only for the selected stream; -1 drops them all.+ bool selectAudioStream(int index);+ // Where the player is (media timeline, microseconds): drives how far ahead the+ // thread reads and when playback pauses for buffering.+ void setPlaybackPositionUs(int64_t us);+ // Repositions (seekable sources only). Returns once the new position is set; the+ // queues restart from there and generation() advances.+ bool seek(int64_t targetUs);+ uint32_t generation() const { return generation_.load(); }+ // Drops the connection and re-establishes it behind the queue.+ void requestReconnect(const char* reason);+ // True while the player should hold still (start-up wait or underflow).+ bool holding() const;+ NetworkStats stats() const;+ void addCorruptFrames(uint64_t flagged, uint64_t skipped);+ std::wstring failureMessage() const;+ bool eof() const;++private:+ DemuxSession();+ struct Item {+ AVPacket* packet = nullptr;+ uint32_t generation = 0;+ bool discontinuity = false;+ int64_t startUs = 0, endUs = 0;+ int64_t dtsUs = INT64_MIN; // AV_NOPTS_VALUE when the container gave none+ size_t bytes = 0;+ };+ struct Queue {+ std::deque<Item> items;+ size_t bytes = 0;+ int64_t firstUs = INT64_MIN; // first content time since open / seek+ int64_t lastEndUs = INT64_MIN; // end of the last packet queued (kept after pops)+ int64_t lastDtsUs = INT64_MIN; // decode time of the last packet queued (resume de-duplication)+ bool ended = false;+ bool dedupe = false; // after a VOD reconnect: drop packets at or before lastDtsUs+ void clear();+ };+ struct Interrupt;+ struct FileAvio;+ enum class Phase { Prebuffering, Playing, Buffering };++ // demux thread+ void threadMain();+ bool openContext(std::wstring* error, bool initial);+ void closeContext();+ void applyDiscardFlags();+ bool verifyStreams();+ void onPacket(AVPacket* packet);+ bool pushLocked(Item&& item, bool video);+ bool recover(int code, const char* why);+ void doSeek();+ bool flowBlockedLocked() const;+ void fail(const std::wstring& message);+ void flushPendingAudio(int64_t anchorUs);++ // shared state (m_)+ double leadSecondsLocked() const;+ void updatePhaseLocked();+ double resumeTargetLocked() const;+ double aheadSecondsLocked() const;+ uint64_t aheadBytesLocked() const;+ double bitrateLocked(double* measured) const;+ double serverRateLocked() const;+ void noteArrivalLocked(size_t bytes);+ bool endedLocked() const;+ void enterPhaseLocked(Phase phase, const char* why);+ void logSummaryLocked(bool force);++ std::vector<SessionStreamInfo> streams_;+ int videoIndex_ = -1;+ std::atomic<int> audioIndex_{-1};+ bool live_ = true;+ int64_t durationUs_ = 0, containerBitRate_ = 0;+ std::string formatName_;+ std::wstring path_;+ NetworkSettings settings_;+ NetworkBufferPlan plan_;+ std::atomic<uint32_t> generation_{1};+ const std::atomic<bool>* cancelled_ = nullptr;++ mutable std::mutex m_;+ std::condition_variable consumerCv_, producerCv_, seekCv_;+ std::atomic<bool> stop_{false};+ std::thread thread_;+ std::unique_ptr<Interrupt> irq_;+ std::unique_ptr<FileAvio> file_;+ AVFormatContext* context_ = nullptr; // demux thread only+ bool network_ = false; // http/https/rtsp (otherwise a file)++ Queue video_, audio_;+ Phase phase_ = Phase::Prebuffering;+ double targetSeconds_ = 0;+ bool afterSeek_ = false;+ int64_t playbackUs_ = -1;+ bool eof_ = false, failed_ = false, reconnecting_ = false;+ uint32_t reconnectAttempt_ = 0, reconnects_ = 0, stalls_ = 0, connections_ = 0;+ std::wstring failure_;+ bool bandwidthLow_ = false;+ uint64_t corruptPackets_ = 0, corruptFrames_ = 0, skippedFrames_ = 0, totalBytes_ = 0;++ // rate measurement (m_)+ struct Arrival { int64_t ns; size_t bytes; };+ std::deque<Arrival> arrivals_;+ double readBytesDecayed_ = 0, readSecondsDecayed_ = 0;+ int64_t lastRateNs_ = 0;+ struct RateSample { int64_t contentUs; uint64_t cumulativeBytes; };+ std::deque<RateSample> rateSamples_;+ uint64_t contentBytes_ = 0;+ int64_t lastSummaryNs_ = 0;+ int64_t phaseSinceNs_ = 0;++ // commands (m_)+ bool seekPending_ = false, seekDone_ = true, seekOk_ = false;+ int64_t seekTargetUs_ = 0;+ bool reconnectPending_ = false;+ std::string reconnectReason_;++ bool discardDirty_ = false; // m_: the demux thread re-applies stream discard flags++ // demux thread only+ int64_t offsetUs_ = 0; // live reconnect: keeps the timeline continuous+ bool gateKeyframe_ = false; // live reconnect: wait for a video keyframe+ bool videoDiscontinuityPending_ = false, audioDiscontinuityPending_ = false;+ std::vector<Item> pendingAudio_; // audio read before the live gate opened+ int64_t pendingAudioBytes_ = 0;+ int64_t reconnectBudgetMs_ = 60000;+};++} // namespace veyra::mediadiff --git a/include/veyra/media/FFmpegDemuxer.h b/include/veyra/media/FFmpegDemuxer.hindex aa9075aa..0a128078 100644--- a/include/veyra/media/FFmpegDemuxer.h+++ b/include/veyra/media/FFmpegDemuxer.h@@ -2,9 +2,16 @@// FFmpeg demuxer wrapper (Playbook section 13.1). Video-only for Phase 3;// PTS-driven, never assumes a fixed frame rate.+//+// Two modes. Direct (default): this class owns an AVFormatContext and reads it on+// the caller's thread - local files, exactly as before. Shared (openShared): the+// stream description and the packets come from a DemuxSession that also feeds the+// audio pipeline (network sources and files on a server, #48).#include <cstdint>+#include <memory>#include <string>+#include "veyra/media/DemuxSession.h"#include "veyra/media/NetworkInput.h"struct AVFormatContext;@@ -29,9 +36,13 @@ public:FFmpegDemuxer& operator=(const FFmpegDemuxer&) = delete;bool open(const std::wstring& path,const std::atomic<bool>* cancelled=nullptr);+ // Shared mode: packets and stream parameters come from the session.+ bool openShared(std::shared_ptr<DemuxSession> session);void close();- bool opened() const { return context_ != nullptr; }+ bool opened() const { return context_ != nullptr || session_ != nullptr; }+ bool shared() const { return session_ != nullptr; }+ const std::shared_ptr<DemuxSession>& session() const { return session_; }int videoStreamIndex() const { return videoStreamIndex_; }int64_t durationUs() const;bool seekable() const;@@ -50,9 +61,18 @@ public:int rotationDegrees() const;// Returns false at end of file. The packet stays owned by this demuxer- // and remains valid until the next call.+ // and remains valid until the next call. In shared mode this waits for data+ // (and never pauses for buffering); false with endOfFile=false is a failure.bool readVideoPacket(bool& endOfFile);+ // Playback read. Direct mode behaves like readVideoPacket. Shared mode waits at+ // most waitMs and, with honourHold, reports Waiting while playback is paused+ // for buffering.+ enum class ReadResult { Packet, Eof, Error, Waiting, Cancelled };+ ReadResult readVideoPacketEx(int waitMs, bool honourHold);+ // The last packet came first after a live reconnect: reset the decoder.+ bool packetDiscontinuity() const { return packetDiscontinuity_; }+// Seek to a time in microseconds; the next read yields a packet at or// after that time. Flushing the decoder afterwards is the caller's job.bool seekToUs(int64_t targetUs);@@ -61,11 +81,15 @@ public:const DemuxerStats& stats() const { return stats_; }private:+ void notePacket();+AVFormatContext* context_ = nullptr;+ std::shared_ptr<DemuxSession> session_;AVPacket* packet_ = nullptr;int videoStreamIndex_ = -1;DemuxerStats stats_{};bool havePendingPacket_ = false;+ bool packetDiscontinuity_ = false;InputInterrupt interrupt_;};diff --git a/include/veyra/media/FFmpegVideoDecoder.h b/include/veyra/media/FFmpegVideoDecoder.hindex c500e2a6..5b995b76 100644--- a/include/veyra/media/FFmpegVideoDecoder.h+++ b/include/veyra/media/FFmpegVideoDecoder.h@@ -109,6 +109,9 @@ public:void flushBuffers(); // seek boundary (Playbook 13.4)void recoverAtKeyframe(); // compressed input loss: discard until a new key frame+ // AVERROR of the last failed sendPacket / receiveFrame (0 when none). Damaged+ // network data reports AVERROR_INVALIDDATA; the caller decides whether to skip it.+ int lastError() const { return lastError_; }const DecoderStats& stats() const { return stats_; }// True when the decoder is producing AV_PIX_FMT_D3D12 frames.@@ -164,6 +167,8 @@ private:AVFrame* frame_ = nullptr;std::deque<AVFrame*> bufferedFrames_;DecodeReceiveStatus receiveStatus_ = DecodeReceiveStatus::NeedInput;+ int lastError_ = 0;+ uint64_t errorLogs_ = 0;int frameTimeBaseNum_ = 0;int frameTimeBaseDen_ = 0;DecoderStats stats_{};diff --git a/include/veyra/media/NetworkInput.h b/include/veyra/media/NetworkInput.hindex d17203bd..591e1585 100644--- a/include/veyra/media/NetworkInput.h+++ b/include/veyra/media/NetworkInput.h@@ -5,10 +5,20 @@#include <string>#include <string_view>#include <mutex>+#include "veyra/media/NetworkSettings.h"extern "C" {#include <libavformat/avformat.h>}namespace veyra::media {+// Network deadlines (#48). The old single 5 s limit applied to open, probe and every+// read alike, so a slow server or a Wi-Fi hiccup was reported as a failed source.+// Opening a connection and reading media now have separate limits; the owner's+// cancel flag (stop / source switch) still aborts every blocking call at once.+constexpr int kConnectTimeoutMs = 15000; // avformat_open_input+constexpr int kProbeTimeoutMs = 30000; // avformat_find_stream_info+constexpr int kReadTimeoutVodMs = 20000; // one av_read_frame / seek on a seekable source+constexpr int kReadTimeoutLiveMs = 10000; // one av_read_frame on a live source+inline bool networkMediaInput(std::wstring_view path) {const auto colon=path.find(L':');if(colon==std::wstring_view::npos||colon>5)return false;@@ -16,11 +26,27 @@ inline bool networkMediaInput(std::wstring_view path) {for(auto& ch:scheme)ch=std::towlower(ch);return scheme==L"http"||scheme==L"https"||scheme==L"rtsp";}+// A file on a server: a UNC path (\\host\share\...) or a drive letter mapped to a+// network share (GetDriveType == DRIVE_REMOTE). Local extended paths (\\?\C:\...)+// are local. Implemented in DemuxSession.cpp.+bool remoteMediaPath(std::wstring_view path);+// VEYRA_TEST_FORCE_DEMUX_SESSION=1: send local files through the shared demux+// session too, to compare it against the direct path frame by frame.+bool forceDemuxSessionForTest();+// Playback sources that read through the shared demux session. Offline users+// (export, tools) pass playback=false and keep the direct file path for NAS files.+inline bool sharedDemuxInput(std::wstring_view path, bool playback) {+ return networkMediaInput(path) || (playback && remoteMediaPath(path)) || forceDemuxSessionForTest();+}+// Per-operation deadlines only on networks; immediate owner cancellation on all inputs.class InputInterrupt {public:- void configure(bool network,const std::atomic<bool>* owner,const std::atomic<bool>* local=nullptr){network_=network;owner_=owner;local_=local;deadline_=0;}- void arm(){deadline_=network_?now()+5000000000ll:0;}+ void configure(bool network,const std::atomic<bool>* owner,const std::atomic<bool>* local=nullptr,bool live=false){network_=network;owner_=owner;local_=local;live_=live;deadline_=0;}+ // Read / seek deadline.+ void arm(){deadline_=network_?now()+int64_t(live_?kReadTimeoutLiveMs:kReadTimeoutVodMs)*1000000ll:0;}+ void armConnect(){deadline_=network_?now()+int64_t(kConnectTimeoutMs)*1000000ll:0;}+ void armProbe(){deadline_=network_?now()+int64_t(kProbeTimeoutMs)*1000000ll:0;}void disarm(){deadline_=0;}static int callback(void* opaque){const auto& self=*static_cast<InputInterrupt*>(opaque);const auto deadline=self.deadline_.load();@@ -29,11 +55,11 @@ public:private:static int64_t now(){return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();}const std::atomic<bool>* owner_=nullptr;const std::atomic<bool>* local_=nullptr;- bool network_=false;std::atomic<int64_t> deadline_{0};+ bool network_=false,live_=false;std::atomic<int64_t> deadline_{0};};inline void networkMediaOptions(AVDictionary** options){static std::once_flag initialized;std::call_once(initialized,[]{avformat_network_init();});- av_dict_set(options,"rw_timeout","5000000",0);av_dict_set(options,"timeout","5000000",0);+ av_dict_set(options,"rw_timeout","15000000",0);av_dict_set(options,"timeout","15000000",0);av_dict_set(options,"rtsp_transport","tcp",0);}}diff --git a/include/veyra/media/NetworkSettings.h b/include/veyra/media/NetworkSettings.hnew file mode 100644index 00000000..7cefff5e--- /dev/null+++ b/include/veyra/media/NetworkSettings.h@@ -0,0 +1,117 @@+#pragma once+// Network playback settings, their resolved buffer plan and the statistics the+// shared demux session publishes (#48). Pure data: no FFmpeg or Windows headers,+// so the engine snapshot, the UI bridge and the tests can include it freely.+#include <algorithm>+#include <cstdint>+#include <string>+#include <string_view>++namespace veyra::media {++enum class NetworkBufferLevel : uint8_t { Auto = 0, Off, Small, Medium, Large };+// What to do with pictures the decoder flags as damaged (network packet loss).+// Conceal : show FFmpeg's concealed picture (default, keeps motion going)+// WaitKeyframe : drop damaged pictures and wait for the next keyframe+enum class CorruptPolicy : uint8_t { Conceal = 0, WaitKeyframe };++struct NetworkSettings {+ NetworkBufferLevel level = NetworkBufferLevel::Auto;+ int startupPrebufferSeconds = -1; // -1 follows the level, 0 does not wait, >0 seconds+ bool autoReconnect = true;+ CorruptPolicy corrupt = CorruptPolicy::Conceal;+ bool operator==(const NetworkSettings&) const = default;+};++inline const char* networkBufferLevelId(NetworkBufferLevel level) {+ switch (level) {+ case NetworkBufferLevel::Off: return "off";+ case NetworkBufferLevel::Small: return "small";+ case NetworkBufferLevel::Medium: return "medium";+ case NetworkBufferLevel::Large: return "large";+ default: return "auto";+ }+}+inline NetworkBufferLevel networkBufferLevelFromId(std::string_view id) {+ if (id == "off") return NetworkBufferLevel::Off;+ if (id == "small") return NetworkBufferLevel::Small;+ if (id == "medium") return NetworkBufferLevel::Medium;+ if (id == "large") return NetworkBufferLevel::Large;+ return NetworkBufferLevel::Auto;+}+inline CorruptPolicy corruptPolicyFromId(std::string_view id) {+ return id == "keyframe" ? CorruptPolicy::WaitKeyframe : CorruptPolicy::Conceal;+}++// Resolved numbers. `ahead` is how far past the playback position the demux+// thread keeps reading (VOD forward window / live jitter ceiling, whichever+// applies); `start` is what must be queued before the first picture and after a+// seek; `lowWater` is the lead below which playback pauses for buffering.+struct NetworkBufferPlan {+ double aheadSeconds = 30;+ uint64_t aheadBytes = 256ull << 20;+ double startSeconds = 3;+ double lowWaterSeconds = 0.3;+ // Auto only: the forward window the player may grow to when the server is+ // slower than the stream (resume target is clamped to it).+ double growSeconds = 120;+ uint64_t growBytes = 1024ull << 20;+ bool holds = true; // false: never pause for buffering (level Off)+};++inline NetworkBufferPlan networkBufferPlan(const NetworkSettings& settings, bool live) {+ NetworkBufferPlan plan;+ constexpr uint64_t MiB = 1ull << 20;+ if (live) {+ switch (settings.level) {+ case NetworkBufferLevel::Off: plan = {1.0, 32 * MiB, 0.0, 0.0, 1.0, 32 * MiB, false}; break;+ case NetworkBufferLevel::Small: plan = {1.5, 32 * MiB, 0.5, 0.1, 1.5, 32 * MiB, true}; break;+ case NetworkBufferLevel::Medium: plan = {3.0, 64 * MiB, 1.5, 0.2, 3.0, 64 * MiB, true}; break;+ case NetworkBufferLevel::Large: plan = {6.0, 128 * MiB, 3.0, 0.3, 6.0, 128 * MiB, true}; break;+ default: plan = {3.0, 64 * MiB, 1.0, 0.15, 6.0, 128 * MiB, true}; break;+ }+ } else {+ switch (settings.level) {+ case NetworkBufferLevel::Off: plan = {2.0, 32 * MiB, 0.0, 0.0, 2.0, 32 * MiB, false}; break;+ case NetworkBufferLevel::Small: plan = {8.0, 64 * MiB, 2.0, 0.25, 8.0, 64 * MiB, true}; break;+ case NetworkBufferLevel::Medium: plan = {30.0, 256 * MiB, 5.0, 0.4, 30.0, 256 * MiB, true}; break;+ case NetworkBufferLevel::Large: plan = {120.0, 1024 * MiB, 10.0, 0.5, 120.0, 1024 * MiB, true}; break;+ default: plan = {30.0, 256 * MiB, 3.0, 0.3, 120.0, 1024 * MiB, true}; break;+ }+ }+ if (settings.startupPrebufferSeconds >= 0 && plan.holds)+ plan.startSeconds = std::min(double(settings.startupPrebufferSeconds), live ? 30.0 : 120.0);+ // The window must be able to hold what the player waits for.+ plan.aheadSeconds = std::max(plan.aheadSeconds, plan.startSeconds * 1.5 + 2.0);+ plan.growSeconds = std::max(plan.growSeconds, plan.aheadSeconds);+ return plan;+}++// Statistics for the signal panel and the status line. Plain values, copied out+// of the session; fields that are not measured yet stay 0 (the UI shows "—").+struct NetworkStats {+ enum class State : uint8_t { Idle = 0, Prebuffering, Playing, Buffering, Reconnecting, Failed, Ended };+ bool active = false; // the source goes through the shared demux session+ bool live = false; // not seekable: no resume position+ State state = State::Idle;+ double bufferedSeconds = 0; // content queued ahead of the playback position+ double targetSeconds = 0; // what the current wait is collecting+ uint64_t bufferedBytes = 0;+ uint64_t capBytes = 0;+ double downloadBytesPerSecond = 0; // arrival rate over the last ~2 s+ double serverBytesPerSecond = 0; // throughput while actually reading+ double bitrateBytesPerSecond = 0; // media bitrate (container or measured)+ bool bandwidthLow = false; // server slower than the stream+ uint32_t reconnects = 0; // successful reconnects+ uint32_t reconnectAttempt = 0; // current attempt, 0 when not reconnecting+ uint32_t stalls = 0; // times playback paused for buffering+ uint64_t corruptPackets = 0; // video packets flagged damaged by the demuxer+ uint64_t corruptFrames = 0; // pictures the decoder flagged damaged+ uint64_t skippedFrames = 0; // damaged pictures dropped (WaitKeyframe)+ uint64_t sessionBytes = 0; // total bytes demuxed+ uint32_t connections = 0; // connections opened over the session (1 + reconnects)+ std::wstring message; // explanation shown to the user, empty when none+ bool holding() const { return state == State::Prebuffering || state == State::Buffering; }+};++} // namespace veyra::mediadiff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.hindex be62df7e..e2048f4d 100644--- a/include/veyra/sink/WasapiAudioSink.h+++ b/include/veyra/sink/WasapiAudioSink.h@@ -1,4 +1,5 @@#pragma once+#include "veyra/media/DemuxSession.h"#include "veyra/media/NetworkInput.h"// AudioPipeline: FFmpeg audio demux/decode + watermarked bounded ring@@ -73,6 +74,11 @@ public:~AudioPipeline();bool open(const std::wstring& path,const std::atomic<bool>* cancelled=nullptr);+ // Network sources and files on a server: take audio packets from the shared demux+ // session that also feeds the video (one connection, #48) instead of opening the+ // address a second time.+ bool open(std::shared_ptr<media::DemuxSession> session);+ bool sharedSession() const { return session_ != nullptr; }const std::vector<media::AudioTrack>& tracks() const { return tracks_; }int selectedTrack() const { return streamIndex_; }// Owner thread only, after stopThread(). Failure preserves the old decoder.@@ -153,16 +159,25 @@ private:void pauseReader(); // returns once the reader is idle; drops queued packetsvoid resumeReader();void stopReader();- bool takeQueuedPacket(bool& eof); // non-blocking; moves the head packet into packet_+ bool takeQueuedPacket(bool& eof,int waitMs=0); // moves the head packet into packet_; waits up to waitMs (session only)+ // Shared session: reposition the decoder and PCM ring at `target` without moving+ // the (shared) demuxer. The engine has already repositioned the session for a seek.+ bool rewindSession(double target);+ void trimRingBefore(double targetMs); // mutex_ heldfriend class AudioThread;AudioFormat pcmFormat_;std::vector<media::AudioTrack> tracks_;AVFormatContext* fmt_ = nullptr;+ std::shared_ptr<media::DemuxSession> session_; // shared mode: packets come from here, fmt_ stays null+ uint32_t sessionGeneration_ = 0; // audio thread: the session reposition this decoder follows+ bool sessionDiscontinuity_ = false; // next packet starts a new live connection: reset the decoder+ std::chrono::steady_clock::time_point prefillDeadline_{};+ bool prefillWait_ = false; // audio thread: wait for session packets (open / seek prefill)media::InputInterrupt inputInterrupt_;AVCodecContext* codecCtx_ = nullptr;- AVStream* stream_ = nullptr;+ AVRational streamTimeBase_{1, 1000};AVPacket* packet_ = nullptr;int swrInputRate_=0,swrInputFormat_=-1;SwrContext* swr_ = nullptr;diff --git a/include/veyra/source/IFrameSource.h b/include/veyra/source/IFrameSource.hindex a3426537..b0971f5d 100644--- a/include/veyra/source/IFrameSource.h+++ b/include/veyra/source/IFrameSource.h@@ -8,6 +8,7 @@#include <string>#include <atomic>+#include "veyra/media/NetworkSettings.h"#include "veyra/pipeline/FramePacket.h"#include "veyra/source/DolbyVision.h"@@ -31,6 +32,11 @@ struct SourceOpenDesc {bool legacyCaptureRgbForDiagnostic = false; // explicit A/B only; never set by the playerconst std::atomic<bool>* cancelled = nullptr;bool deinterlace = false; // playback opt-in; unchanged default for offline consumers+ // Network and server playback (#48). Offline consumers (export, tools, tests) keep+ // the defaults: strict about damaged data, reads that wait, direct file reads.+ media::NetworkSettings network; // the user's buffering / reconnect / damaged-picture choices+ bool nonBlocking = false; // player: read() may return Waiting while the network buffers+ bool tolerateCorruption = false; // player: keep going through damaged packets (network sources, MPEG-TS)};struct SourceInfo {diff --git a/include/veyra/source/MediaFileSource.h b/include/veyra/source/MediaFileSource.hindex b6d8c14c..bf837fba 100644--- a/include/veyra/source/MediaFileSource.h+++ b/include/veyra/source/MediaFileSource.h@@ -7,9 +7,12 @@// implementation exists here: FFmpegDemuxer + FFmpegVideoDecoder do the// work; this class owns contract translation (PTS/duration/color/flags/// epoch) and the seek protocol.+#include <chrono>#include <cstdint>+#include <memory>#include <string_view>+#include "veyra/media/DemuxSession.h"#include "veyra/media/FFmpegDemuxer.h"#include "veyra/media/FFmpegVideoDecoder.h"#include "veyra/media/FFmpegDeinterlacer.h"@@ -36,14 +39,32 @@ public:uint64_t epoch() const { return epoch_; }const std::wstring& errorMessage() const { return errorMessage_; }+ // ---- network / server playback (#48) -----------------------------------------+ // The shared demux session the audio pipeline reads from too; null for local files.+ std::shared_ptr<media::DemuxSession> sharedSession() const { return demuxer_.session(); }+ // Zeroed (active=false) when the source does not go through a session.+ media::NetworkStats networkStats() const;+ // Playback position on the media timeline, written by the engine each turn so the+ // session knows how much is buffered ahead.+ void setPlaybackPositionMs(double ms);+private:pipeline::ColorDescription parseColor(const AVCodecParameters* params) const;bool fallbackToSoftware(std::string_view reason);+ void beginDiscontinuity();+ void resetCorruptionState();+ bool tolerateDecoderError();media::FFmpegDemuxer demuxer_;media::FFmpegVideoDecoder decoder_;media::FFmpegDeinterlacer deinterlacer_;bool deinterlaceEnabled_=true,filterDraining_=false;+ // Damaged data tolerance (network sources, MPEG-TS) and buffering reads.+ bool nonBlocking_=false,tolerant_=false,waitKeyframe_=false,pendingDiscontinuity_=false;+ media::CorruptPolicy corruptPolicy_=media::CorruptPolicy::Conceal;+ uint64_t corruptPacketsSeen_=0,corruptFramesSeen_=0,decoderErrorsSeen_=0;+ std::chrono::steady_clock::time_point lastReadCall_{},noOutputSince_{},lastCorruptLog_{},lastForcedReconnect_{},errorWindowStart_{};+ unsigned errorsInWindow_=0;SourceInfo info_{};uint64_t sequence_ = 0;uint64_t epoch_ = 1;diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex b3685551..a084d458 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -180,6 +180,7 @@ void EngineController::open(HWND video,const std::wstring& path,PlayerOptions op// keep them across the snapshot round-trip below.const bool captureCpuUnpack=opts.captureCpuUnpack;const bool softwareDecode=opts.softwareDecode;const bool hardwareDecodeOnly=opts.hardwareDecodeOnly;+ const media::NetworkSettings network=opts.network; // #48: buffering / reconnect choices#ifdef VEYRA_ENABLE_REMOTEPLAY// PS5 手柄控制 belongs to a capture card source; any other source ends it.if(!path.starts_with(L"capture:")&&!path.starts_with(L"capture2:"))stopRemoteControl();@@ -188,6 +189,7 @@ void EngineController::open(HWND video,const std::wstring& path,PlayerOptions opopts.captureReplayForTest=captureReplay;opts.captureCpuUnpack=captureCpuUnpack;opts.softwareDecode=softwareDecode;opts.hardwareDecodeOnly=hardwareDecodeOnly;+ opts.network=network;post([this,video,path,opts]{paused_=false;seekSeconds_=-1;run(video,path,opts);});}#ifdef VEYRA_ENABLE_REMOTEPLAY@@ -556,6 +558,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,ssource::SourceOpenDesc od;od.path=path;od.cancelled=&stop_;od.deinterlace=options.deinterlace;+ // Network sources and files on a server (#48): buffer settings, reads that may report+ // "buffering" instead of blocking the loop, and tolerance for damaged packets. Local+ // files and capture sources ignore all three.+ od.network=options.network;+ od.nonBlocking=!isCapture;+ od.tolerateCorruption=!isCapture;// Files use the same shared D3D12 device as the graph-> Capture// uses it for the compressed-payload decoder (H.264/HEVC/AV1/// VP9 through D3D12VA; MJPEG stays on the software path inside@@ -647,7 +655,22 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// normal owner-thread loop below, preserving its PTS.if(!isCapture){pipeline::FramePacket firstPacket;const AVFrame* firstFrame=nullptr;- const auto firstStatus=activeSource->read(firstPacket,&firstFrame);+ auto firstStatus=activeSource->read(firstPacket,&firstFrame);+ // A network source collects its start-up buffer before the first picture; show the+ // progress instead of an empty window, and let the user stop at any time.+ {+ auto nextShown=Clock::now();+ while(firstStatus==source::SourceReadStatus::Waiting&&!stop_){+ if(Clock::now()>=nextShown){+ nextShown=Clock::now()+std::chrono::milliseconds(150);+ const auto stats=source.networkStats();+ {std::lock_guard lock(mutex_);snapshot_.network=stats;}+ if(!stats.message.empty())status(stats.message);+ }+ firstStatus=activeSource->read(firstPacket,&firstFrame);+ }+ if(stop_)break;+ }if(firstStatus!=source::SourceReadStatus::Frame||firstFrame==nullptr||firstPacket.pts.isUnknown()){status(activeSource->info().kind==pipeline::SourceKind::File&&source.errorMessage().empty()?L"视频首帧无法解码或没有有效时间戳,请查看诊断":source.errorMessage().empty()?L"视频首帧读取失败":source.errorMessage(),true);@@ -913,10 +936,16 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,suint64_t seekDecoded=0;bool fileAwaitingVideo=true,fileAudioAlignPending=true,fileInputEnded=false;double lastFilePresentedMs=0,lastFilePresentLateness=0;TimingWindow presentEntryDeviation,presentReturnDeviation;- if(!isImage&&!isCapture&&audioPipe.open(path,&stop_)){+ // Network sources and files on a server share ONE connection between picture and sound:+ // the audio pipeline reads the same demux session instead of opening the address again.+ const auto demuxSession=isImage||isCapture?std::shared_ptr<media::DemuxSession>{}:source.sharedSession();+ if(!isImage&&!isCapture&&(demuxSession?audioPipe.open(demuxSession):audioPipe.open(path,&stop_))){{std::lock_guard lock(mutex_);snapshot_.audioTracks=audioPipe.tracks();snapshot_.selectedAudioTrack=audioPipe.selectedTrack();}audioPipe.holdForVideo();audioPipe.startThread(&audio,true);audioStarted=true;std::lock_guard lock(mutex_);snapshot_.audioAvailable=true;+ }else if(demuxSession){+ demuxSession->selectAudioStream(-1); // nobody reads audio: stop queueing it+ veyra::log::info("net-session","no audio pipeline for this source; audio packets are dropped");}auto holdFileAudio=[&]{if(audioStarted)audioPipe.holdForVideo();fileAwaitingVideo=true;fileInputEnded=false;};TimingWindow captureAges,scheduleWaits,processTimes,presentTimes,decodeTimes,gpuReadyTimes;@@ -1327,6 +1356,25 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}return lastAudioClockMs;};+ // Network sources and files on a server: statistics for the signal panel, and the buffering /+ // reconnect explanation on the status line while playback is held. The previous status comes+ // back when the hold ends, unless something else replaced the text in the meantime.+ std::wstring networkSavedStatus,networkShownStatus;+ bool networkClockFrozen=false;double networkFrozenMs=0;+ auto nextNetworkPublish=Clock::now();+ auto publishNetwork=[&]{+ const auto stats=source.networkStats();+ std::lock_guard lock(mutex_);+ snapshot_.network=stats;+ const bool explain=!stats.message.empty()&&(stats.holding()||stats.state==media::NetworkStats::State::Reconnecting);+ if(explain){+ if(networkShownStatus.empty())networkSavedStatus=snapshot_.status;+ snapshot_.status=networkShownStatus=stats.message;+ }else if(!networkShownStatus.empty()){+ if(snapshot_.status==networkShownStatus)snapshot_.status=networkSavedStatus;+ networkShownStatus.clear();+ }+ };uint64_t hdrDisplayCheck=0;bool captureRecovering=false;unsigned captureRetries=0;Clock::time_point captureRetryAt{};@@ -1389,6 +1437,19 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sdiagnostics::CpuStallTrace loopTrace("engine-stall",frames,45.0,watchdog_->stage());collectTimings();loopTrace.mark("collect");+ if(demuxSession){+ // Without an audio device the media clock is the wall clock: stand it still while the+ // session pauses playback for buffering (with audio, pausing the endpoint does that).+ if(!audioStarted){+ if(demuxSession->holding()){+ if(!networkClockFrozen){networkClockFrozen=true;networkFrozenMs=nowMs();}+ anchor=Clock::now();anchorMs=networkFrozenMs;+ }else networkClockFrozen=false;+ }+ // Where playback is decides how far ahead the session reads and when it pauses for buffering.+ source.setPlaybackPositionMs(nowMs());+ if(Clock::now()>=nextNetworkPublish){nextNetworkPublish=Clock::now()+std::chrono::milliseconds(100);publishNetwork();}+ }if(captureRecovering){if(Clock::now()<captureRetryAt){std::this_thread::sleep_for(std::chrono::milliseconds(20));continue;}++captureRetries;diff --git a/src/media/DemuxSession.cpp b/src/media/DemuxSession.cppnew file mode 100644index 00000000..a9017e87--- /dev/null+++ b/src/media/DemuxSession.cpp@@ -0,0 +1,1132 @@+#include "veyra/media/DemuxSession.h"++#include <windows.h>++#include <algorithm>+#include <cmath>+#include <cstdlib>+#include <cwctype>+#include <format>+#include <limits>++extern "C" {+#include <libavcodec/avcodec.h>+#include <libavformat/avformat.h>+#include <libavformat/avio.h>+#include <libavutil/avutil.h>+#include <libavutil/dict.h>+#include <libavutil/error.h>+#include <libavutil/mathematics.h>+}++#include "veyra/Log.h"++namespace veyra::media {+namespace {+using Clock = std::chrono::steady_clock;++int64_t nowNs() {+ return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count();+}+std::string utf8(std::wstring_view text) {+ if (text.empty()) return {};+ const int size = WideCharToMultiByte(CP_UTF8, 0, text.data(), int(text.size()), nullptr, 0, nullptr, nullptr);+ std::string out(size_t(std::max(size, 0)), '\0');+ if (size > 0) WideCharToMultiByte(CP_UTF8, 0, text.data(), int(text.size()), out.data(), size, nullptr, nullptr);+ return out;+}+std::string errorText(int code) {+ char text[AV_ERROR_MAX_STRING_SIZE]{};+ av_strerror(code, text, sizeof(text));+ return text;+}+double envNumber(const wchar_t* name, double fallback) {+ wchar_t text[48]{};+ const DWORD n = GetEnvironmentVariableW(name, text, 48);+ if (n == 0 || n >= 48) return fallback;+ wchar_t* end = nullptr;+ const double value = std::wcstod(text, &end);+ return end != text ? value : fallback;+}+int64_t toUs(int64_t ts, AVRational base) {+ return ts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE : av_rescale_q(ts, base, AV_TIME_BASE_Q);+}+constexpr int64_t kStreamEnded = INT64_MIN;+} // namespace++bool remoteMediaPath(std::wstring_view path) {+ if (path.size() >= 2 && path[0] == L'\\' && path[1] == L'\\') {+ // \\?\C:\... and \\.\... are local; \\?\UNC\server\share is a server.+ if (path.size() >= 4 && (path[2] == L'?' || path[2] == L'.') && path[3] == L'\\') {+ const auto rest = path.substr(4);+ return rest.size() >= 4 && _wcsnicmp(rest.data(), L"UNC\\", 4) == 0;+ }+ return true;+ }+ if (path.size() >= 3 && std::iswalpha(path[0]) && path[1] == L':' && (path[2] == L'\\' || path[2] == L'/')) {+ const wchar_t root[4] = {path[0], L':', L'\\', 0};+ return GetDriveTypeW(root) == DRIVE_REMOTE;+ }+ return false;+}++bool forceDemuxSessionForTest() {+ static const bool forced = GetEnvironmentVariableW(L"VEYRA_TEST_FORCE_DEMUX_SESSION", nullptr, 0) > 0;+ return forced;+}++void CodecParametersDeleter::operator()(AVCodecParameters* parameters) const { avcodec_parameters_free(¶meters); }++// ---------------------------------------------------------------------------+// Interrupt: every blocking FFmpeg call asks this. The owner's stop flag, the+// session's own shutdown, a pending command (seek / forced reconnect) and the+// per-operation deadline all abort it at once.+// ---------------------------------------------------------------------------+struct DemuxSession::Interrupt {+ const std::atomic<bool>* owner = nullptr;+ std::atomic<bool> stop{false}, command{false};+ std::atomic<int64_t> deadline{0};+ bool cancelled() const { return (owner && owner->load()) || stop.load(); }+ bool should() const {+ if (cancelled() || command.load()) return true;+ const auto limit = deadline.load();+ return limit && nowNs() >= limit;+ }+ bool timedOut() const {+ const auto limit = deadline.load();+ return limit && nowNs() >= limit;+ }+ static int callback(void* opaque) { return static_cast<Interrupt*>(opaque)->should() ? 1 : 0; }+ void arm(int ms) { deadline.store(nowNs() + int64_t(ms) * 1000000ll); }+ void disarm() { deadline.store(0); }+ // Sleeps up to ms, returning false as soon as a stop / command arrives.+ bool sleep(int ms) const {+ for (int waited = 0; waited < ms; waited += 20) {+ if (cancelled() || command.load()) return false;+ Sleep(DWORD(std::min(20, ms - waited)));+ }+ return !(cancelled() || command.load());+ }+};++// ---------------------------------------------------------------------------+// FileAvio: reads a file (local test, UNC, mapped drive) through our own IO so+// the transfer is counted, cancellable and, for tests, throttled+// (VEYRA_TEST_SLOW_IO=<MB/s>[,<latency ms per read>] stands in for a slow NAS).+// ---------------------------------------------------------------------------+struct DemuxSession::FileAvio {+ static constexpr int kBuffer = 1 << 20;+ HANDLE handle = INVALID_HANDLE_VALUE;+ AVIOContext* avio = nullptr;+ const Interrupt* irq = nullptr;+ int64_t position = 0, size = -1;+ double mbps = 0;+ int latencyMs = 0;+ int64_t throttleStartNs = 0;+ double throttleBytes = 0;++ ~FileAvio() {+ if (avio) {+ av_freep(&avio->buffer);+ avio_context_free(&avio);+ }+ if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);+ }+ bool open(const std::wstring& path, const Interrupt* interrupt) {+ irq = interrupt;+ handle = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);+ if (handle == INVALID_HANDLE_VALUE) return false;+ LARGE_INTEGER length{};+ if (GetFileSizeEx(handle, &length)) size = length.QuadPart;+ wchar_t text[64]{};+ if (const DWORD n = GetEnvironmentVariableW(L"VEYRA_TEST_SLOW_IO", text, 64); n > 0 && n < 64) {+ wchar_t* end = nullptr;+ mbps = std::wcstod(text, &end);+ if (end && *end == L',') latencyMs = std::max(0, _wtoi(end + 1));+ if (mbps > 0 || latencyMs > 0)+ log::warn("net-session", std::format("test slow IO active: {:.2f} MB/s, {} ms per read (VEYRA_TEST_SLOW_IO)", mbps, latencyMs));+ }+ auto* buffer = static_cast<uint8_t*>(av_malloc(kBuffer));+ if (!buffer) return false;+ avio = avio_alloc_context(buffer, kBuffer, 0, this, &FileAvio::readPacket, nullptr, &FileAvio::seek);+ if (!avio) {+ av_free(buffer);+ return false;+ }+ throttleStartNs = nowNs();+ return true;+ }+ bool wait(int ms) const {+ for (int waited = 0; waited < ms; waited += 10) {+ if (irq && irq->should()) return false;+ Sleep(DWORD(std::min(10, ms - waited)));+ }+ return !(irq && irq->should());+ }+ static int readPacket(void* opaque, uint8_t* buffer, int size) {+ auto& self = *static_cast<FileAvio*>(opaque);+ if (self.irq && self.irq->should()) return AVERROR_EXIT;+ if (self.latencyMs > 0 && !self.wait(self.latencyMs)) return AVERROR_EXIT;+ DWORD got = 0;+ if (!ReadFile(self.handle, buffer, DWORD(std::min(size, kBuffer)), &got, nullptr)) return AVERROR(EIO);+ if (got == 0) return AVERROR_EOF;+ self.position += got;+ if (self.mbps > 0) {+ // Token bucket: the bytes delivered so far may not run ahead of the allowed rate.+ self.throttleBytes += got;+ const double allowedSeconds = self.throttleBytes / (self.mbps * 1048576.0);+ const double elapsed = double(nowNs() - self.throttleStartNs) / 1e9;+ if (allowedSeconds > elapsed && !self.wait(int((allowedSeconds - elapsed) * 1000.0))) return AVERROR_EXIT;+ if (elapsed > allowedSeconds + 1.0) { // idle time earns no credit beyond a second+ self.throttleStartNs = nowNs();+ self.throttleBytes = 0;+ }+ }+ return int(got);+ }+ static int64_t seek(void* opaque, int64_t offset, int whence) {+ auto& self = *static_cast<FileAvio*>(opaque);+ if (whence & AVSEEK_SIZE) return self.size;+ whence &= ~AVSEEK_FORCE;+ if (self.latencyMs > 0) self.wait(self.latencyMs);+ LARGE_INTEGER target{}, result{};+ target.QuadPart = offset;+ const DWORD method = whence == SEEK_SET ? FILE_BEGIN : whence == SEEK_CUR ? FILE_CURRENT : FILE_END;+ if (!SetFilePointerEx(self.handle, target, &result, method)) return AVERROR(EIO);+ self.position = result.QuadPart;+ return result.QuadPart;+ }+};++void DemuxSession::Queue::clear() {+ for (auto& item : items) av_packet_free(&item.packet);+ items.clear();+ bytes = 0;+ firstUs = lastEndUs = lastDtsUs = INT64_MIN;+ ended = false;+ dedupe = false;+}++DemuxSession::DemuxSession() = default;++DemuxSession::~DemuxSession() {+ stop_.store(true);+ if (irq_) irq_->stop.store(true);+ producerCv_.notify_all();+ consumerCv_.notify_all();+ seekCv_.notify_all();+ if (thread_.joinable()) thread_.join();+ video_.clear();+ audio_.clear();+ for (auto& item : pendingAudio_) av_packet_free(&item.packet);+ closeContext();+}++// ---------------------------------------------------------------------------+// Opening+// ---------------------------------------------------------------------------+void DemuxSession::closeContext() {+ // AVFMT_FLAG_CUSTOM_IO keeps FFmpeg from closing our AVIO; it is freed with file_.+ if (context_) avformat_close_input(&context_);+ file_.reset();+}++bool DemuxSession::openContext(std::wstring* error, bool initial) {+ closeContext();+ AVFormatContext* context = avformat_alloc_context();+ if (!context) {+ if (error) *error = L"无法分配媒体上下文";+ return false;+ }+ context->interrupt_callback = {&Interrupt::callback, irq_.get()};+ AVDictionary* options = nullptr;+ const std::string name = utf8(path_);+ if (network_) {+ networkMediaOptions(&options);+ // Short drops are retried inside FFmpeg's HTTP layer first; this session's+ // reconnect (recover()) only takes over when they run out.+ av_dict_set(&options, "reconnect", "1", 0);+ av_dict_set(&options, "reconnect_streamed", "1", 0);+ av_dict_set(&options, "reconnect_on_network_error", "1", 0);+ av_dict_set(&options, "reconnect_delay_max", "4", 0);+ av_dict_set(&options, "seg_max_retry", "3", 0); // HLS segments+ av_dict_set(&options, "multiple_requests", "1", 0);+ } else {+ file_ = std::make_unique<FileAvio>();+ if (!file_->open(path_, irq_.get())) {+ file_.reset();+ avformat_free_context(context);+ av_dict_free(&options);+ if (error) *error = L"无法打开视频文件,请检查路径和网络共享是否可访问";+ return false;+ }+ context->pb = file_->avio;+ context->flags |= AVFMT_FLAG_CUSTOM_IO;+ }+ irq_->arm(kConnectTimeoutMs);+ int result = avformat_open_input(&context, name.c_str(), nullptr, &options);+ av_dict_free(&options);+ const bool timedOut = irq_->timedOut();+ irq_->disarm();+ if (result < 0) { // avformat_open_input freed the context+ log::error("net-session", std::format("open failed code={} text={} timedOut={} initial={}", result, errorText(result), timedOut, initial));+ file_.reset();+ if (error) *error = irq_->cancelled() ? L"已取消" : timedOut ? L"连接服务器超时(15 秒内没有响应),请检查地址和网络" : L"无法连接到服务器或地址不可用,请检查网络";+ return false;+ }+ irq_->arm(kProbeTimeoutMs);+ result = avformat_find_stream_info(context, nullptr);+ const bool probeTimedOut = irq_->timedOut();+ irq_->disarm();+ if (result < 0) {+ log::error("net-session", std::format("find_stream_info failed code={} text={} timedOut={}", result, errorText(result), probeTimedOut));+ avformat_close_input(&context);+ file_.reset();+ if (error) *error = irq_->cancelled() ? L"已取消" : probeTimedOut ? L"读取媒体信息超时(30 秒),服务器太慢或不是视频流" : L"无法读取媒体信息,地址可能不是视频";+ return false;+ }+ context_ = context;+ ++connections_;+ return true;+}++std::shared_ptr<DemuxSession> DemuxSession::open(const OpenParams& params, std::wstring* error) {+ std::shared_ptr<DemuxSession> session(new DemuxSession());+ auto& s = *session;+ s.path_ = params.path;+ s.settings_ = params.settings;+ s.cancelled_ = params.cancelled;+ s.network_ = networkMediaInput(params.path);+ s.irq_ = std::make_unique<Interrupt>();+ s.irq_->owner = params.cancelled;+ s.reconnectBudgetMs_ = int64_t(envNumber(L"VEYRA_TEST_RECONNECT_BUDGET_MS", 60000));+ std::wstring failure;+ if (!s.openContext(&failure, true)) {+ if (error) *error = failure;+ return nullptr;+ }+ AVFormatContext* context = s.context_;+ const int video = av_find_best_stream(context, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);+ if (video < 0) {+ log::error("net-session", "no video stream");+ if (error) *error = L"该地址没有视频流";+ return nullptr;+ }+ int audio = params.audioStream;+ if (audio == -2) audio = av_find_best_stream(context, AVMEDIA_TYPE_AUDIO, -1, video, nullptr, 0);+ if (audio < 0 || unsigned(audio) >= context->nb_streams || context->streams[audio]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) audio = -1;+ s.videoIndex_ = video;+ s.audioIndex_.store(audio);+ s.streams_.resize(context->nb_streams);+ for (unsigned i = 0; i < context->nb_streams; ++i) {+ const AVStream* st = context->streams[i];+ auto& info = s.streams_[i];+ info.index = int(i);+ info.type = st->codecpar->codec_type;+ info.parameters.reset(avcodec_parameters_alloc());+ if (info.parameters) avcodec_parameters_copy(info.parameters.get(), st->codecpar);+ info.timeBaseNum = st->time_base.num;+ info.timeBaseDen = std::max(st->time_base.den, 1);+ info.avgRateNum = st->avg_frame_rate.num;+ info.avgRateDen = st->avg_frame_rate.den;+ info.nominalRateNum = st->r_frame_rate.num;+ info.nominalRateDen = st->r_frame_rate.den;+ info.sarNum = st->sample_aspect_ratio.num;+ info.sarDen = st->sample_aspect_ratio.den;+ info.duration = st->duration;+ if (const auto* e = av_dict_get(st->metadata, "language", nullptr, 0)) info.language = e->value;+ if (const auto* e = av_dict_get(st->metadata, "title", nullptr, 0)) info.title = e->value;+ if (const auto* e = av_dict_get(st->metadata, "rotate", nullptr, 0)) info.rotate = e->value;+ }+ s.durationUs_ = context->duration == AV_NOPTS_VALUE ? 0 : context->duration;+ s.containerBitRate_ = context->bit_rate;+ s.formatName_ = context->iformat && context->iformat->name ? context->iformat->name : "";+ const bool byteSeekable = context->pb && (context->pb->seekable & AVIO_SEEKABLE_NORMAL);+ const bool hls = s.formatName_.find("hls") != std::string::npos || s.formatName_.find("applehttp") != std::string::npos;+ // A source with a known length that can be repositioned is on demand; anything+ // else (RTSP, HTTP-TS without length, live HLS) is live: no seek, no resume point.+ s.live_ = !(s.durationUs_ > 0 && (byteSeekable || hls));+ if (s.network_ && s.formatName_.find("rtsp") != std::string::npos) s.live_ = true;+ s.plan_ = networkBufferPlan(s.settings_, s.live_);+ {+ std::lock_guard lock(s.m_);+ s.targetSeconds_ = s.plan_.holds ? s.plan_.startSeconds : 0.0;+ s.phase_ = s.targetSeconds_ > 0 ? Phase::Prebuffering : Phase::Playing;+ s.phaseSinceNs_ = nowNs();+ }+ // Streams nobody reads must not be downloaded: an HLS master playlist lists every+ // quality as streams of the same context, and the demuxer fetches all that are+ // not discarded.+ for (unsigned i = 0; i < context->nb_streams; ++i)+ context->streams[i]->discard = (int(i) == video || int(i) == audio) ? AVDISCARD_DEFAULT : AVDISCARD_ALL;+ log::info("net-session", std::format("opened format={} live={} durationUs={} containerBitRate={} videoStream={} audioStream={} streams={} startSeconds={:.1f} aheadSeconds={:.1f} aheadMiB={} holds={} autoReconnect={}",+ s.formatName_, s.live_, s.durationUs_, s.containerBitRate_, video, audio, context->nb_streams, s.plan_.startSeconds,+ s.plan_.aheadSeconds, s.plan_.aheadBytes >> 20, s.plan_.holds, s.settings_.autoReconnect));+ s.thread_ = std::thread([raw = &s] { raw->threadMain(); });+ return session;+}++// ---------------------------------------------------------------------------+// Shared-state arithmetic (m_ held)+// ---------------------------------------------------------------------------+bool DemuxSession::endedLocked() const { return eof_ || failed_; }++double DemuxSession::aheadSecondsLocked() const {+ return settings_.level == NetworkBufferLevel::Auto && bandwidthLow_ ? plan_.growSeconds : plan_.aheadSeconds;+}+uint64_t DemuxSession::aheadBytesLocked() const {+ return settings_.level == NetworkBufferLevel::Auto && bandwidthLow_ ? plan_.growBytes : plan_.aheadBytes;+}++double DemuxSession::leadSecondsLocked() const {+ const int64_t position = playbackUs_;+ double best = std::numeric_limits<double>::infinity();+ auto consider = [&](const Queue& q) {+ if (q.lastEndUs == INT64_MIN || q.firstUs == INT64_MIN) {+ best = 0;+ return;+ }+ const int64_t from = position < 0 || position < q.firstUs ? q.firstUs : position;+ best = std::min(best, std::max(0.0, double(q.lastEndUs - from) / 1e6));+ };+ consider(video_);+ if (audioIndex_.load() >= 0 && !audio_.ended) consider(audio_);+ return std::isfinite(best) ? best : 0.0;+}++void DemuxSession::noteArrivalLocked(size_t bytes) {+ const int64_t now = nowNs();+ arrivals_.push_back({now, bytes});+ while (!arrivals_.empty() && now - arrivals_.front().ns > 3000000000ll) arrivals_.pop_front();+ totalBytes_ += bytes;+}++double DemuxSession::serverRateLocked() const {+ return readSecondsDecayed_ >= 0.2 ? readBytesDecayed_ / readSecondsDecayed_ : 0.0;+}++double DemuxSession::bitrateLocked(double* measured) const {+ double rate = 0;+ if (measured) *measured = 0;+ if (rateSamples_.size() >= 2) {+ const auto& first = rateSamples_.front();+ const auto& last = rateSamples_.back();+ const double seconds = double(last.contentUs - first.contentUs) / 1e6;+ if (seconds >= 3.0) {+ rate = double(last.cumulativeBytes - first.cumulativeBytes) / seconds;+ if (measured) *measured = rate;+ }+ }+ if (rate <= 0 && containerBitRate_ > 0) rate = double(containerBitRate_) / 8.0;+ return rate;+}++double DemuxSession::resumeTargetLocked() const {+ double target = std::max(plan_.startSeconds, 1.0);+ if (bandwidthLow_) {+ const double bitrate = bitrateLocked(nullptr), server = serverRateLocked();+ if (bitrate > 0 && server > 0) {+ // Playing at the stream's speed drains the buffer by (1 - server/bitrate) per second:+ // collect enough to play about a minute before the next stop.+ const double ratio = std::clamp(server / bitrate, 0.02, 1.0);+ target = std::max(target, 60.0 * (1.0 - ratio));+ }+ }+ return std::min(target, std::max(1.0, aheadSecondsLocked() - 0.5));+}++void DemuxSession::enterPhaseLocked(Phase phase, const char* why) {+ if (phase == phase_) return;+ const int64_t now = nowNs();+ log::info("net-session", std::format("phase {} -> {} ({}) lead={:.2f}s target={:.2f}s bandwidthLow={} stalls={}",+ phase_ == Phase::Playing ? "playing" : phase_ == Phase::Buffering ? "buffering" : "prebuffering",+ phase == Phase::Playing ? "playing" : phase == Phase::Buffering ? "buffering" : "prebuffering", why,+ leadSecondsLocked(), targetSeconds_, bandwidthLow_, stalls_));+ phase_ = phase;+ phaseSinceNs_ = now;+ consumerCv_.notify_all();+ producerCv_.notify_all();+}++void DemuxSession::updatePhaseLocked() {+ // Bandwidth verdict (hysteresis): the server delivers less than the stream needs.+ {+ const double bitrate = bitrateLocked(nullptr), server = serverRateLocked();+ if (bitrate > 0 && readSecondsDecayed_ >= 3.0) {+ if (!bandwidthLow_ && server < bitrate * 0.95) {+ bandwidthLow_ = true;+ log::warn("net-session", std::format("server slower than the stream: server {:.2f} MB/s < bitrate {:.2f} MB/s", server / 1048576.0, bitrate / 1048576.0));+ } else if (bandwidthLow_ && server > bitrate * 1.1) {+ bandwidthLow_ = false;+ log::info("net-session", std::format("server fast enough again: server {:.2f} MB/s, bitrate {:.2f} MB/s", server / 1048576.0, bitrate / 1048576.0));+ }+ }+ }+ const double lead = leadSecondsLocked();+ const bool ended = endedLocked();+ const uint64_t queued = video_.bytes + audio_.bytes;+ const bool capacity = lead >= aheadSecondsLocked() - 0.05 || queued >= aheadBytesLocked();+ switch (phase_) {+ case Phase::Prebuffering:+ if (!plan_.holds || ended || lead >= targetSeconds_ || capacity) enterPhaseLocked(Phase::Playing, ended ? "end of data" : capacity ? "window full" : "target reached");+ break;+ case Phase::Playing:+ if (plan_.holds && !ended && lead < plan_.lowWaterSeconds) {+ ++stalls_;+ targetSeconds_ = resumeTargetLocked();+ enterPhaseLocked(Phase::Buffering, "underflow");+ }+ break;+ case Phase::Buffering:+ if (!plan_.holds || ended || lead >= targetSeconds_ || capacity) enterPhaseLocked(Phase::Playing, ended ? "end of data" : capacity ? "window full" : "target reached");+ else targetSeconds_ = resumeTargetLocked();+ break;+ }+}++bool DemuxSession::flowBlockedLocked() const {+ if (endedLocked()) return true;+ const uint64_t queued = video_.bytes + audio_.bytes;+ if (queued >= aheadBytesLocked()) return true;+ return leadSecondsLocked() >= aheadSecondsLocked();+}++void DemuxSession::logSummaryLocked(bool force) {+ const int64_t now = nowNs();+ if (!force && now - lastSummaryNs_ < 1000000000ll) return;+ lastSummaryNs_ = now;+ double measured = 0;+ const double bitrate = bitrateLocked(&measured);+ double arrivalBytes = 0;+ for (const auto& a : arrivals_) arrivalBytes += double(a.bytes);+ log::info("net-buffer", std::format("state={} leadSec={:.2f} targetSec={:.2f} videoQ={} audioQ={} queuedMiB={:.1f} downloadMBps={:.2f} serverMBps={:.2f} bitrateMBps={:.2f} bandwidthLow={} reconnects={} attempt={} stalls={} corruptPackets={} totalMiB={:.1f} eof={} failed={}",+ reconnecting_ ? "reconnecting" : phase_ == Phase::Playing ? "playing" : phase_ == Phase::Buffering ? "buffering" : "prebuffering",+ leadSecondsLocked(), targetSeconds_, video_.items.size(), audio_.items.size(), double(video_.bytes + audio_.bytes) / 1048576.0,+ arrivalBytes / 3.0 / 1048576.0, serverRateLocked() / 1048576.0, bitrate / 1048576.0, bandwidthLow_, reconnects_, reconnectAttempt_, stalls_,+ corruptPackets_, double(totalBytes_) / 1048576.0, eof_, failed_));+}++// ---------------------------------------------------------------------------+// Consumers+// ---------------------------------------------------------------------------+DemuxSession::Pop DemuxSession::popVideo(AVPacket* dst, Meta& meta, int waitMs, bool honourHold) {+ std::unique_lock lock(m_);+ const auto deadline = Clock::now() + std::chrono::milliseconds(std::max(waitMs, 0));+ for (;;) {+ if (stop_.load() || (cancelled_ && cancelled_->load())) return Pop::Cancelled;+ updatePhaseLocked();+ const bool hold = honourHold && phase_ != Phase::Playing;+ if (!hold && !video_.items.empty()) {+ Item item = std::move(video_.items.front());+ video_.items.pop_front();+ video_.bytes -= item.bytes;+ av_packet_move_ref(dst, item.packet);+ av_packet_free(&item.packet);+ meta.discontinuity = item.discontinuity;+ meta.generation = item.generation;+ producerCv_.notify_one();+ return Pop::Packet;+ }+ if (video_.items.empty() && endedLocked()) return failed_ ? Pop::Failed : Pop::Eof;+ if (waitMs <= 0 || Clock::now() >= deadline) return Pop::Empty;+ consumerCv_.wait_until(lock, deadline);+ }+}++DemuxSession::Pop DemuxSession::popAudio(AVPacket* dst, Meta& meta, int waitMs) {+ std::unique_lock lock(m_);+ const auto deadline = Clock::now() + std::chrono::milliseconds(std::max(waitMs, 0));+ for (;;) {+ if (stop_.load() || (cancelled_ && cancelled_->load())) return Pop::Cancelled;+ if (audioIndex_.load() < 0) return Pop::Eof;+ if (!audio_.items.empty()) {+ Item item = std::move(audio_.items.front());+ audio_.items.pop_front();+ audio_.bytes -= item.bytes;+ av_packet_move_ref(dst, item.packet);+ av_packet_free(&item.packet);+ meta.discontinuity = item.discontinuity;+ meta.generation = item.generation;+ producerCv_.notify_one();+ return Pop::Packet;+ }+ if (endedLocked()) return failed_ ? Pop::Failed : Pop::Eof;+ if (waitMs <= 0 || Clock::now() >= deadline) return Pop::Empty;+ consumerCv_.wait_until(lock, deadline);+ }+}++bool DemuxSession::selectAudioStream(int index) {+ if (index >= 0 && (size_t(index) >= streams_.size() || streams_[size_t(index)].type != AVMEDIA_TYPE_AUDIO)) return false;+ std::lock_guard lock(m_);+ if (audioIndex_.load() == index) return true;+ audioIndex_.store(index);+ audio_.clear();+ discardDirty_ = true;+ producerCv_.notify_all();+ return true;+}++void DemuxSession::setPlaybackPositionUs(int64_t us) {+ if (us < 0) return;+ std::lock_guard lock(m_);+ playbackUs_ = us;+ updatePhaseLocked();+ producerCv_.notify_one();+}++bool DemuxSession::seek(int64_t targetUs) {+ if (live_) return false;+ std::unique_lock lock(m_);+ if (failed_ && !settings_.autoReconnect) return false;+ seekTargetUs_ = std::max<int64_t>(0, targetUs);+ seekPending_ = true;+ seekDone_ = false;+ seekOk_ = false;+ irq_->command.store(true);+ producerCv_.notify_all();+ // Poll the owner's stop flag: nothing notifies this wait when it is set.+ while (!seekDone_) {+ if (stop_.load() || (cancelled_ && cancelled_->load())) return false;+ seekCv_.wait_for(lock, std::chrono::milliseconds(50));+ }+ return seekOk_;+}++void DemuxSession::requestReconnect(const char* reason) {+ std::lock_guard lock(m_);+ if (reconnecting_ || reconnectPending_ || failed_) return;+ reconnectPending_ = true;+ reconnectReason_ = reason ? reason : "requested";+ irq_->command.store(true);+ producerCv_.notify_all();+}++bool DemuxSession::holding() const {+ std::lock_guard lock(m_);+ const_cast<DemuxSession*>(this)->updatePhaseLocked();+ return phase_ != Phase::Playing;+}++void DemuxSession::addCorruptFrames(uint64_t flagged, uint64_t skipped) {+ std::lock_guard lock(m_);+ corruptFrames_ += flagged;+ skippedFrames_ += skipped;+}++std::wstring DemuxSession::failureMessage() const {+ std::lock_guard lock(m_);+ return failure_;+}++bool DemuxSession::eof() const {+ std::lock_guard lock(m_);+ return eof_;+}++NetworkStats DemuxSession::stats() const {+ std::lock_guard lock(m_);+ NetworkStats out;+ out.active = true;+ out.live = live_;+ out.bufferedSeconds = leadSecondsLocked();+ out.targetSeconds = targetSeconds_;+ out.bufferedBytes = video_.bytes + audio_.bytes;+ out.capBytes = aheadBytesLocked();+ double arrivalBytes = 0;+ int64_t oldest = nowNs();+ for (const auto& a : arrivals_) {+ arrivalBytes += double(a.bytes);+ oldest = std::min(oldest, a.ns);+ }+ const double window = std::clamp(double(nowNs() - oldest) / 1e9, 1.0, 3.0);+ out.downloadBytesPerSecond = arrivalBytes / window;+ out.serverBytesPerSecond = serverRateLocked();+ out.bitrateBytesPerSecond = bitrateLocked(nullptr);+ out.bandwidthLow = bandwidthLow_;+ out.reconnects = reconnects_;+ out.reconnectAttempt = reconnecting_ ? reconnectAttempt_ : 0;+ out.stalls = stalls_;+ out.corruptPackets = corruptPackets_;+ out.corruptFrames = corruptFrames_;+ out.skippedFrames = skippedFrames_;+ out.sessionBytes = totalBytes_;+ out.connections = connections_;+ if (failed_) {+ out.state = NetworkStats::State::Failed;+ out.message = failure_;+ } else if (reconnecting_) {+ out.state = NetworkStats::State::Reconnecting;+ out.message = std::format(L"网络中断,正在重连(第 {} 次)", reconnectAttempt_ ? reconnectAttempt_ : 1u);+ } else if (eof_ && video_.items.empty()) {+ out.state = NetworkStats::State::Ended;+ } else if (phase_ == Phase::Prebuffering) {+ out.state = NetworkStats::State::Prebuffering;+ out.message = std::format(L"正在缓冲 {:.1f}/{:.1f} 秒", out.bufferedSeconds, targetSeconds_);+ } else if (phase_ == Phase::Buffering) {+ out.state = NetworkStats::State::Buffering;+ out.message = std::format(L"网络缓冲中 {:.1f}/{:.1f} 秒", out.bufferedSeconds, targetSeconds_);+ } else {+ out.state = NetworkStats::State::Playing;+ }+ if (bandwidthLow_ && (out.state == NetworkStats::State::Buffering || out.state == NetworkStats::State::Prebuffering)) {+ out.message += std::format(L";服务器速度 {:.1f} MB/s 低于视频码率 {:.1f} MB/s,建议加大缓冲或下载后播放",+ out.serverBytesPerSecond / 1048576.0, out.bitrateBytesPerSecond / 1048576.0);+ }+ return out;+}++// ---------------------------------------------------------------------------+// Demux thread+// ---------------------------------------------------------------------------+void DemuxSession::fail(const std::wstring& message) {+ log::error("net-session", std::format("session failed: {}", utf8(message)));+ std::lock_guard lock(m_);+ failed_ = true;+ reconnecting_ = false;+ failure_ = message;+ updatePhaseLocked();+ consumerCv_.notify_all();+ seekCv_.notify_all();+}++void DemuxSession::applyDiscardFlags() {+ if (!context_) return;+ const int video = videoIndex_, audio = audioIndex_.load();+ for (unsigned i = 0; i < context_->nb_streams; ++i)+ context_->streams[i]->discard = (int(i) == video || int(i) == audio) ? AVDISCARD_DEFAULT : AVDISCARD_ALL;+}++// The reconnected source must offer the streams the consumers already rely on.+bool DemuxSession::verifyStreams() {+ if (!context_ || unsigned(videoIndex_) >= context_->nb_streams) return false;+ auto matches = [&](int index) {+ if (index < 0) return true;+ if (unsigned(index) >= context_->nb_streams || size_t(index) >= streams_.size()) return false;+ const auto* parameters = context_->streams[index]->codecpar;+ const auto& known = streams_[size_t(index)];+ return parameters->codec_type == known.type && known.parameters && parameters->codec_id == known.parameters->codec_id;+ };+ if (!matches(videoIndex_) || !matches(audioIndex_.load())) {+ log::warn("net-session", "reconnected source does not offer the same video/audio streams");+ return false;+ }+ const auto* now = context_->streams[videoIndex_]->codecpar;+ const auto* before = streams_[size_t(videoIndex_)].parameters.get();+ if (before && (now->width != before->width || now->height != before->height)) {+ log::warn("net-session", std::format("reconnected source changed picture size {}x{} -> {}x{}", before->width, before->height, now->width, now->height));+ return false;+ }+ applyDiscardFlags();+ return true;+}++void DemuxSession::threadMain() {+ AVPacket* packet = av_packet_alloc();+ while (!stop_.load()) {+ enum class Work { Read, Seek, Reconnect, Idle, Stop } work = Work::Idle;+ {+ std::unique_lock lock(m_);+ for (;;) {+ if (stop_.load()) {+ work = Work::Stop;+ break;+ }+ if (cancelled_ && cancelled_->load()) { // the engine stopped: nothing will read any more+ consumerCv_.notify_all();+ producerCv_.wait_for(lock, std::chrono::milliseconds(100));+ continue;+ }+ if (seekPending_) {+ work = Work::Seek;+ break;+ }+ if (reconnectPending_) {+ work = Work::Reconnect;+ break;+ }+ if (discardDirty_) {+ discardDirty_ = false;+ lock.unlock();+ applyDiscardFlags();+ lock.lock();+ continue;+ }+ updatePhaseLocked();+ logSummaryLocked(false);+ if (!flowBlockedLocked() && context_) {+ work = Work::Read;+ break;+ }+ if (!context_ && !endedLocked()) { // disconnected and nothing is pending: reconnect now+ work = Work::Reconnect;+ reconnectReason_ = "no connection";+ break;+ }+ producerCv_.wait_for(lock, std::chrono::milliseconds(100));+ }+ }+ if (work == Work::Stop) break;+ if (work == Work::Seek) {+ doSeek();+ continue;+ }+ if (work == Work::Reconnect) {+ std::string why;+ {+ std::lock_guard lock(m_);+ why = reconnectReason_;+ reconnectPending_ = false;+ }+ irq_->command.store(false);+ recover(0, why.c_str());+ continue;+ }+ // Read one packet.+ irq_->arm(live_ ? kReadTimeoutLiveMs : kReadTimeoutVodMs);+ const auto begin = Clock::now();+ const int result = av_read_frame(context_, packet);+ const bool timedOut = irq_->timedOut();+ irq_->disarm();+ const double seconds = std::chrono::duration<double>(Clock::now() - begin).count();+ if (result >= 0) {+ {+ std::lock_guard lock(m_);+ const int64_t now = nowNs();+ const double dt = lastRateNs_ ? double(now - lastRateNs_) / 1e9 : 0.0;+ const double keep = std::exp(-dt / 6.0);+ readBytesDecayed_ = readBytesDecayed_ * keep + double(packet->size);+ readSecondsDecayed_ = readSecondsDecayed_ * keep + seconds;+ lastRateNs_ = now;+ }+ onPacket(packet);+ continue;+ }+ if (stop_.load()) break;+ {+ std::lock_guard lock(m_);+ if (seekPending_ || reconnectPending_) continue; // our own command interrupted the read+ }+ if (cancelled_ && cancelled_->load()) continue;+ if (result == AVERROR_EOF) {+ std::lock_guard lock(m_);+ eof_ = true;+ video_.ended = true;+ audio_.ended = true;+ log::info("net-session", std::format("end of stream: video queued {} audio queued {}", video_.items.size(), audio_.items.size()));+ updatePhaseLocked();+ consumerCv_.notify_all();+ continue;+ }+ log::warn("net-session", std::format("read failed code={} text={} timedOut={}", result, errorText(result), timedOut));+ recover(result, timedOut ? "read timeout" : "read error");+ }+ av_packet_free(&packet);+}++void DemuxSession::flushPendingAudio(int64_t anchorUs) {+ // Called when the live gate opens: pending audio starts at the keyframe time.+ const int audio = audioIndex_.load();+ if (audio < 0 || size_t(audio) >= streams_.size()) {+ for (auto& item : pendingAudio_) av_packet_free(&item.packet);+ pendingAudio_.clear();+ pendingAudioBytes_ = 0;+ return;+ }+ const AVRational tb{streams_[size_t(audio)].timeBaseNum, streams_[size_t(audio)].timeBaseDen};+ const int64_t offsetTb = av_rescale_q(offsetUs_, AV_TIME_BASE_Q, tb);+ for (auto& item : pendingAudio_) {+ if (item.startUs + 5000 < anchorUs) {+ av_packet_free(&item.packet);+ continue;+ }+ if (item.packet->pts != AV_NOPTS_VALUE) item.packet->pts += offsetTb;+ if (item.packet->dts != AV_NOPTS_VALUE) item.packet->dts += offsetTb;+ item.startUs += offsetUs_;+ item.endUs += offsetUs_;+ if (item.dtsUs != AV_NOPTS_VALUE) item.dtsUs += offsetUs_;+ item.generation = generation_.load();+ item.discontinuity = audioDiscontinuityPending_;+ audioDiscontinuityPending_ = false;+ std::lock_guard lock(m_);+ pushLocked(std::move(item), false);+ }+ pendingAudio_.clear();+ pendingAudioBytes_ = 0;+}++void DemuxSession::onPacket(AVPacket* pkt) {+ const int index = pkt->stream_index;+ const bool isVideo = index == videoIndex_;+ const bool isAudio = index == audioIndex_.load();+ const SessionStreamInfo* info = stream(index);+ if (!info || (!isVideo && !isAudio)) {+ av_packet_unref(pkt);+ return;+ }+ const AVRational tb{info->timeBaseNum, info->timeBaseDen};+ const int64_t stamp = pkt->pts != AV_NOPTS_VALUE ? pkt->pts : pkt->dts;+ int64_t startUs = toUs(stamp, tb);+ int64_t dtsUs = toUs(pkt->dts != AV_NOPTS_VALUE ? pkt->dts : pkt->pts, tb);+ // Estimated duration when the container leaves it out.+ int64_t durationUs = pkt->duration > 0 ? av_rescale_q(pkt->duration, tb, AV_TIME_BASE_Q) : 0;+ if (durationUs <= 0) {+ if (isVideo) {+ const int num = info->avgRateNum > 0 ? info->avgRateNum : info->nominalRateNum;+ const int den = info->avgRateDen > 0 ? info->avgRateDen : info->nominalRateDen;+ durationUs = num > 0 && den > 0 ? int64_t(1e6 * double(den) / double(num)) : 40000;+ } else {+ const auto* params = info->parameters.get();+ durationUs = params && params->frame_size > 0 && params->sample_rate > 0 ? int64_t(1e6 * params->frame_size / params->sample_rate) : 21333;+ }+ }+ Queue& queue = isVideo ? video_ : audio_;+ // ---- live reconnect: wait for a video keyframe, then continue the old timeline ----+ if (gateKeyframe_) {+ if (isVideo) {+ if (!(pkt->flags & AV_PKT_FLAG_KEY) || startUs == AV_NOPTS_VALUE) {+ av_packet_unref(pkt);+ return;+ }+ int64_t previousEnd;+ {+ std::lock_guard lock(m_);+ previousEnd = std::max(video_.lastEndUs, audio_.lastEndUs); // INT64_MIN: nothing was ever queued+ }+ offsetUs_ = previousEnd == INT64_MIN ? 0 : previousEnd - startUs;+ gateKeyframe_ = false;+ videoDiscontinuityPending_ = true;+ audioDiscontinuityPending_ = true;+ log::info("net-session", std::format("live reconnect: keyframe found, timeline offset {} ms", offsetUs_ / 1000));+ flushPendingAudio(startUs);+ } else {+ if (startUs == AV_NOPTS_VALUE || pendingAudioBytes_ > (8 << 20)) {+ av_packet_unref(pkt);+ return;+ }+ Item item;+ item.packet = av_packet_alloc();+ if (!item.packet) {+ av_packet_unref(pkt);+ return;+ }+ av_packet_move_ref(item.packet, pkt);+ item.startUs = startUs;+ item.endUs = startUs + durationUs;+ item.dtsUs = dtsUs;+ item.bytes = size_t(item.packet->size);+ pendingAudioBytes_ += int64_t(item.bytes);+ pendingAudio_.push_back(std::move(item));+ return;+ }+ }+ if (offsetUs_) {+ const int64_t offsetTb = av_rescale_q(offsetUs_, AV_TIME_BASE_Q, tb);+ if (pkt->pts != AV_NOPTS_VALUE) pkt->pts += offsetTb;+ if (pkt->dts != AV_NOPTS_VALUE) pkt->dts += offsetTb;+ if (startUs != AV_NOPTS_VALUE) startUs += offsetUs_;+ if (dtsUs != AV_NOPTS_VALUE) dtsUs += offsetUs_;+ }+ // ---- VOD reconnect: skip what was queued before the connection dropped ----+ if (queue.dedupe) {+ if (dtsUs != AV_NOPTS_VALUE && queue.lastDtsUs != INT64_MIN && dtsUs <= queue.lastDtsUs) {+ av_packet_unref(pkt);+ return;+ }+ queue.dedupe = false;+ }+ Item item;+ item.packet = av_packet_alloc();+ if (!item.packet) {+ av_packet_unref(pkt);+ return;+ }+ av_packet_move_ref(item.packet, pkt);+ if (startUs == AV_NOPTS_VALUE) startUs = queue.lastEndUs != INT64_MIN ? queue.lastEndUs : 0;+ item.startUs = startUs;+ item.endUs = startUs + durationUs;+ item.bytes = size_t(item.packet->size);+ item.generation = generation_.load();+ if (isVideo && videoDiscontinuityPending_) {+ item.discontinuity = true;+ videoDiscontinuityPending_ = false;+ } else if (isAudio && audioDiscontinuityPending_) {+ item.discontinuity = true;+ audioDiscontinuityPending_ = false;+ }+ item.dtsUs = dtsUs;+ std::lock_guard lock(m_);+ pushLocked(std::move(item), isVideo);+}++bool DemuxSession::pushLocked(Item&& item, bool video) {+ Queue& queue = video ? video_ : audio_;+ if (item.packet->flags & AV_PKT_FLAG_CORRUPT) {+ if (video) ++corruptPackets_;+ }+ if (queue.firstUs == INT64_MIN) queue.firstUs = item.startUs;+ queue.lastEndUs = std::max(queue.lastEndUs, item.endUs);+ if (item.dtsUs != AV_NOPTS_VALUE) queue.lastDtsUs = item.dtsUs;+ queue.bytes += item.bytes;+ noteArrivalLocked(item.bytes);+ contentBytes_ += item.bytes;+ if (video) {+ if (rateSamples_.empty() || item.endUs - rateSamples_.back().contentUs >= 500000) rateSamples_.push_back({item.endUs, contentBytes_});+ while (rateSamples_.size() > 2 && rateSamples_.back().contentUs - rateSamples_[1].contentUs > 12000000) rateSamples_.pop_front();+ }+ queue.items.push_back(std::move(item));+ updatePhaseLocked();+ consumerCv_.notify_all();+ return true;+}++// ---------------------------------------------------------------------------+// Seek and reconnect (demux thread)+// ---------------------------------------------------------------------------+void DemuxSession::doSeek() {+ int64_t target;+ {+ std::lock_guard lock(m_);+ target = seekTargetUs_;+ seekPending_ = false;+ }+ irq_->command.store(false);+ bool ok = false;+ {+ std::lock_guard lock(m_);+ video_.clear();+ audio_.clear();+ for (auto& item : pendingAudio_) av_packet_free(&item.packet);+ pendingAudio_.clear();+ pendingAudioBytes_ = 0;+ generation_.fetch_add(1);+ eof_ = false;+ playbackUs_ = target;+ rateSamples_.clear();+ contentBytes_ = 0;+ afterSeek_ = true;+ targetSeconds_ = plan_.holds ? std::min(plan_.startSeconds, 5.0) : 0.0;+ phase_ = targetSeconds_ > 0 ? Phase::Prebuffering : Phase::Playing;+ phaseSinceNs_ = nowNs();+ }+ gateKeyframe_ = false;+ videoDiscontinuityPending_ = audioDiscontinuityPending_ = false;+ offsetUs_ = 0;+ for (int attempt = 0; attempt < 2 && !ok && !stop_.load() && !(cancelled_ && cancelled_->load()); ++attempt) {+ if (!context_) {+ std::wstring error;+ if (!openContext(&error, false) || !verifyStreams()) {+ closeContext();+ break;+ }+ }+ const auto& v = streams_[size_t(videoIndex_)];+ const int64_t ts = av_rescale_q(target, AV_TIME_BASE_Q, AVRational{v.timeBaseNum, v.timeBaseDen});+ irq_->arm(kConnectTimeoutMs + kReadTimeoutVodMs);+ const int result = av_seek_frame(context_, videoIndex_, ts, AVSEEK_FLAG_BACKWARD);+ irq_->disarm();+ ok = result >= 0;+ if (!ok) {+ log::warn("net-session", std::format("seek to {} ms failed code={} text={} attempt={}", target / 1000, result, errorText(result), attempt));+ if (irq_->command.load()) break;+ closeContext(); // the next attempt reconnects+ }+ }+ {+ std::lock_guard lock(m_);+ seekOk_ = ok;+ seekDone_ = true;+ seekCv_.notify_all();+ updatePhaseLocked();+ consumerCv_.notify_all();+ }+ log::info("net-session", std::format("seek to {} ms ok={} generation={}", target / 1000, ok, generation_.load()));+}++// Re-establishes the source after a failure, keeping everything already queued.+bool DemuxSession::recover(int code, const char* why) {+ log::warn("net-session", std::format("connection lost reason={} code={} text={}", why, code, code ? errorText(code) : std::string()));+ closeContext();+ if (!settings_.autoReconnect) {+ fail(L"网络连接中断(断线自动重连已关闭)");+ return false;+ }+ {+ std::lock_guard lock(m_);+ reconnecting_ = true;+ reconnectAttempt_ = 0;+ updatePhaseLocked();+ }+ const auto begin = Clock::now();+ int delayMs = 1000;+ uint32_t attempt = 0;+ while (!stop_.load() && !(cancelled_ && cancelled_->load())) {+ if (std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - begin).count() >= reconnectBudgetMs_) break;+ // Back off, but give way at once to a seek or a stop.+ if (!irq_->sleep(delayMs)) {+ std::lock_guard lock(m_);+ if (seekPending_) { // doSeek() reconnects as part of positioning+ reconnecting_ = false;+ return false;+ }+ if (stop_.load() || (cancelled_ && cancelled_->load())) break;+ }+ {+ std::lock_guard lock(m_);+ ++attempt;+ reconnectAttempt_ = attempt;+ }+ std::wstring error;+ bool ok = openContext(&error, false) && verifyStreams();+ if (ok) {+ if (!live_) {+ // On demand: continue after the last queued packet.+ int64_t resume;+ {+ std::lock_guard lock(m_);+ resume = video_.lastDtsUs != INT64_MIN ? video_.lastDtsUs : audio_.lastDtsUs;+ }+ if (resume != INT64_MIN) {+ const auto& v = streams_[size_t(videoIndex_)];+ const int64_t ts = av_rescale_q(std::max<int64_t>(0, resume), AV_TIME_BASE_Q, AVRational{v.timeBaseNum, v.timeBaseDen});+ irq_->arm(kConnectTimeoutMs + kReadTimeoutVodMs);+ const int result = av_seek_frame(context_, videoIndex_, ts, AVSEEK_FLAG_BACKWARD);+ irq_->disarm();+ if (result < 0) {+ log::warn("net-session", std::format("resume seek failed code={} text={}", result, errorText(result)));+ ok = false;+ } else {+ std::lock_guard lock(m_);+ video_.dedupe = video_.lastDtsUs != INT64_MIN;+ audio_.dedupe = audio_.lastDtsUs != INT64_MIN;+ }+ }+ } else {+ gateKeyframe_ = true;+ for (auto& item : pendingAudio_) av_packet_free(&item.packet);+ pendingAudio_.clear();+ pendingAudioBytes_ = 0;+ }+ }+ if (ok) {+ std::lock_guard lock(m_);+ reconnecting_ = false;+ reconnectAttempt_ = 0;+ ++reconnects_;+ eof_ = false;+ log::info("net-session", std::format("reconnected after {} attempt(s), {} ms; reconnects={} live={}", attempt,+ std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - begin).count(), reconnects_, live_));+ updatePhaseLocked();+ return true;+ }+ closeContext();+ gateKeyframe_ = false;+ delayMs = std::min(delayMs * 2, 8000);+ }+ if (stop_.load() || (cancelled_ && cancelled_->load())) return false;+ fail(std::format(L"网络连接中断,已重试 {} 秒仍无法恢复", reconnectBudgetMs_ / 1000));+ return false;+}++} // namespace veyra::mediadiff --git a/src/media/FFmpegDemuxer.cpp b/src/media/FFmpegDemuxer.cppindex 8e2b6683..d18f2762 100644--- a/src/media/FFmpegDemuxer.cpp+++ b/src/media/FFmpegDemuxer.cpp@@ -17,14 +17,63 @@ extern "C" {namespace veyra::media {+namespace {+// Rotation from the "rotate" tag or the display matrix in the stream's side data.+int rotationFrom(const AVCodecParameters* parameters, const char* rotateTag)+{+ // av_display_rotation_get reads the container's display matrix (the same+ // metadata players use); it returns degrees counter-clockwise.+ if (rotateTag != nullptr && *rotateTag != '\0') {+ const int value = std::atoi(rotateTag);+ if (value != 0) return ((value % 360) + 360) % 360;+ }+ if (parameters == nullptr) return 0;+ // FFmpeg 6+ exposes stream side data through the packet-side-data API.+ const AVPacketSideData* side = parameters->coded_side_data;+ const int sideCount = parameters->nb_coded_side_data;+ const uint8_t* matrix = nullptr;+ for (int i = 0; i < sideCount; ++i) {+ if (side[i].type == AV_PKT_DATA_DISPLAYMATRIX && side[i].size >= 9 * int(sizeof(int32_t))) { matrix = side[i].data; break; }+ }+ if (matrix == nullptr) return 0;+ const double degrees = av_display_rotation_get(reinterpret_cast<const int32_t*>(matrix));+ if (!std::isfinite(degrees)) return 0;+ int normalized = int(std::lround(-degrees)) % 360;+ if (normalized < 0) normalized += 360;+ return normalized;+}+}+FFmpegDemuxer::~FFmpegDemuxer(){close();}+bool FFmpegDemuxer::openShared(std::shared_ptr<DemuxSession> session)+{+ if (opened()) {+ close();+ }+ if (!session || session->videoStream() < 0) {+ return false;+ }+ packet_ = av_packet_alloc();+ if (packet_ == nullptr) {+ return false;+ }+ session_ = std::move(session);+ videoStreamIndex_ = session_->videoStream();+ stats_ = DemuxerStats{};+ const auto* stream = session_->stream(videoStreamIndex_);+ log::info("media", std::format("demuxer: opened shared session codecId={} streams={} videoStream={} durationUs={} timeBase={}/{} format={}",+ stream && stream->parameters ? static_cast<int>(stream->parameters->codec_id) : -1, session_->streams().size(), videoStreamIndex_,+ session_->durationUs(), stream ? stream->timeBaseNum : 0, stream ? stream->timeBaseDen : 0, session_->formatName()));+ return true;+}+bool FFmpegDemuxer::open(const std::wstring& path,const std::atomic<bool>* cancelled){- if (context_ != nullptr) {+ if (opened()) {close();}@@ -42,7 +91,7 @@ bool FFmpegDemuxer::open(const std::wstring& path,const std::atomic<bool>* canceraw->interrupt_callback={InputInterrupt::callback,&interrupt_};AVDictionary* options=nullptr;if(network)networkMediaOptions(&options);- interrupt_.arm();+ interrupt_.armConnect();const int openResult = avformat_open_input(&raw, utf8Path.c_str(), nullptr, &options);av_dict_free(&options);if (openResult < 0) {@@ -52,7 +101,7 @@ bool FFmpegDemuxer::open(const std::wstring& path,const std::atomic<bool>* cancereturn false;}- interrupt_.arm();+ interrupt_.armProbe();const int infoResult=avformat_find_stream_info(raw, nullptr);interrupt_.disarm();if (infoResult < 0) {@@ -93,12 +142,21 @@ void FFmpegDemuxer::close()if (context_ != nullptr) {avformat_close_input(&context_);}+ session_.reset();videoStreamIndex_ = -1;havePendingPacket_ = false;+ packetDiscontinuity_ = false;}int64_t FFmpegDemuxer::durationUs() const{+ if (session_) {+ const auto* stream = session_->stream(videoStreamIndex_);+ if (stream && stream->duration > 0 && stream->timeBaseDen > 0) {+ return av_rescale_q(stream->duration, { stream->timeBaseNum, stream->timeBaseDen }, { 1, 1000000 });+ }+ return session_->durationUs();+ }if (context_ == nullptr) {return 0;}@@ -110,11 +168,17 @@ int64_t FFmpegDemuxer::durationUs() const}bool FFmpegDemuxer::seekable() const {+ if (session_) return session_->seekable();return context_&&context_->pb&&(context_->pb->seekable&AVIO_SEEKABLE_NORMAL);}double FFmpegDemuxer::averageFps() const{+ if (session_) {+ const auto* stream = session_->stream(videoStreamIndex_);+ if (!stream || stream->avgRateDen == 0) return 0.0;+ return static_cast<double>(stream->avgRateNum) / stream->avgRateDen;+ }if (context_ == nullptr) {return 0.0;}@@ -126,15 +190,33 @@ double FFmpegDemuxer::averageFps() const}int FFmpegDemuxer::nominalRateNum() const {+ if (session_) {+ const auto* stream = session_->stream(videoStreamIndex_);+ return stream ? stream->nominalRateNum : 0;+ }return context_ && videoStreamIndex_ >= 0 ? context_->streams[videoStreamIndex_]->r_frame_rate.num : 0;}int FFmpegDemuxer::nominalRateDen() const {+ if (session_) {+ const auto* stream = session_->stream(videoStreamIndex_);+ return stream ? stream->nominalRateDen : 0;+ }return context_ && videoStreamIndex_ >= 0 ? context_->streams[videoStreamIndex_]->r_frame_rate.den : 0;}void FFmpegDemuxer::sampleAspect(int& num, int& den) const{num = 0; den = 0;+ if (session_) {+ const auto* stream = session_->stream(videoStreamIndex_);+ if (!stream) return;+ if (stream->sarNum > 0 && stream->sarDen > 0) { num = stream->sarNum; den = stream->sarDen; return; }+ const auto* parameters = stream->parameters.get();+ if (parameters && parameters->sample_aspect_ratio.num > 0 && parameters->sample_aspect_ratio.den > 0) {+ num = parameters->sample_aspect_ratio.num; den = parameters->sample_aspect_ratio.den;+ }+ return;+ }if (context_ == nullptr || videoStreamIndex_ < 0) return;const AVRational sar = context_->streams[videoStreamIndex_]->sample_aspect_ratio;if (sar.num > 0 && sar.den > 0) { num = sar.num; den = sar.den; return; }@@ -145,32 +227,22 @@ void FFmpegDemuxer::sampleAspect(int& num, int& den) constint FFmpegDemuxer::rotationDegrees() const{+ if (session_) {+ const auto* stream = session_->stream(videoStreamIndex_);+ return stream ? rotationFrom(stream->parameters.get(), stream->rotate.c_str()) : 0;+ }if (context_ == nullptr || videoStreamIndex_ < 0) return 0;const AVStream* stream = context_->streams[videoStreamIndex_];- // av_display_rotation_get reads the container's display matrix (the same- // metadata players use); it returns degrees counter-clockwise.const AVDictionaryEntry* rotate = av_dict_get(stream->metadata, "rotate", nullptr, 0);- if (rotate != nullptr) {- const int value = std::atoi(rotate->value);- if (value != 0) return ((value % 360) + 360) % 360;- }- // FFmpeg 6+ exposes stream side data through the packet-side-data API.- const AVPacketSideData* side = stream->codecpar->coded_side_data;- const int sideCount = stream->codecpar->nb_coded_side_data;- const uint8_t* matrix = nullptr;- for (int i = 0; i < sideCount; ++i) {- if (side[i].type == AV_PKT_DATA_DISPLAYMATRIX && side[i].size >= 9 * int(sizeof(int32_t))) { matrix = side[i].data; break; }- }- if (matrix == nullptr) return 0;- const double degrees = av_display_rotation_get(reinterpret_cast<const int32_t*>(matrix));- if (!std::isfinite(degrees)) return 0;- int normalized = int(std::lround(-degrees)) % 360;- if (normalized < 0) normalized += 360;- return normalized;+ return rotationFrom(stream->codecpar, rotate != nullptr ? rotate->value : nullptr);}const AVCodecParameters* FFmpegDemuxer::videoCodecParameters() const{+ if (session_) {+ const auto* stream = session_->stream(videoStreamIndex_);+ return stream ? stream->parameters.get() : nullptr;+ }if (context_ == nullptr || videoStreamIndex_ < 0) {return nullptr;}@@ -179,6 +251,10 @@ const AVCodecParameters* FFmpegDemuxer::videoCodecParameters() constint FFmpegDemuxer::videoTimeBaseNum() const{+ if (session_) {+ const auto* stream = session_->stream(videoStreamIndex_);+ return stream ? stream->timeBaseNum : 0;+ }if (context_ == nullptr || videoStreamIndex_ < 0) {return 0;}@@ -187,6 +263,10 @@ int FFmpegDemuxer::videoTimeBaseNum() constint FFmpegDemuxer::videoTimeBaseDen() const{+ if (session_) {+ const auto* stream = session_->stream(videoStreamIndex_);+ return stream ? stream->timeBaseDen : 0;+ }if (context_ == nullptr || videoStreamIndex_ < 0) {return 0;}@@ -195,15 +275,50 @@ int FFmpegDemuxer::videoTimeBaseDen() conststd::string FFmpegDemuxer::formatName() const{+ if (session_) {+ return session_->formatName();+ }if (context_ == nullptr || context_->iformat == nullptr || context_->iformat->name == nullptr) {return {};}return context_->iformat->name;}+void FFmpegDemuxer::notePacket()+{+ ++stats_.packetsRead;+ AVRational base{};+ if (session_) {+ const auto* stream = session_->stream(videoStreamIndex_);+ base = stream ? AVRational{stream->timeBaseNum, stream->timeBaseDen} : AVRational{1, 1000000};+ } else {+ base = context_->streams[videoStreamIndex_]->time_base;+ }+ const int64_t ptsUs = av_rescale_q(packet_->pts != AV_NOPTS_VALUE ? packet_->pts : packet_->dts, base, { 1, 1000000 });+ if (stats_.packetsRead == 1) {+ stats_.firstPts = ptsUs;+ }+ else if (ptsUs < stats_.lastPts) {+ ++stats_.ptsNonMonotonicCount;+ }+ stats_.lastPts = ptsUs;+}+bool FFmpegDemuxer::readVideoPacket(bool& endOfFile){endOfFile = false;+ if (session_) {+ // Offline / blocking consumers: wait for the session, ignore the buffering hold.+ for (;;) {+ const auto result = readVideoPacketEx(50, false);+ switch (result) {+ case ReadResult::Packet: return true;+ case ReadResult::Eof: endOfFile = true; return false;+ case ReadResult::Waiting: continue;+ default: return false;+ }+ }+ }if (context_ == nullptr) {return false;}@@ -231,22 +346,43 @@ bool FFmpegDemuxer::readVideoPacket(bool& endOfFile)av_packet_unref(packet_);continue;}- ++stats_.packetsRead;- const int64_t ptsUs = av_rescale_q(packet_->pts != AV_NOPTS_VALUE ? packet_->pts : packet_->dts,- context_->streams[videoStreamIndex_]->time_base, { 1, 1000000 });- if (stats_.packetsRead == 1) {- stats_.firstPts = ptsUs;- }- else if (ptsUs < stats_.lastPts) {- ++stats_.ptsNonMonotonicCount;- }- stats_.lastPts = ptsUs;+ notePacket();return true;}}+FFmpegDemuxer::ReadResult FFmpegDemuxer::readVideoPacketEx(int waitMs, bool honourHold)+{+ if (!session_) {+ bool eof = false;+ if (readVideoPacket(eof)) return ReadResult::Packet;+ return eof ? ReadResult::Eof : ReadResult::Error;+ }+ av_packet_unref(packet_);+ DemuxSession::Meta meta;+ switch (session_->popVideo(packet_, meta, waitMs, honourHold)) {+ case DemuxSession::Pop::Packet:+ packetDiscontinuity_ = meta.discontinuity;+ notePacket();+ return ReadResult::Packet;+ case DemuxSession::Pop::Empty: return ReadResult::Waiting;+ case DemuxSession::Pop::Eof: return ReadResult::Eof;+ case DemuxSession::Pop::Cancelled: return ReadResult::Cancelled;+ case DemuxSession::Pop::Failed: break;+ }+ return ReadResult::Error;+}+bool FFmpegDemuxer::seekToUs(int64_t targetUs){+ if (session_) {+ if (!session_->seek(targetUs)) {+ log::error("media", std::format("demuxer: session seek failed targetUs={}", targetUs));+ return false;+ }+ packetDiscontinuity_ = false;+ return true;+ }if (context_ == nullptr) {return false;}diff --git a/src/media/FFmpegVideoDecoder.cpp b/src/media/FFmpegVideoDecoder.cppindex c6a794c0..3cabd296 100644--- a/src/media/FFmpegVideoDecoder.cpp+++ b/src/media/FFmpegVideoDecoder.cpp@@ -662,9 +662,13 @@ bool FFmpegVideoDecoder::sendPacket(const AVPacket* packet)}if (result == AVERROR_EOF && packet == nullptr) return true;if (result < 0) {- char errorText[AV_ERROR_MAX_STRING_SIZE]{};- av_strerror(result, errorText, sizeof(errorText));- log::error("media", std::format("decoder: send_packet failed code={} text={}", result, errorText));+ lastError_ = result;+ // Damaged network data fails often; log the first few and then a sample.+ if (++errorLogs_ <= 5 || errorLogs_ % 100 == 0) {+ char errorText[AV_ERROR_MAX_STRING_SIZE]{};+ av_strerror(result, errorText, sizeof(errorText));+ log::error("media", std::format("decoder: send_packet failed code={} text={} (failures so far {})", result, errorText, errorLogs_));+ }return false;}if (packet != nullptr) {@@ -692,9 +696,12 @@ const AVFrame* FFmpegVideoDecoder::receiveFrame()else if (result == AVERROR_EOF) receiveStatus_ = DecodeReceiveStatus::EndOfStream;else {receiveStatus_ = DecodeReceiveStatus::Error;- char errorText[AV_ERROR_MAX_STRING_SIZE]{};- av_strerror(result, errorText, sizeof(errorText));- log::error("media", std::format("decoder: receive_frame failed code={} text={}", result, errorText));+ lastError_ = result;+ if (++errorLogs_ <= 5 || errorLogs_ % 100 == 0) {+ char errorText[AV_ERROR_MAX_STRING_SIZE]{};+ av_strerror(result, errorText, sizeof(errorText));+ log::error("media", std::format("decoder: receive_frame failed code={} text={} (failures so far {})", result, errorText, errorLogs_));+ }}return nullptr;}diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cppindex ec5740b2..000b2e2b 100644--- a/src/sink/WasapiAudioSink.cpp+++ b/src/sink/WasapiAudioSink.cpp@@ -44,11 +44,11 @@ bool AudioPipeline::open(const std::wstring& path,const std::atomic<bool>* cancefmt_->interrupt_callback={media::InputInterrupt::callback,&inputInterrupt_};AVDictionary* options=nullptr;if(media::networkMediaInput(path))media::networkMediaOptions(&options);- inputInterrupt_.arm();+ inputInterrupt_.armConnect();const int opened=avformat_open_input(&fmt_,narrow.c_str(),nullptr,&options);av_dict_free(&options);if(opened<0)return false;- inputInterrupt_.arm();+ inputInterrupt_.armProbe();const int found=avformat_find_stream_info(fmt_,nullptr);inputInterrupt_.disarm();if(found<0)return false;@@ -69,10 +69,40 @@ bool AudioPipeline::open(const std::wstring& path,const std::atomic<bool>* cancereturn selectTrack(si);}+bool AudioPipeline::open(std::shared_ptr<media::DemuxSession> session)+{+ if(!session||thread_.joinable())return false;+ session_=std::move(session);+ queueMode_=true;+ tracks_.clear();+ for(const auto& stream:session_->streams()){+ if(stream.type!=AVMEDIA_TYPE_AUDIO||!stream.parameters)continue;+ const auto* p=stream.parameters.get();+ tracks_.push_back({stream.index,stream.language,stream.title,avcodec_get_name(p->codec_id),unsigned(p->ch_layout.nb_channels)});+ }+ const int si=session_->audioStream();+ if(si<0){+ veyra::log::info("audio", "no audio stream in source");+ return false;+ }+ return selectTrack(si);+}+bool AudioPipeline::selectTrack(int si){- if(thread_.joinable()||!fmt_||si<0||unsigned(si)>=fmt_->nb_streams)return false;- const auto* parameters=fmt_->streams[si]->codecpar;+ if(thread_.joinable()||(!fmt_&&!session_)||si<0)return false;+ const AVCodecParameters* parameters=nullptr;+ AVRational timeBase{1,1000};+ if(session_){+ const auto* stream=session_->stream(si);+ if(!stream||!stream->parameters)return false;+ parameters=stream->parameters.get();+ timeBase={stream->timeBaseNum,std::max(stream->timeBaseDen,1)};+ }else{+ if(unsigned(si)>=fmt_->nb_streams)return false;+ parameters=fmt_->streams[si]->codecpar;+ timeBase=fmt_->streams[si]->time_base;+ }if(parameters->codec_type!=AVMEDIA_TYPE_AUDIO)return false;const auto* codec=avcodec_find_decoder(parameters->codec_id);if(!codec)return false;@@ -89,7 +119,13 @@ bool AudioPipeline::selectTrack(int si)log::error("audio-track",std::format("decoder rejected stream={} code={}",si,result));avcodec_free_context(&candidate);return false;}- avcodec_free_context(&codecCtx_);codecCtx_=candidate;streamIndex_=si;stream_=fmt_->streams[si];pcmFormat_=format;+ // The session queues packets of one audio stream; switching tells it which.+ if(session_&&!session_->selectAudioStream(si)){+ log::error("audio-track",std::format("session refused audio stream {}",si));+ avcodec_free_context(&candidate);return false;+ }+ avcodec_free_context(&codecCtx_);codecCtx_=candidate;streamIndex_=si;streamTimeBase_=timeBase;pcmFormat_=format;+ sessionDiscontinuity_=false;if(swr_)swr_free(&swr_);resetTempo();av_packet_unref(packet_);havePacket_=demuxEof_=drainSent_=false;decodedEof_=false;@@ -198,7 +234,7 @@ void AudioPipeline::readerLoop()AVPacket* queued=av_packet_alloc();if(!queued){av_packet_unref(scratch);readerEof_=true;continue;}av_packet_move_ref(queued,scratch);- queuedMs_+=queued->duration>0?queued->duration*av_q2d(stream_->time_base)*1000.0:0.0;+ queuedMs_+=queued->duration>0?queued->duration*av_q2d(streamTimeBase_)*1000.0:0.0;queuedBytes_+=size_t(std::max(queued->size,0));queuedPackets_.push_back(queued);}@@ -235,7 +271,7 @@ void AudioPipeline::resumeReader()void AudioPipeline::stopReader(){- queueMode_=false;+ if(!session_)queueMode_=false; // a session is always read through its queueif(!reader_.joinable())return;{std::lock_guard lock(readerMutex_);readerStop_=true;}readerCv_.notify_all();@@ -245,13 +281,26 @@ void AudioPipeline::stopReader()queuedPackets_.clear();queuedMs_=0;queuedBytes_=0;}-bool AudioPipeline::takeQueuedPacket(bool& eof)+bool AudioPipeline::takeQueuedPacket(bool& eof,int waitMs){- std::lock_guard lock(readerMutex_);eof=false;+ if(session_){+ // The demux thread of the session is the reader; this only moves a packet over.+ media::DemuxSession::Meta meta;+ switch(session_->popAudio(packet_,meta,waitMs)){+ case media::DemuxSession::Pop::Packet:+ if(meta.discontinuity)sessionDiscontinuity_=true;+ return true;+ case media::DemuxSession::Pop::Eof:+ case media::DemuxSession::Pop::Failed: // the video side reports a failed source+ eof=true;return false;+ default:return false;+ }+ }+ std::lock_guard lock(readerMutex_);if(queuedPackets_.empty()){eof=readerEof_;return false;}AVPacket* front=queuedPackets_.front();queuedPackets_.pop_front();- queuedMs_=std::max(0.0,queuedMs_-(front->duration>0?front->duration*av_q2d(stream_->time_base)*1000.0:0.0));+ queuedMs_=std::max(0.0,queuedMs_-(front->duration>0?front->duration*av_q2d(streamTimeBase_)*1000.0:0.0));queuedBytes_-=std::min(queuedBytes_,size_t(std::max(front->size,0)));av_packet_move_ref(packet_,front);av_packet_free(&front);readerCv_.notify_all();@@ -268,7 +317,9 @@ double AudioPipeline::requestSeek(double targetMs)wake_.notify_all();// The audio thread signals when the ring is prefilled past target.if (!seekDoneCv_.wait_for(lock, std::chrono::milliseconds(3000), [this] { return seekDone_; })) {- veyra::log::error("audio", "seek prefill timed out");+ // On a shared session the prefill waits for the network and finishes in the background.+ if (session_) veyra::log::info("audio", "seek prefill still waiting for network data; the audio thread finishes it in the background");+ else veyra::log::error("audio", "seek prefill timed out");}return seekDone_ ? firstPtsAfterSeek_.load() : std::numeric_limits<double>::quiet_NaN();}@@ -312,7 +363,7 @@ void AudioPipeline::pushDecoded(const AVFrame* frame)const auto timestamp = frame->best_effort_timestamp != AV_NOPTS_VALUE? frame->best_effort_timestamp : frame->pts;if (timestamp != AV_NOPTS_VALUE) {- const double ptsMs = timestamp * av_q2d(stream_->time_base) * 1000.0;+ const double ptsMs = timestamp * av_q2d(streamTimeBase_) * 1000.0;nextPtsMs_ = ptsMs - 1000.0 * swr_get_delay(swr_, frame->sample_rate) / frame->sample_rate;}const auto capacity = swr_get_out_samples(swr_, frame->nb_samples);@@ -460,8 +511,11 @@ void AudioPipeline::decodeBlock()if (!havePacket_) {if (queueMode_) {bool eof = false;- if (!takeQueuedPacket(eof)) {+ // Open / seek prefill waits for the session's packets (the endpoint is stopped, the+ // network may be slow); steady playback never waits - the endpoint has to be fed.+ if (!takeQueuedPacket(eof, prefillWait_ ? 50 : 0)) {if (eof) { demuxEof_ = true; continue; }+ if (prefillWait_ && !stopFlag_ && !seekRequested_ && std::chrono::steady_clock::now() < prefillDeadline_) continue;break; // nothing read ahead yet: go back to pumping the endpoint}} else if (!readPacket(packet_)) {@@ -474,6 +528,13 @@ void AudioPipeline::decodeBlock()havePacket_ = false;continue;}+ if (sessionDiscontinuity_) {+ // First packet of a new live connection: the old decoder state is meaningless.+ sessionDiscontinuity_ = false;+ avcodec_flush_buffers(codecCtx_);+ if (swr_) swr_free(&swr_);+ log::info("audio", "network source reconnected: audio decoder reset");+ }}const int sent = avcodec_send_packet(codecCtx_, packet_);if (sent == 0) {@@ -494,6 +555,49 @@ void AudioPipeline::closeAll()if (packet_ != nullptr) av_packet_free(&packet_);if (codecCtx_ != nullptr) avcodec_free_context(&codecCtx_);if (fmt_ != nullptr) avformat_close_input(&fmt_);+ session_.reset();+}++// Drops PCM before targetMs from the front of the ring (mutex_ held).+void AudioPipeline::trimRingBefore(double targetMs)+{+ while (!segments_.empty()) {+ Segment& seg = segments_.front();+ if (seg.startPtsMs >= targetMs || seg.stepMs <= 0) break;+ const size_t drop = std::min(seg.frames, static_cast<size_t>(std::ceil((targetMs - seg.startPtsMs) / seg.stepMs - 1e-7)));+ if (drop == 0) break;+ ring_.erase(ring_.begin(), ring_.begin() + static_cast<std::ptrdiff_t>(drop * pcmFormat_.channels));+ ringFrames_ -= drop;+ seg.frames -= drop;+ seg.startPtsMs += static_cast<double>(drop) * seg.stepMs;+ if (seg.frames == 0) segments_.pop_front();+ else break;+ }+}++// Shared session: the demuxer is not ours to move. After an engine seek the session was+// already repositioned (new generation), so everything decoded so far is stale; otherwise+// (alignment to the first picture, endpoint recovery) only the PCM before `target` is dropped.+bool AudioPipeline::rewindSession(double target)+{+ const uint32_t generation = session_->generation();+ std::lock_guard lock(mutex_);+ if (generation != sessionGeneration_) {+ sessionGeneration_ = generation;+ ring_.clear();ringFrames_=0;segments_.clear();+ if(havePacket_){av_packet_unref(packet_);havePacket_=false;}+ avcodec_flush_buffers(codecCtx_);+ if(swr_)swr_free(&swr_);+ resetTempo();+ sessionDiscontinuity_ = false;+ demuxEof_=drainSent_=false;decodedEof_=false;+ nextPtsMs_=target;discardUntilPtsMs_=target;+ } else {+ trimRingBefore(target);+ discardUntilPtsMs_ = target;+ // The ring may now end before the target: decoding continues and discards up to it.+ }+ return true;}bool AudioRenderer::copyPcm(BYTE* destination,const float* input,size_t frames){@@ -935,7 +1039,10 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint,// instead (engine-side, plan P1). Only explicit transport holds — open,// seek, settings rebuild, pause — gate the endpoint here.auto videoBlocked=[&]{return videoSync_&&videoHold_.load();};- auto shouldPause=[&]{return paused_.load()||videoBlocked();};+ // A network source that ran dry (or is still collecting its start-up buffer) stops the+ // device clock exactly like a pause, so picture and sound wait together.+ auto networkHold=[&]{return session_&&session_->holding();};+ auto shouldPause=[&]{return paused_.load()||videoBlocked()||networkHold();};auto publishVideoWait=[&](bool paused){const bool waiting=paused&&videoBlocked();if(videoWaiting_.exchange(waiting)!=waiting&&waiting)++videoWaitCount_;};auto nextContinuitySummary=t0+std::chrono::milliseconds(1000);auto recovering = [&](HRESULT error) {@@ -953,6 +1060,17 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint,// resumes from the new position afterwards.pauseReader();struct ResumeReader{AudioPipeline* self;~ResumeReader(){self->resumeReader();}} resumeReader{this};+ if(session_){+ // Shared session: no file to seek. The prefill may have to wait for the network.+ prefillWait_=true;prefillDeadline_=std::chrono::steady_clock::now()+std::chrono::seconds(20);+ rewindSession(target);+ decodeBlock();+ prefillWait_=false;+ discardUntilPtsMs_=-1;+ clockExhausted_=decodedEof_&&headPtsMs()<0;+ log::info("audio-seek",std::format("targetMs={:.3f} firstPtsMs={:.3f} totalMs={:.3f} (shared session)",target,headPtsMs(),std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-seekBegin).count()));+ return true;+ }{std::lock_guard lock(mutex_);ring_.clear();ringFrames_=0;segments_.clear();@@ -981,9 +1099,11 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint,};if(renderer&&ownEndpoint&&!endpointReady)recovering(renderer->lastError());resetTempo();- // Initial prefill (open case).+ // Initial prefill (open case). A shared session may still be collecting its start-up buffer.+ if(session_){sessionGeneration_=session_->generation();prefillWait_=true;prefillDeadline_=std::chrono::steady_clock::now()+std::chrono::seconds(60);}if(initialMs>=0){if(!rewind(initialMs))recovering(E_FAIL);}else decodeBlock();+ prefillWait_=false;{std::unique_lock<std::mutex> lock(mutex_);if (segments_.empty()) {@@ -999,6 +1119,8 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint,// not mean "no audio"; headPtsMs() also uses -1 as its empty sentinel.// Use the actual prefetched sample count to distinguish those cases and// anchor the renderer whenever a finite audio timeline is available.+ // A shared session can still be empty here (slow network): anchor as soon as PCM arrives.+ bool needAnchor = session_ && endpointReady && !clockExhausted_ && !(prefetchedMs > 0.0 && std::isfinite(firstPts));if (endpointReady && prefetchedMs > 0.0 && std::isfinite(firstPts)) {if (!renderer->startAnchored(*this,pauseApplied)) recovering(renderer->lastError());else endpointRecovering_=false;@@ -1054,6 +1176,7 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint,const double target = seekTargetMs_;seekCount_.fetch_add(1);lock.unlock();+ needAnchor = false; // the seek anchors the endpoint itselfif (endpointReady) renderer->fadeAndReset(*this,stopFlag_);lastClockMs=recoveryTargetMs=target;const bool seekOk=rewind(target);@@ -1097,6 +1220,21 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint,wake_.wait_for(lock,std::chrono::milliseconds(5),[&]{return stopFlag_||seekRequested_;});continue;}+ if (needAnchor && endpointReady) {+ // Shared session whose first PCM had not arrived at start-up: nothing may reach the+ // endpoint before it is anchored to the first sample's PTS.+ if (bufferedMs() >= kAudioLowWatermarkMs && headPtsMs() >= 0.0) {+ needAnchor = false;+ pauseApplied = shouldPause();+ if (!renderer->startAnchored(*this,pauseApplied)) recovering(renderer->lastError());+ else endpointRecovering_=false;+ continue;+ }+ if (bufferedMs() < kAudioHighWatermarkMs) decodeBlock();+ if (demuxEof_ && bufferedMs() < 1.0) needAnchor = false;+ std::unique_lock lock(mutex_);wake_.wait_for(lock,std::chrono::milliseconds(5));+ continue;+ }if (pauseNow) { std::unique_lock lock(mutex_);wake_.wait_for(lock,std::chrono::milliseconds(2));continue; }// Regular cycle: pump the endpoint, then top up below high watermark.if (renderer != nullptr) {@@ -1144,6 +1282,7 @@ void AudioPipeline::startThread(AudioRenderer* renderer, bool ownEndpoint, doublif(readStallMs_>0)log::warn("audio-test",std::format("injected file read stall {:.0f} ms every {:.0f} ms (test only) directRead={}",readStallMs_,readStallEveryMs_,directReadForTest_));stopFlag_=false;seekRequested_=false;seekDone_=true;discardUntilPtsMs_=-1;endpointRecovering_=renderer&&ownEndpoint;endpointError_=S_OK;endpointRecoveries_=0;clockExhausted_=false;+ queueMode_=session_!=nullptr; // a shared session is always read through its queuethread_ = std::thread(&AudioPipeline::runOnAudioThread, this, renderer, ownEndpoint, initialMs);}diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cppindex e501eb84..044826c8 100644--- a/src/source/MediaFileSource.cpp+++ b/src/source/MediaFileSource.cpp@@ -67,10 +67,12 @@ bool MediaFileSource::fallbackToSoftware(std::string_view reason)"D3D12VA {} fallback to software reason={} path=redacted resumeUs={}", midStream ? "mid-stream" : "first-frame", reason, resumeUs));deinterlacer_.close();filterDraining_=false;decoder_.close();- demuxer_.close();- if (!demuxer_.open(path_,cancelled_)) {- veyra::log::error("source-file", "software fallback could not reopen demuxer");- return false;+ if (!demuxer_.shared()) {+ demuxer_.close();+ if (!demuxer_.open(path_,cancelled_)) {+ veyra::log::error("source-file", "software fallback could not reopen demuxer");+ return false;+ }}const auto* params = demuxer_.videoCodecParameters();if (params == nullptr || !decoder_.openSoftware(params, demuxer_.videoTimeBaseNum(),@@ -80,7 +82,9 @@ bool MediaFileSource::fallbackToSoftware(std::string_view reason)}info_.hardwareDecodeActive = false;if (midStream && resumeUs != INT64_MIN) {- if (!demuxer_.seekToUs(std::max<int64_t>(0, resumeUs))) veyra::log::warn("source-file", "software fallback could not seek back; continuing from stream start");+ // A live session cannot go back: the software decoder continues at the current position.+ if (demuxer_.shared() && !demuxer_.seekable()) veyra::log::warn("source-file", "software fallback on a live source continues at the current position");+ else if (!demuxer_.seekToUs(std::max<int64_t>(0, resumeUs))) veyra::log::warn("source-file", "software fallback could not seek back; continuing from stream start");decoder_.flushBuffers();// The engine treats Seek as a hard history reset; frames before the// resume point are dropped by the caller's discardBefore logic.@@ -166,10 +170,30 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)deinterlaceEnabled_=desc.deinterlace;filterDraining_=false;preferHardwareDecode_ = desc.preferHardwareDecode && desc.d3d12Device != nullptr && desc.d3d12Queue != nullptr;requireHardwareDecode_ = desc.requireHardwareDecode;- if (!demuxer_.open(desc.path,cancelled_)) {+ nonBlocking_ = desc.nonBlocking;+ corruptPolicy_ = desc.network.corrupt;+ resetCorruptionState();+ if (media::sharedDemuxInput(desc.path, desc.nonBlocking)) {+ // Network addresses and files on a server: one connection, read ahead of playback,+ // shared with the audio pipeline (docs/NETWORK_BUFFER_48_PLAN_2026-10-17.md).+ media::DemuxSession::OpenParams session;+ session.path = desc.path;+ session.settings = desc.network;+ session.cancelled = desc.cancelled;+ std::wstring failure;+ auto opened = media::DemuxSession::open(session, &failure);+ if (!opened || !demuxer_.openShared(std::move(opened))) {+ errorMessage_ = failure.empty() ? L"无法打开视频,请查看诊断" : failure;+ veyra::log::error("source-file", "shared demux session open failed");+ return false;+ }+ } else if (!demuxer_.open(desc.path,cancelled_)) {veyra::log::error("source-file", "demuxer open failed");return false;}+ // Damaged data is tolerated on the player's network sources and MPEG-TS; export+ // and every offline user keep the strict stop.+ tolerant_ = desc.tolerateCorruption && (media::networkMediaInput(desc.path) || demuxer_.formatName().find("mpegts") != std::string::npos);const AVCodecParameters* params = demuxer_.videoCodecParameters();if (params == nullptr) {veyra::log::error("source-file", "no video codec parameters");@@ -296,6 +320,13 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrameout = pipeline::FramePacket{};if (!info_.opened || !errorMessage_.empty()) { return SourceReadStatus::Error; }+ {+ // A long gap between read() calls (pause, stall) must not count as "no output".+ const auto now = std::chrono::steady_clock::now();+ if (now - lastReadCall_ > std::chrono::seconds(2)) noOutputSince_ = {};+ lastReadCall_ = now;+ }+readAgain: // a damaged picture was dropped (corrupt policy WaitKeyframe): fetch the next oneconst AVFrame* frame = nullptr;for (;;) {if(deinterlacer_.active()){@@ -335,6 +366,10 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFramereturn SourceReadStatus::Eos;}if (decoder_.receiveStatus() == media::DecodeReceiveStatus::Error) {+ // Network data that the decoder rejects is skipped up to the next keyframe.+ if (tolerant_ && tolerateDecoderError()) {+ continue;+ }if (fallbackToSoftware("decoder-error")) {continue;}@@ -345,9 +380,24 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrameerrorMessage_ = L"视频解码失败,已停止处理,请检查源文件是否损坏";return SourceReadStatus::Error;}- bool eof = false;- if (!demuxer_.readVideoPacket(eof)) {- if (!eof) { errorMessage_ = L"源视频读取失败,已停止处理"; return SourceReadStatus::Error; }+ const auto got = demuxer_.readVideoPacketEx(nonBlocking_ ? 20 : 50, nonBlocking_);+ if (got == media::FFmpegDemuxer::ReadResult::Waiting) {+ // Playback is paused for buffering (or the next packet has not arrived):+ // nothing is lost, the caller retries and the picture stays on screen.+ if (nonBlocking_) {+ return SourceReadStatus::Waiting;+ }+ continue;+ }+ if (got == media::FFmpegDemuxer::ReadResult::Cancelled) {+ return SourceReadStatus::Error; // the owner is stopping; no message+ }+ if (got == media::FFmpegDemuxer::ReadResult::Error) {+ const auto failure = demuxer_.shared() ? demuxer_.session()->failureMessage() : std::wstring{};+ errorMessage_ = failure.empty() ? L"源视频读取失败,已停止处理" : failure;+ return SourceReadStatus::Error;+ }+ if (got == media::FFmpegDemuxer::ReadResult::Eof) {draining_ = true;if (!decoder_.sendPacket(nullptr)) {errorMessage_ = L"视频尾帧解码失败,已停止处理";@@ -355,12 +405,52 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame}continue;}- if (demuxer_.currentPacket()->flags & AV_PKT_FLAG_CORRUPT) {- veyra::log::error("source-file", "corrupt video packet; refusing to skip source data");- errorMessage_ = L"源视频包含损坏数据,已停止处理";- return SourceReadStatus::Error;+ if (demuxer_.packetDiscontinuity()) {+ beginDiscontinuity();+ }+ // Packets keep arriving but nothing decodable comes out for 10 s: the connection+ // is delivering garbage. Start over on a fresh one (at most once per 30 s).+ if (tolerant_ && demuxer_.shared()) {+ const auto now = std::chrono::steady_clock::now();+ if (noOutputSince_ == std::chrono::steady_clock::time_point{}) noOutputSince_ = now;+ else if (now - noOutputSince_ >= std::chrono::seconds(10) && now - lastForcedReconnect_ >= std::chrono::seconds(30)) {+ lastForcedReconnect_ = now;+ noOutputSince_ = {};+ veyra::log::warn("source-file", "no decodable picture for 10 s while data keeps arriving; reconnecting");+ demuxer_.session()->requestReconnect("no decodable picture for 10 s");+ }+ }+ const AVPacket* packet = demuxer_.currentPacket();+ if (packet->flags & AV_PKT_FLAG_CORRUPT) {+ if (!tolerant_) {+ veyra::log::error("source-file", "corrupt video packet; refusing to skip source data");+ errorMessage_ = L"源视频包含损坏数据,已停止处理";+ return SourceReadStatus::Error;+ }+ ++corruptPacketsSeen_;+ const auto now = std::chrono::steady_clock::now();+ if (now - lastCorruptLog_ >= std::chrono::seconds(1)) {+ lastCorruptLog_ = now;+ veyra::log::warn("source-file", std::format("damaged video packet from the network (policy={} packetsSoFar={}); decoding continues",+ corruptPolicy_ == media::CorruptPolicy::WaitKeyframe ? "wait-keyframe" : "conceal", corruptPacketsSeen_));+ }+ if (corruptPolicy_ == media::CorruptPolicy::WaitKeyframe) {+ decoder_.recoverAtKeyframe();+ waitKeyframe_ = true;+ if (const auto& session = demuxer_.session()) session->addCorruptFrames(0, 0);+ }+ }+ if (waitKeyframe_) {+ // A clean start after a damaged stretch is a keyframe that is not itself damaged.+ if (!(packet->flags & AV_PKT_FLAG_KEY) || (packet->flags & AV_PKT_FLAG_CORRUPT)) {+ continue;+ }+ waitKeyframe_ = false;}- if (!decoder_.sendPacket(demuxer_.currentPacket())) {+ if (!decoder_.sendPacket(packet)) {+ if (tolerant_ && tolerateDecoderError()) {+ continue;+ }if (fallbackToSoftware("send-packet-error")) {continue;}@@ -390,9 +480,27 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame}if ((frame->flags & AV_FRAME_FLAG_CORRUPT) || frame->decode_error_flags) {- veyra::log::error("source-file", std::format("corrupt decoded frame flags={} decodeErrors={}", frame->flags, frame->decode_error_flags));- errorMessage_ = L"源视频包含损坏画面,已停止处理";- return SourceReadStatus::Error;+ if (!tolerant_) {+ veyra::log::error("source-file", std::format("corrupt decoded frame flags={} decodeErrors={}", frame->flags, frame->decode_error_flags));+ errorMessage_ = L"源视频包含损坏画面,已停止处理";+ return SourceReadStatus::Error;+ }+ // Network loss: FFmpeg has concealed what it could. Show that picture, or drop it+ // and wait for the next keyframe, as the user chose.+ ++corruptFramesSeen_;+ const bool drop = corruptPolicy_ == media::CorruptPolicy::WaitKeyframe;+ if (const auto& session = demuxer_.session()) session->addCorruptFrames(1, drop ? 1 : 0);+ const auto now = std::chrono::steady_clock::now();+ if (now - lastCorruptLog_ >= std::chrono::seconds(1)) {+ lastCorruptLog_ = now;+ veyra::log::warn("source-file", std::format("damaged picture flags={} decodeErrors={} policy={} picturesSoFar={}",+ frame->flags, frame->decode_error_flags, drop ? "wait-keyframe" : "conceal", corruptFramesSeen_));+ }+ if (drop) {+ decoder_.recoverAtKeyframe();+ waitKeyframe_ = true;+ goto readAgain;+ }}if (frame->width <= 0 || frame->height <= 0 || uint32_t(frame->width) != info_.width || uint32_t(frame->height) != info_.height) {veyra::log::error("source-file", std::format("frame extent changed: opened={}x{} decoded={}x{}; file processing stopped before upload", info_.width, info_.height, frame->width, frame->height));@@ -484,6 +592,12 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrameflags |= static_cast<uint32_t>(pipeline::FrameFlagBits::Seek);pendingSeekFlag_ = false;}+ if (pendingDiscontinuity_) {+ // First picture after a live reconnect: temporal history from the old connection+ // does not apply to it.+ flags |= static_cast<uint32_t>(pipeline::FrameFlagBits::Discontinuity);+ pendingDiscontinuity_ = false;+ }const int64_t ptsUs = rationalToUs(out.pts);if (lastPtsUs_ != INT64_MIN && !out.pts.isUnknown() && ptsUs < lastPtsUs_) {flags |= static_cast<uint32_t>(pipeline::FrameFlagBits::Discontinuity);@@ -510,14 +624,77 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame}++framesRead_;+ noOutputSince_ = {};if (decodedFrame != nullptr) { *decodedFrame = frame; }return SourceReadStatus::Frame;}+media::NetworkStats MediaFileSource::networkStats() const+{+ if (const auto& session = demuxer_.session()) return session->stats();+ return {};+}++void MediaFileSource::setPlaybackPositionMs(double ms)+{+ if (const auto& session = demuxer_.session()) {+ if (std::isfinite(ms) && ms >= 0) session->setPlaybackPositionUs(int64_t(ms * 1000.0));+ }+}++void MediaFileSource::resetCorruptionState()+{+ waitKeyframe_ = false;+ pendingDiscontinuity_ = false;+ corruptPacketsSeen_ = corruptFramesSeen_ = decoderErrorsSeen_ = 0;+ errorsInWindow_ = 0;+ errorWindowStart_ = lastCorruptLog_ = lastReadCall_ = noOutputSince_ = {};+ lastForcedReconnect_ = std::chrono::steady_clock::now();+}++// The first packet after a live reconnect: the old connection's decoder state and+// temporal history do not apply. The session has already cut to a keyframe and kept+// the timeline continuous.+void MediaFileSource::beginDiscontinuity()+{+ veyra::log::info("source-file", "network source reconnected: resetting the decoder at the new keyframe");+ deinterlacer_.close();+ filterDraining_ = false;+ decoder_.recoverAtKeyframe();+ waitKeyframe_ = false;+ pendingDiscontinuity_ = true;+ lastPtsUs_ = INT64_MIN;+ ++epoch_;+}++// A damaged packet the decoder rejects is a few lost frames, not a dead source: skip+// to the next keyframe. A burst of failures (a broken decoder or hardware path) is+// not tolerated, so the usual software fallback / error applies.+bool MediaFileSource::tolerateDecoderError()+{+ const auto now = std::chrono::steady_clock::now();+ if (errorsInWindow_ == 0 || now - errorWindowStart_ > std::chrono::seconds(2)) {+ errorWindowStart_ = now;+ errorsInWindow_ = 0;+ }+ ++decoderErrorsSeen_;+ if (++errorsInWindow_ > 12) {+ veyra::log::warn("source-file", std::format("decoder rejected {} packets within 2 s; treating it as a decoder failure", errorsInWindow_));+ return false;+ }+ if (decoder_.lastError() != AVERROR_INVALIDDATA && decoderErrorsSeen_ > 3 && decoder_.hardwareActive()) {+ return false; // not damaged data: let the hardware fallback decide+ }+ if (const auto& session = demuxer_.session()) session->addCorruptFrames(0, 0);+ decoder_.recoverAtKeyframe();+ waitKeyframe_ = true;+ return true;+}+bool MediaFileSource::seek(const pipeline::Rational& targetSeconds){if (!info_.opened) { return false; }- if(media::networkMediaInput(path_)&&!demuxer_.seekable())return false;+ if((media::networkMediaInput(path_)||demuxer_.shared())&&!demuxer_.seekable())return false;if (targetSeconds.isUnknown() || targetSeconds.den == 0 || targetSeconds.isNegative()) {veyra::log::error("source-file", "seek target must be a known non-negative rational");return false;@@ -530,6 +707,9 @@ bool MediaFileSource::seek(const pipeline::Rational& targetSeconds)draining_ = false;eofSignalled_ = false;pendingSeekFlag_ = true;+ pendingDiscontinuity_ = false;+ waitKeyframe_ = false;+ noOutputSince_ = {};lastPtsUs_ = INT64_MIN;++epoch_;++seekCount_;