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++
Engine integration of the demux session, test server and network buffer tests
Veyra Goal Agentc4da72d53fbe
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 4f2d85b7..1aeffae5 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -674,6 +674,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_features(veyra_network_interlace_tests PRIVATE cxx_std_20)target_compile_definitions(veyra_network_interlace_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)target_link_libraries(veyra_network_interlace_tests PRIVATE veyra_engine)+ # #48: shared demux session, reconnect, buffering, damaged-data tolerance (tests/network).+ add_executable(veyra_network_buffer_tests tests/integration/NetworkBufferTests.cpp)+ target_compile_features(veyra_network_buffer_tests PRIVATE cxx_std_20)+ target_compile_definitions(veyra_network_buffer_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)+ target_link_libraries(veyra_network_buffer_tests PRIVATE veyra_engine)add_executable(veyra_decklink_tests tests/unit/DeckLinkCaptureTests.cpp)target_compile_features(veyra_decklink_tests PRIVATE cxx_std_20)target_compile_definitions(veyra_decklink_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)diff --git a/include/veyra/media/DemuxSession.h b/include/veyra/media/DemuxSession.hindex b8a029f2..db70d0ce 100644--- a/include/veyra/media/DemuxSession.h+++ b/include/veyra/media/DemuxSession.h@@ -179,7 +179,9 @@ private:Phase phase_ = Phase::Prebuffering;double targetSeconds_ = 0;bool afterSeek_ = false;- int64_t playbackUs_ = -1;+ int64_t playbackUs_ = -1; // hint from the player (media timeline)+ bool hasHint_ = false; // the player supplies playbackUs_; otherwise consumption is the position+ int64_t consumedUs_ = -1; // start of the last video packet a consumer tookbool eof_ = false, failed_ = false, reconnecting_ = false;uint32_t reconnectAttempt_ = 0, reconnects_ = 0, stalls_ = 0, connections_ = 0;std::wstring failure_;diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex a084d458..5e427104 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -1375,6 +1375,25 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,snetworkShownStatus.clear();}};+ // Runs every loop turn and inside the presentation back-pressure wait: while playback is held+ // for buffering the frozen clock keeps queued pictures from presenting, and that wait must+ // neither look like a hang to the watchdog nor stop the statistics.+ auto networkTick=[&]{+ if(!demuxSession)return;+ const bool holding=demuxSession->holding();+ if(holding)watchdog_->beat();+ // 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(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();}+ };uint64_t hdrDisplayCheck=0;bool captureRecovering=false;unsigned captureRetries=0;Clock::time_point captureRetryAt{};@@ -1437,19 +1456,7 @@ 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();}- }+ networkTick();if(captureRecovering){if(Clock::now()<captureRetryAt){std::this_thread::sleep_for(std::chrono::milliseconds(20));continue;}++captureRetries;@@ -1782,6 +1789,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s};const auto leaseWaitStart=Clock::now();while((liveScheduler->occupancy()>=2||!graph->nextFrameSlotAvailable()||enhancementPending())&&!stop_&&(!paused_||seekPreviewPending)&&!liveScheduler->failed()){+ networkTick();advanceLive();if(seekSeconds_>=0)break;if(liveScheduler->occupancy()==0&&!graph->nextFrameSlotAvailable()&&elapsedMs(leaseWaitStart)>2000){status(L"等待输出纹理释放超时",true);stop_=true;break;}if(liveScheduler->occupancy()>=2||!graph->nextFrameSlotAvailable()||enhancementPending()){diff --git a/src/media/DemuxSession.cpp b/src/media/DemuxSession.cppindex a9017e87..2ac7d5df 100644--- a/src/media/DemuxSession.cpp+++ b/src/media/DemuxSession.cpp@@ -380,7 +380,9 @@ uint64_t DemuxSession::aheadBytesLocked() const {}double DemuxSession::leadSecondsLocked() const {- const int64_t position = playbackUs_;+ // The player reports where playback is; offline readers (export, tools, tests) do not, and for+ // them the video packet last taken is the position.+ const int64_t position = hasHint_ ? playbackUs_ : consumedUs_;double best = std::numeric_limits<double>::infinity();auto consider = [&](const Queue& q) {if (q.lastEndUs == INT64_MIN || q.firstUs == INT64_MIN) {@@ -433,6 +435,9 @@ double DemuxSession::resumeTargetLocked() const {target = std::max(target, 60.0 * (1.0 - ratio));}}+ // A slow server needs as long to fill a big window as to play it: cap the wait per level.+ const double cap = settings_.level == NetworkBufferLevel::Large ? 45.0 : 20.0;+ target = std::min(target, std::max(cap, plan_.startSeconds));return std::min(target, std::max(1.0, aheadSecondsLocked() - 0.5));}@@ -521,6 +526,7 @@ DemuxSession::Pop DemuxSession::popVideo(AVPacket* dst, Meta& meta, int waitMs,Item item = std::move(video_.items.front());video_.items.pop_front();video_.bytes -= item.bytes;+ consumedUs_ = item.startUs;av_packet_move_ref(dst, item.packet);av_packet_free(&item.packet);meta.discontinuity = item.discontinuity;@@ -572,6 +578,7 @@ void DemuxSession::setPlaybackPositionUs(int64_t us) {if (us < 0) return;std::lock_guard lock(m_);playbackUs_ = us;+ hasHint_ = true;updatePhaseLocked();producerCv_.notify_one();}@@ -790,6 +797,17 @@ void DemuxSession::threadMain() {const bool timedOut = irq_->timedOut();irq_->disarm();const double seconds = std::chrono::duration<double>(Clock::now() - begin).count();+ if (result >= 0 && (packet->flags & AV_PKT_FLAG_CORRUPT) && context_->pb && context_->pb->error < 0) {+ // The connection broke in the middle of a packet: FFmpeg hands the partial data over flagged+ // "corrupt" and reports the error only on the next read. That is a lost connection, not+ // damaged media - the packet is dropped and the link re-established.+ const int code = context_->pb->error;+ av_packet_unref(packet);+ log::warn("net-session", std::format("packet cut short by a transport error code={} text={}", code, errorText(code)));+ if (stop_.load()) break;+ recover(code, "truncated packet");+ continue;+ }if (result >= 0) {{std::lock_guard lock(m_);@@ -1003,6 +1021,7 @@ void DemuxSession::doSeek() {generation_.fetch_add(1);eof_ = false;playbackUs_ = target;+ consumedUs_ = target;rateSamples_.clear();contentBytes_ = 0;afterSeek_ = true;@@ -1122,7 +1141,8 @@ bool DemuxSession::recover(int code, const char* why) {}closeContext();gateKeyframe_ = false;- delayMs = std::min(delayMs * 2, 8000);+ // 1, 2, 4 s, then every 4 s: an outage of about eight seconds is over within 5 s of its end.+ delayMs = std::min(delayMs * 2, 4000);}if (stop_.load() || (cancelled_ && cancelled_->load())) return false;fail(std::format(L"网络连接中断,已重试 {} 秒仍无法恢复", reconnectBudgetMs_ / 1000));diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cppindex 044826c8..12427af9 100644--- a/src/source/MediaFileSource.cpp+++ b/src/source/MediaFileSource.cpp@@ -180,6 +180,7 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)session.path = desc.path;session.settings = desc.network;session.cancelled = desc.cancelled;+ session.audioStream = desc.nonBlocking ? -2 : -1; // offline readers (export, tools) take no audiostd::wstring failure;auto opened = media::DemuxSession::open(session, &failure);if (!opened || !demuxer_.openShared(std::move(opened))) {diff --git a/tests/integration/NetworkBufferTests.cpp b/tests/integration/NetworkBufferTests.cppnew file mode 100644index 00000000..3a0fac09--- /dev/null+++ b/tests/integration/NetworkBufferTests.cpp@@ -0,0 +1,350 @@+// #48 network playback / server buffering checks.+//+// veyra_network_buffer_tests selftest+// veyra_network_buffer_tests source <path-or-url> <outdir> [key=value ...]+// veyra_network_buffer_tests engine <path-or-url> <outdir> [key=value ...]+//+// `source` drives MediaFileSource directly (blocking reads unless nonblocking=1) and writes a per-frame+// CSV (pts, luma hash) for A/B comparisons; `engine` plays through EngineController on a hidden window+// and samples the snapshot, including the network statistics, every 50 ms. Both finish with one+// "RESULT {json}" line the orchestrator (tests/network/run_network_tests.py) parses.+#include "veyra/source/MediaFileSource.h"+#include "veyra/engine/EngineController.h"+#include "veyra/media/NetworkInput.h"+#include "veyra/media/NetworkSettings.h"+#include "veyra/Log.h"++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstdint>+#include <cstdio>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <map>+#include <sstream>+#include <string>+#include <thread>+#include <vector>++extern "C" {+#include <libavutil/frame.h>+#include <libavutil/pixfmt.h>+}++using namespace veyra;+using Clock = std::chrono::steady_clock;++namespace {++std::string narrow(const std::wstring& text) {+ if (text.empty()) return {};+ const int n = WideCharToMultiByte(CP_UTF8, 0, text.data(), int(text.size()), nullptr, 0, nullptr, nullptr);+ std::string out(size_t(n), '\0');+ WideCharToMultiByte(CP_UTF8, 0, text.data(), int(text.size()), out.data(), n, nullptr, nullptr);+ return out;+}+std::string jsonEscape(const std::string& s) {+ std::string out;+ for (const unsigned char c : s) {+ if (c == '"' || c == '\\') { out += '\\'; out += char(c); }+ else if (c < 0x20) { char b[8]; std::snprintf(b, sizeof b, "\\u%04x", c); out += b; }+ else out += char(c);+ }+ return out;+}++using Options = std::map<std::string, std::string>;+Options parseOptions(int argc, wchar_t** argv, int first) {+ Options o;+ for (int i = first; i < argc; ++i) {+ const std::string a = narrow(argv[i]);+ const auto eq = a.find('=');+ o[eq == std::string::npos ? a : a.substr(0, eq)] = eq == std::string::npos ? "1" : a.substr(eq + 1);+ }+ return o;+}+double num(const Options& o, const char* key, double fallback) {+ const auto it = o.find(key);+ return it == o.end() ? fallback : std::atof(it->second.c_str());+}+std::string str(const Options& o, const char* key, const char* fallback = "") {+ const auto it = o.find(key);+ return it == o.end() ? fallback : it->second;+}++media::NetworkSettings networkSettings(const Options& o) {+ media::NetworkSettings s;+ s.level = media::networkBufferLevelFromId(str(o, "level", "auto"));+ s.startupPrebufferSeconds = int(num(o, "prebuffer", -1));+ s.autoReconnect = num(o, "reconnect", 1) != 0;+ s.corrupt = media::corruptPolicyFromId(str(o, "policy", "conceal"));+ return s;+}++const char* stateName(media::NetworkStats::State s) {+ switch (s) {+ case media::NetworkStats::State::Prebuffering: return "prebuffering";+ case media::NetworkStats::State::Playing: return "playing";+ case media::NetworkStats::State::Buffering: return "buffering";+ case media::NetworkStats::State::Reconnecting: return "reconnecting";+ case media::NetworkStats::State::Failed: return "failed";+ case media::NetworkStats::State::Ended: return "ended";+ default: return "idle";+ }+}++// ---------------------------------------------------------------------------------------------+int selfTest() {+ int failures = 0;+ auto check = [&](bool ok, const char* name) { failures += !ok; std::cout << (ok ? "PASS " : "FAIL ") << name << std::endl; };+ check(media::networkMediaInput(L"http://example.com/a.mp4") && media::networkMediaInput(L"RTSP://cam/x") && media::networkMediaInput(L"https://x/y.m3u8"), "network schemes recognised");+ check(!media::networkMediaInput(L"C:\\video\\a.mkv") && !media::networkMediaInput(L"\\\\nas\\share\\a.mkv") && !media::networkMediaInput(L"file:///c:/a.mp4"), "paths are not network addresses");+ check(media::remoteMediaPath(L"\\\\nas\\share\\movies\\a.mkv") && media::remoteMediaPath(L"\\\\?\\UNC\\nas\\share\\a.mkv"), "UNC paths are server files");+ check(!media::remoteMediaPath(L"\\\\?\\C:\\video\\a.mkv") && !media::remoteMediaPath(L"\\\\.\\C:\\a.mkv") && !media::remoteMediaPath(L"relative\\a.mkv") && !media::remoteMediaPath(L"C:\\Windows\\a.mkv"), "local paths are not server files");+ media::NetworkSettings s;+ const auto vodAuto = media::networkBufferPlan(s, false);+ check(vodAuto.aheadSeconds == 30 && vodAuto.aheadBytes == (256ull << 20) && vodAuto.startSeconds == 3 && vodAuto.holds, "auto VOD plan: 30 s / 256 MB, 3 s start");+ s.level = media::NetworkBufferLevel::Large;+ const auto vodLarge = media::networkBufferPlan(s, false);+ check(vodLarge.aheadSeconds == 120 && vodLarge.aheadBytes == (1024ull << 20), "large VOD plan: 120 s / 1024 MB");+ s.level = media::NetworkBufferLevel::Small;+ const auto vodSmall = media::networkBufferPlan(s, false);+ check(vodSmall.aheadSeconds == 8 && vodSmall.aheadBytes == (64ull << 20), "small VOD plan: 8 s / 64 MB");+ s.level = media::NetworkBufferLevel::Off;+ const auto off = media::networkBufferPlan(s, false);+ check(!off.holds && off.startSeconds == 0 && off.lowWaterSeconds == 0, "off: never pauses for buffering");+ s = {};+ s.startupPrebufferSeconds = 20;+ const auto custom = media::networkBufferPlan(s, false);+ check(custom.startSeconds == 20 && custom.aheadSeconds >= 32, "custom pre-buffer enlarges the window");+ s = {};+ const auto live = media::networkBufferPlan(s, true);+ check(live.aheadSeconds <= 6 && live.startSeconds <= 3, "live buffers are jitter-sized");+ check(media::networkBufferLevelFromId("medium") == media::NetworkBufferLevel::Medium && media::networkBufferLevelFromId("nonsense") == media::NetworkBufferLevel::Auto, "level ids");+ return failures ? 1 : 0;+}++// ---------------------------------------------------------------------------------------------+uint64_t lumaHash(const AVFrame* frame) {+ uint64_t h = 1469598103934665603ull;+ if (!frame || !frame->data[0] || frame->format != AV_PIX_FMT_YUV420P) return h;+ for (int y = 0; y < frame->height; ++y) {+ const uint8_t* row = frame->data[0] + ptrdiff_t(y) * frame->linesize[0];+ for (int x = 0; x < frame->width; ++x) { h ^= row[x]; h *= 1099511628211ull; }+ }+ return h;+}++int sourceTest(const std::wstring& path, const std::filesystem::path& out, const Options& o) {+ std::filesystem::create_directories(out);+ Logger::instance().openFile((out / L"source.log").wstring());+ Logger::instance().setConsoleEnabled(false);+ std::atomic<bool> cancel = false;+ source::SourceOpenDesc desc;+ desc.path = path;+ desc.cancelled = &cancel;+ desc.preferHardwareDecode = num(o, "hw", 0) != 0;+ desc.deinterlace = false;+ desc.network = networkSettings(o);+ desc.nonBlocking = num(o, "nonblocking", 0) != 0;+ desc.tolerateCorruption = num(o, "tolerant", 0) != 0;+ const double maxFrames = num(o, "frames", 1e12), maxSeconds = num(o, "seconds", 1e9);+ const bool hash = num(o, "hash", 0) != 0;+ const bool pace = num(o, "pace", 0) != 0; // consume at the content rate, like playback does+ // seek=<targetSeconds>@<afterFrames>+ double seekTarget = -1;+ uint64_t seekAfter = 0;+ if (const auto s = str(o, "seek"); !s.empty()) {+ seekTarget = std::atof(s.c_str());+ seekAfter = uint64_t(std::atof(s.c_str() + s.find('@') + 1));+ }+ const auto openStart = Clock::now();+ source::MediaFileSource input;+ if (!input.open(desc)) {+ std::cout << "RESULT {\"opened\":false,\"error\":\"" << jsonEscape(narrow(input.errorMessage())) << "\",\"openMs\":"+ << std::chrono::duration<double, std::milli>(Clock::now() - openStart).count() << "}" << std::endl;+ return 2;+ }+ const double openMs = std::chrono::duration<double, std::milli>(Clock::now() - openStart).count();+ std::ofstream csv(out / "frames.csv");+ csv << "index,ptsSeconds,flags,hash\n";+ uint64_t frames = 0, waits = 0, discontinuities = 0, bigGaps = 0, nonMonotonic = 0;+ double firstPts = -1, lastPts = -1, maxGapMs = 0, waitedMs = 0;+ uint64_t overall = 1469598103934665603ull;+ source::SourceReadStatus status = source::SourceReadStatus::Frame;+ const AVFrame* decoded = nullptr;+ pipeline::FramePacket packet;+ auto start = Clock::now(), lastFrame = start, lastWait = start;+ bool seeked = false;+ double paceBase = -1;+ Clock::time_point paceStart{};+ while (true) {+ if (std::chrono::duration<double>(Clock::now() - start).count() > maxSeconds) { status = source::SourceReadStatus::Eos; break; }+ status = input.read(packet, &decoded);+ if (status == source::SourceReadStatus::Waiting) {+ ++waits;+ std::this_thread::sleep_for(std::chrono::milliseconds(10));+ waitedMs += 10;+ continue;+ }+ if (status != source::SourceReadStatus::Frame) break;+ const auto now = Clock::now();+ const double gap = std::chrono::duration<double, std::milli>(now - lastFrame).count();+ if (frames) { maxGapMs = std::max(maxGapMs, gap); bigGaps += gap > 500; }+ lastFrame = now;+ const double pts = packet.pts.toDouble();+ if (firstPts < 0) firstPts = pts;+ if (lastPts >= 0 && pts <= lastPts && !(packet.flags & (uint32_t(pipeline::FrameFlagBits::Seek) | uint32_t(pipeline::FrameFlagBits::Discontinuity)))) ++nonMonotonic;+ if (packet.flags & uint32_t(pipeline::FrameFlagBits::Discontinuity)) ++discontinuities;+ lastPts = pts;+ const uint64_t h = hash ? lumaHash(decoded) : 0;+ overall = (overall ^ h) * 1099511628211ull;+ csv << frames << ',' << pts << ',' << packet.flags << ',' << h << '\n';+ ++frames;+ if (pace) {+ if (paceBase < 0) { paceBase = pts; paceStart = Clock::now(); }+ const auto due = paceStart + std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>((pts - paceBase)));+ std::this_thread::sleep_until(due);+ }+ if (seekTarget >= 0 && !seeked && frames >= seekAfter) {+ seeked = true;+ const auto seekStart = Clock::now();+ const bool ok = input.seek({int64_t(seekTarget * 1e6), 1000000});+ std::cout << "SEEK ok=" << ok << " ms=" << std::chrono::duration<double, std::milli>(Clock::now() - seekStart).count() << std::endl;+ if (!ok) { status = source::SourceReadStatus::Error; break; }+ paceBase = -1;+ }+ if (double(frames) >= maxFrames) break;+ }+ const auto stats = input.networkStats();+ const double elapsed = std::chrono::duration<double>(Clock::now() - start).count();+ std::ostringstream json;+ json << "{\"opened\":true,\"openMs\":" << openMs << ",\"frames\":" << frames << ",\"firstPts\":" << firstPts << ",\"lastPts\":" << lastPts+ << ",\"status\":\"" << (status == source::SourceReadStatus::Eos ? "eos" : status == source::SourceReadStatus::Frame ? "limit" : status == source::SourceReadStatus::Error ? "error" : "waiting")+ << "\",\"error\":\"" << jsonEscape(narrow(input.errorMessage())) << "\",\"elapsedSeconds\":" << elapsed+ << ",\"maxFrameGapMs\":" << maxGapMs << ",\"gapsOver500ms\":" << bigGaps << ",\"waits\":" << waits << ",\"nonMonotonic\":" << nonMonotonic+ << ",\"discontinuities\":" << discontinuities << ",\"hash\":\"" << std::hex << overall << std::dec << "\""+ << ",\"session\":" << (stats.active ? "true" : "false") << ",\"live\":" << (stats.live ? "true" : "false")+ << ",\"corruptPackets\":" << stats.corruptPackets << ",\"corruptFrames\":" << stats.corruptFrames << ",\"skippedFrames\":" << stats.skippedFrames+ << ",\"reconnects\":" << stats.reconnects << ",\"connections\":" << stats.connections << ",\"stalls\":" << stats.stalls+ << ",\"sessionBytes\":" << stats.sessionBytes << ",\"bandwidthLow\":" << (stats.bandwidthLow ? "true" : "false")+ << ",\"state\":\"" << stateName(stats.state) << "\",\"message\":\"" << jsonEscape(narrow(stats.message)) << "\"}";+ std::cout << "RESULT " << json.str() << std::endl;+ input.close();+ return status == source::SourceReadStatus::Error ? 1 : 0;+}++// ---------------------------------------------------------------------------------------------+int engineTest(const std::wstring& path, const std::filesystem::path& out, const Options& o) {+ CoInitializeEx(nullptr, COINIT_MULTITHREADED);+ std::filesystem::create_directories(out);+ Logger::instance().openFile((out / L"player.log").wstring());+ Logger::instance().setConsoleEnabled(false);+ HWND window = CreateWindowExW(0, L"STATIC", L"Network buffer playback test", WS_POPUP, 0, 0, 960, 540, nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);+ if (!window) return 2;+ ShowWindow(window, SW_SHOWNOACTIVATE);+ engine::EngineController player;+ player.setVolume(0, true);+ engine::PlayerOptions options;+ options.settings.nrRuntime = engine::NrRuntime::NvidiaOriginal;+ options.settings.nrPolicy = pipeline::NrSizePolicy::Realtime;+ options.network = networkSettings(o);+ options.softwareDecode = num(o, "software", 0) != 0;+ const double seconds = num(o, "seconds", 30);+ // events: seek=<target>@<atWallSeconds>, pause=<seconds>@<atWallSeconds>+ double seekTarget = -1, seekAt = 0, pauseFor = 0, pauseAt = 0;+ if (const auto s = str(o, "seek"); !s.empty()) { seekTarget = std::atof(s.c_str()); seekAt = std::atof(s.c_str() + s.find('@') + 1); }+ if (const auto s = str(o, "pause"); !s.empty()) { pauseFor = std::atof(s.c_str()); pauseAt = std::atof(s.c_str() + s.find('@') + 1); }+ std::ofstream timeline(out / "timeline.csv");+ timeline << "t,transport,position,realPresented,state,bufferedSec,targetSec,downloadMBps,serverMBps,bitrateMBps,reconnects,attempt,stalls,corruptPackets,corruptFrames,connections,lateMs,lateP95Ms,failed,status\n";+ const auto begin = Clock::now();+ player.open(window, path, options);+ uint64_t maxFrames = 0, samples = 0;+ double firstFrameAt = -1, maxLate = 0, maxP95 = 0, lastPosition = -1, positionStall = 0, stallStart = -1, maxStall = 0;+ double bufferingSeconds = 0, reconnectingSeconds = 0, playingSeconds = 0, prebufferSeconds = 0;+ std::map<std::string, int> seen;+ bool failed = false, seekDone = false, pauseDone = false, resumed = false;+ std::wstring lastStatus, failure;+ double clockAtBufferingStart = -1, maxClockAdvanceWhileBuffering = 0;+ bool inBuffering = false;+ auto lastSample = begin;+ engine::PlayerSnapshot s;+ while (true) {+ MSG msg;+ while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); }+ const double t = std::chrono::duration<double>(Clock::now() - begin).count();+ if (t > seconds) break;+ s = player.snapshot();+ if (s.failed) { failed = true; failure = s.status; break; }+ const double dt = std::chrono::duration<double>(Clock::now() - lastSample).count();+ lastSample = Clock::now();+ const auto& n = s.network;+ const std::string state = n.active ? stateName(n.state) : "local";+ ++seen[state];+ maxFrames = std::max(maxFrames, s.metrics.flow.counters.realPresented);+ if (firstFrameAt < 0 && s.metrics.flow.counters.realPresented > 0) firstFrameAt = t;+ if (n.active) {+ if (n.state == media::NetworkStats::State::Buffering) bufferingSeconds += dt;+ else if (n.state == media::NetworkStats::State::Reconnecting) reconnectingSeconds += dt;+ else if (n.state == media::NetworkStats::State::Prebuffering) prebufferSeconds += dt;+ else if (n.state == media::NetworkStats::State::Playing) playingSeconds += dt;+ }+ const bool buffering = n.active && (n.state == media::NetworkStats::State::Buffering);+ if (buffering && !inBuffering) { inBuffering = true; clockAtBufferingStart = s.position; }+ if (!buffering && inBuffering) { inBuffering = false; }+ if (inBuffering) maxClockAdvanceWhileBuffering = std::max(maxClockAdvanceWhileBuffering, s.position - clockAtBufferingStart);+ // The picture must keep moving while playing: measure the longest time the position stood still.+ if (s.position != lastPosition) { lastPosition = s.position; stallStart = -1; }+ else if (stallStart < 0) stallStart = t;+ if (stallStart >= 0) maxStall = std::max(maxStall, t - stallStart);+ if (s.transport == engine::TransportState::Playing && firstFrameAt >= 0) { maxLate = std::max(maxLate, std::abs(s.lateMs)); maxP95 = std::max(maxP95, s.lateP95Ms); }+ if (!seekDone && seekTarget >= 0 && t >= seekAt) { seekDone = true; player.seek(seekTarget); }+ if (!pauseDone && pauseFor > 0 && t >= pauseAt) { pauseDone = true; player.pause(true); }+ if (pauseDone && !resumed && t >= pauseAt + pauseFor) { resumed = true; player.pause(false); }+ if ((samples++ % 1) == 0) {+ timeline << t << ',' << int(s.transport) << ',' << s.position << ',' << s.metrics.flow.counters.realPresented << ',' << state << ',' << n.bufferedSeconds << ','+ << n.targetSeconds << ',' << n.downloadBytesPerSecond / 1048576.0 << ',' << n.serverBytesPerSecond / 1048576.0 << ',' << n.bitrateBytesPerSecond / 1048576.0 << ','+ << n.reconnects << ',' << n.reconnectAttempt << ',' << n.stalls << ',' << n.corruptPackets << ',' << n.corruptFrames << ',' << n.connections << ','+ << s.lateMs << ',' << s.lateP95Ms << ',' << s.failed << ",\"" << jsonEscape(narrow(s.status)) << "\"\n";+ }+ if (s.transport == engine::TransportState::Ended) break;+ std::this_thread::sleep_for(std::chrono::milliseconds(50));+ }+ const auto stopAt = Clock::now();+ const double finalPosition = s.position;+ const auto finalNet = s.network;+ player.stop();+ const double stopMs = std::chrono::duration<double, std::milli>(Clock::now() - stopAt).count();+ DestroyWindow(window);+ std::ostringstream json;+ json << "{\"failed\":" << (failed ? "true" : "false") << ",\"failure\":\"" << jsonEscape(narrow(failure)) << "\",\"realPresented\":" << maxFrames+ << ",\"firstFrameSeconds\":" << firstFrameAt << ",\"finalPosition\":" << finalPosition << ",\"maxPositionStallSeconds\":" << maxStall+ << ",\"bufferingSeconds\":" << bufferingSeconds << ",\"reconnectingSeconds\":" << reconnectingSeconds << ",\"prebufferSeconds\":" << prebufferSeconds+ << ",\"playingSeconds\":" << playingSeconds << ",\"maxClockAdvanceWhileBuffering\":" << maxClockAdvanceWhileBuffering+ << ",\"maxLateMs\":" << maxLate << ",\"maxLateP95Ms\":" << maxP95 << ",\"stopMs\":" << stopMs << ",\"states\":{";+ bool first = true;+ for (const auto& [name, count] : seen) { json << (first ? "" : ",") << "\"" << name << "\":" << count; first = false; }+ json << "},\"reconnects\":" << finalNet.reconnects << ",\"stalls\":" << finalNet.stalls << ",\"connections\":" << finalNet.connections+ << ",\"corruptPackets\":" << finalNet.corruptPackets << ",\"corruptFrames\":" << finalNet.corruptFrames << ",\"skippedFrames\":" << finalNet.skippedFrames+ << ",\"sessionBytes\":" << finalNet.sessionBytes << ",\"bandwidthLow\":" << (finalNet.bandwidthLow ? "true" : "false")+ << ",\"bitrateMBps\":" << finalNet.bitrateBytesPerSecond / 1048576.0 << ",\"serverMBps\":" << finalNet.serverBytesPerSecond / 1048576.0+ << ",\"message\":\"" << jsonEscape(narrow(finalNet.message)) << "\"}";+ std::cout << "RESULT " << json.str() << std::endl;+ return failed ? 1 : 0;+}++} // namespace++int wmain(int argc, wchar_t** argv) {+ if (argc >= 2 && std::wstring_view(argv[1]) == L"selftest") return selfTest();+ if (argc < 4) {+ std::cerr << "usage: selftest | source <path-or-url> <outdir> [k=v...] | engine <path-or-url> <outdir> [k=v...]" << std::endl;+ return 2;+ }+ const Options options = parseOptions(argc, argv, 4);+ if (std::wstring_view(argv[1]) == L"source") return sourceTest(argv[2], argv[3], options);+ if (std::wstring_view(argv[1]) == L"engine") return engineTest(argv[2], argv[3], options);+ return 2;+}diff --git a/tests/network/__pycache__/netlib.cpython-311.pyc b/tests/network/__pycache__/netlib.cpython-311.pycnew file mode 100644index 00000000..b70d5112Binary files /dev/null and b/tests/network/__pycache__/netlib.cpython-311.pyc differdiff --git a/tests/network/__pycache__/slow_server.cpython-311.pyc b/tests/network/__pycache__/slow_server.cpython-311.pycnew file mode 100644index 00000000..da936fbbBinary files /dev/null and b/tests/network/__pycache__/slow_server.cpython-311.pyc differdiff --git a/tests/network/make_media.py b/tests/network/make_media.pynew file mode 100644index 00000000..06622f19--- /dev/null+++ b/tests/network/make_media.py@@ -0,0 +1,79 @@+#!/usr/bin/env python3+"""Builds the media the #48 network tests serve (originals are only read, never modified).++ big-4k-av.mkv / big-4k-av.mp4 remux (-c:v copy) of an existing 4K30 ~70 Mbps clip plus a generated AAC track:+ the "huge high-bitrate MKV" a slow server cannot keep up with+ av-720p30-60s.mp4 / .mkv small A/V files (synthetic: running timer + one beep per second)+ av-720p30-10min.ts 10 minutes of MPEG-TS for the packet-loss runs+ live-src.ts 20 s loop source for the real-time /live.ts relay+ hls/vod, hls/multi HLS playlists + segments (single rendition and three renditions)++usage: py -3.11 -I make_media.py --out <dir> --ffmpeg <ffmpeg.exe> --big-source <4k mp4> [--skip-big]+"""+import argparse+import os+import shutil+import subprocess+import sys+from pathlib import Path+++def run(cmd):+ print(' '.join(str(c) for c in cmd), flush=True)+ subprocess.run([str(c) for c in cmd], check=True)+++def main():+ p = argparse.ArgumentParser()+ p.add_argument('--out', required=True)+ p.add_argument('--ffmpeg', required=True)+ p.add_argument('--big-source', default='')+ p.add_argument('--skip-big', action='store_true')+ a = p.parse_args()+ out = Path(a.out)+ out.mkdir(parents=True, exist_ok=True)+ ff = a.ffmpeg+ common = [ff, '-y', '-hide_banner', '-loglevel', 'error', '-nostdin']++ if not a.skip_big and a.big_source:+ for name, extra in (('big-4k-av.mkv', ['-f', 'matroska']), ('big-4k-av.mp4', ['-movflags', '+faststart'])):+ target = out / name+ if target.exists():+ continue+ run(common + ['-i', a.big_source, '-f', 'lavfi', '-i', 'sine=frequency=440:beep_factor=4:sample_rate=48000',+ '-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '128k', '-shortest'] + extra + [target])++ synthetic = ['-f', 'lavfi', '-i', 'testsrc2=size=1280x720:rate=30',+ '-f', 'lavfi', '-i', 'sine=frequency=1000:beep_factor=4:sample_rate=48000']+ encode = ['-c:v', 'libx264', '-preset', 'veryfast', '-b:v', '3M', '-maxrate', '4M', '-bufsize', '6M', '-g', '60',+ '-keyint_min', '60', '-sc_threshold', '0', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '128k']+ for name, extra in (('av-720p30-60s.mp4', ['-movflags', '+faststart']), ('av-720p30-60s.mkv', [])):+ if not (out / name).exists():+ run(common + synthetic + ['-t', '60'] + encode + extra + [out / name])+ if not (out / 'av-720p30-10min.ts').exists():+ run(common + synthetic + ['-t', '600'] + encode + ['-f', 'mpegts', out / 'av-720p30-10min.ts'])+ if not (out / 'live-src.ts').exists():+ run(common + synthetic + ['-t', '20'] + encode + ['-f', 'mpegts', out / 'live-src.ts'])++ hls = out / 'hls'+ vod = hls / 'vod'+ if not (vod / 'index.m3u8').exists():+ vod.mkdir(parents=True, exist_ok=True)+ run(common + ['-i', out / 'av-720p30-60s.mp4', '-c', 'copy', '-f', 'hls', '-hls_time', '4', '-hls_playlist_type', 'vod',+ '-hls_segment_filename', vod / 'seg%03d.ts', vod / 'index.m3u8'])+ multi = hls / 'multi'+ if not (multi / 'master.m3u8').exists():+ multi.mkdir(parents=True, exist_ok=True)+ run(common + synthetic + ['-t', '40', '-filter_complex',+ '[0:v]split=3[a][b][c];[a]scale=640:360[v0];[b]scale=960:540[v1];[c]scale=1280:720[v2]',+ '-map', '[v0]', '-map', '[v1]', '-map', '[v2]', '-map', '1:a', '-map', '1:a', '-map', '1:a',+ '-c:v', 'libx264', '-preset', 'veryfast', '-g', '60', '-sc_threshold', '0', '-pix_fmt', 'yuv420p',+ '-b:v:0', '600k', '-b:v:1', '1400k', '-b:v:2', '3000k', '-c:a', 'aac', '-b:a', '96k',+ '-f', 'hls', '-hls_time', '4', '-hls_playlist_type', 'vod', '-master_pl_name', 'master.m3u8',+ '-var_stream_map', 'v:0,a:0 v:1,a:1 v:2,a:2',+ '-hls_segment_filename', multi / 'v%v_seg%03d.ts', multi / 'v%v.m3u8'])+ print('media ready:', out)+++if __name__ == '__main__':+ main()diff --git a/tests/network/netlib.py b/tests/network/netlib.pynew file mode 100644index 00000000..a9f61b1c--- /dev/null+++ b/tests/network/netlib.py@@ -0,0 +1,106 @@+"""Shared helpers for the #48 network tests: start/stop slow_server.py, run the C++ test program,+parse its RESULT line. Standard library only."""+import json+import os+import subprocess+import sys+import time+import urllib.request+from pathlib import Path++BASE = Path('E:/项目/Veyra')+TASK = 'claude-network-buffer-48-20261017'+APP = BASE / 'tests' / TASK / 'app'+MEDIA = BASE / 'tests' / TASK / 'media'+EXE = APP / 'veyra_network_buffer_tests.exe'+SERVER = Path(__file__).resolve().parent / 'slow_server.py'+FFMPEG = Path('C:/Users/123/AppData/Local/Microsoft/WinGet/Packages/Gyan.FFmpeg_Microsoft.Winget.Source_8wekyb3d8bbwe/ffmpeg-8.1.1-full_build/bin/ffmpeg.exe')+++def clean_env(extra=None):+ env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_', 'QML_'))}+ tmp = BASE / 'tmp' / TASK / 'run'+ tmp.mkdir(parents=True, exist_ok=True)+ env.update(TEMP=str(tmp), TMP=str(tmp))+ if extra:+ env.update({k: str(v) for k, v in extra.items()})+ return env+++class Server:+ """slow_server.py as a child process; port picked by the OS and read back from a file."""++ def __init__(self, logdir, root=MEDIA, **flags):+ self.logdir = Path(logdir)+ self.logdir.mkdir(parents=True, exist_ok=True)+ self.root = root+ self.flags = flags+ self.proc = None+ self.port = 0++ def __enter__(self):+ portfile = self.logdir / 'server.port'+ if portfile.exists():+ portfile.unlink()+ cmd = [sys.executable, '-I', str(SERVER), '--root', str(self.root), '--port-file', str(portfile),+ '--log', str(self.logdir / 'server.jsonl'), '--ffmpeg', str(FFMPEG)]+ for key, value in self.flags.items():+ flag = '--' + key.replace('_', '-')+ if isinstance(value, list):+ for item in value:+ cmd += [flag, str(item)]+ elif value is True:+ cmd.append(flag)+ elif value is not None and value is not False:+ cmd += [flag, str(value)]+ self.out = (self.logdir / 'server.out').open('wb')+ self.proc = subprocess.Popen(cmd, stdout=self.out, stderr=subprocess.STDOUT, creationflags=0x08000000)+ deadline = time.time() + 20+ while time.time() < deadline:+ if portfile.exists() and portfile.read_text().strip():+ self.port = int(portfile.read_text().strip())+ self.control = int(Path(str(portfile) + '.control').read_text().strip())+ break+ if self.proc.poll() is not None:+ raise RuntimeError('server exited: ' + (self.logdir / 'server.out').read_text(errors='replace'))+ time.sleep(0.05)+ if not self.port:+ raise RuntimeError('server did not start')+ return self++ def __exit__(self, *exc):+ if self.proc and self.proc.poll() is None:+ self.proc.terminate()+ try:+ self.proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ self.proc.kill()+ self.out.close()++ def url(self, name):+ return f'http://127.0.0.1:{self.port}/{name}'++ def stats(self):+ with urllib.request.urlopen(f'http://127.0.0.1:{self.control}/', timeout=5) as r:+ return json.loads(r.read())+++def run_exe(mode, target, outdir, options=None, env=None, timeout=280):+ """Runs veyra_network_buffer_tests; returns (returncode, RESULT json or None, seconds)."""+ outdir = Path(outdir)+ outdir.mkdir(parents=True, exist_ok=True)+ cmd = [str(EXE), mode, str(target), str(outdir)] + [f'{k}={v}' for k, v in (options or {}).items()]+ start = time.time()+ with (outdir / 'stdout.txt').open('wb') as out:+ try:+ p = subprocess.run(cmd, cwd=str(APP), env=clean_env(env), stdout=out, stderr=subprocess.STDOUT,+ timeout=timeout, creationflags=0x08000000)+ rc = p.returncode+ except subprocess.TimeoutExpired:+ rc = 124+ seconds = time.time() - start+ result = None+ for line in (outdir / 'stdout.txt').read_text(encoding='utf8', errors='replace').splitlines():+ if line.startswith('RESULT '):+ result = json.loads(line[7:])+ return rc, result, secondsdiff --git a/tests/network/slow_server.py b/tests/network/slow_server.pynew file mode 100644index 00000000..6b882457--- /dev/null+++ b/tests/network/slow_server.py@@ -0,0 +1,482 @@+#!/usr/bin/env python3+"""Local media server for the #48 network-playback tests (Python standard library only).++It stands in for the slow / unreliable servers the user does not have:++ * serves files below --root with HTTP Range support (progressive MP4/MKV, HLS playlists + segments);+ * --rate-mbps R one shared link of R megabytes per second for every connection;+ * --stall-at S1,S2 at server second S every transfer freezes for --stall-seconds (connection stays open);+ * --outage-at S at server second S active transfers are reset and new connections are reset for+ --outage-seconds (a cable pulled out);+ * --drop-after-mb M every response is cut off (reset) after M megabytes of body;+ * --ts-flip RATIO damages RATIO of the 188-byte packets of *.ts files (size preserved, so Range+ requests stay consistent): transport-error bit + garbled payload;+ * --live NAME=FILE /NAME is an endless real-time MPEG-TS stream relayed from ffmpeg looping FILE+ (no Content-Length); --ts-drop RATIO removes that fraction of its TS packets+ (IPTV-style packet loss, produces continuity errors);+ * /__stats JSON: connections, in-flight requests, bytes sent, per-request log.++Everything is logged to --log (one JSON object per line) and summarised at /__stats.+"""+import argparse+import http.server+import json+import mimetypes+import os+import queue+import random+import socket+import socketserver+import struct+import subprocess+import sys+import threading+import time+from urllib.parse import unquote, urlparse++TS = 188+CHUNK = 64 * 1024+++class Shaper:+ """One shared link: global rate limit, scheduled stalls and an outage window."""++ def __init__(self, args):+ self.rate = args.rate_mbps * 1048576.0 if args.rate_mbps > 0 else 0.0+ self.stalls = [(float(s), float(args.stall_seconds)) for s in args.stall_at.split(',') if s]+ self.outage = (float(args.outage_at), float(args.outage_seconds)) if args.outage_at >= 0 else None+ self.t0 = time.monotonic()+ self.lock = threading.Lock()+ self.tokens = 0.0+ self.last = time.monotonic()+ self.generation = 0 # bumped when an outage starts: in-flight transfers see it and reset+ self._outage_started = False++ def now(self):+ return time.monotonic() - self.t0++ def stalled(self):+ t = self.now()+ return any(start <= t < start + length for start, length in self.stalls)++ def in_outage(self):+ if not self.outage:+ return False+ t = self.now()+ active = self.outage[0] <= t < self.outage[0] + self.outage[1]+ if active and not self._outage_started:+ self._outage_started = True+ self.generation += 1+ return active++ def wait(self, nbytes, stop):+ """Blocks until nbytes may go out. Returns False when the transfer must be reset."""+ gen = self.generation+ while not stop.is_set():+ if self.in_outage() or self.generation != gen:+ return False+ if self.stalled():+ time.sleep(0.05)+ continue+ if not self.rate:+ return True+ with self.lock:+ now = time.monotonic()+ self.tokens = min(self.tokens + (now - self.last) * self.rate, max(self.rate * 0.05, CHUNK))+ self.last = now+ if self.tokens >= nbytes:+ self.tokens -= nbytes+ return True+ need = (nbytes - self.tokens) / self.rate+ time.sleep(min(max(need, 0.001), 0.05))+ return False+++class Stats:+ def __init__(self):+ self.lock = threading.Lock()+ self.connections = 0+ self.refused = 0+ self.in_flight = 0+ self.max_in_flight = 0+ self.bytes_sent = 0+ self.requests = []++ def begin(self, path, rng, client):+ with self.lock:+ rec = {'id': len(self.requests) + 1, 't': round(time.monotonic() - T0, 3), 'path': path, 'range': rng,+ 'client': client, 'bytes': 0, 'endT': None, 'result': 'open'}+ self.requests.append(rec)+ self.in_flight += 1+ self.max_in_flight = max(self.max_in_flight, self.in_flight)+ return rec++ def add(self, rec, n):+ with self.lock:+ rec['bytes'] += n+ self.bytes_sent += n++ def end(self, rec, result):+ with self.lock:+ rec['endT'] = round(time.monotonic() - T0, 3)+ rec['result'] = result+ self.in_flight -= 1+ log(dict(event='request-end', id=rec['id'], path=rec['path'], range=rec['range'], bytes=rec['bytes'], result=result))++ def snapshot(self):+ with self.lock:+ return dict(connections=self.connections, refused=self.refused, inFlight=self.in_flight,+ maxInFlight=self.max_in_flight, bytesSent=self.bytes_sent,+ requestCount=len(self.requests), requests=list(self.requests[-200:]),+ serverSeconds=round(time.monotonic() - T0, 3))+++T0 = time.monotonic()+ARGS = None+SHAPER = None+STATS = Stats()+LOG = None+LOG_LOCK = threading.Lock()+STOP = threading.Event()+LIVE = {}+ACTIVE = set()+ACTIVE_LOCK = threading.Lock()+++def reset_all():+ """A cable pulled out: every open connection dies with a reset, even one blocked in a write."""+ with ACTIVE_LOCK:+ sockets = list(ACTIVE)+ for sock in sockets:+ try:+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))+ sock.close()+ except OSError:+ pass+++def outage_watcher():+ started = False+ while not STOP.is_set():+ if SHAPER.in_outage() and not started:+ started = True+ log(dict(event='outage-start'))+ reset_all()+ elif started and not SHAPER.in_outage():+ started = False+ log(dict(event='outage-end'))+ time.sleep(0.02)+++def log(obj):+ obj['t'] = round(time.monotonic() - T0, 3)+ if LOG:+ with LOG_LOCK:+ LOG.write(json.dumps(obj, ensure_ascii=False) + '\n')+ LOG.flush()+++def flip_ts(buf, base, ratio, seed):+ """Deterministically damages ratio of the TS packets in buf (which starts at absolute offset base)."""+ if ratio <= 0:+ return buf+ data = bytearray(buf)+ first = -(-base // TS) * TS # first packet boundary at or after base+ for off in range(first - base, len(data) - TS + 1, TS):+ index = (base + off) // TS+ h = ((index * 2654435761) ^ seed) & 0xFFFFFFFF+ if h / 4294967296.0 < ratio:+ data[off + 1] |= 0x80 # transport_error_indicator+ for i in range(off + 12, off + TS, 7):+ data[i] ^= 0x5A+ return bytes(data)+++class Handler(http.server.BaseHTTPRequestHandler):+ protocol_version = 'HTTP/1.1'+ server_version = 'veyra-test/1'++ def log_message(self, fmt, *a):+ pass++ def setup(self):+ super().setup()+ with STATS.lock:+ STATS.connections += 1+ with ACTIVE_LOCK:+ ACTIVE.add(self.connection)+ if SHAPER.in_outage():+ with STATS.lock:+ STATS.refused += 1+ self.reset()++ def finish(self):+ with ACTIVE_LOCK:+ ACTIVE.discard(self.connection)+ try:+ super().finish()+ except OSError:+ pass++ def reset(self):+ try:+ self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))+ self.connection.close()+ except OSError:+ pass+ self.close_connection = True++ def do_HEAD(self):+ self.serve(True)++ def do_GET(self):+ self.serve(False)++ def serve(self, head):+ path = unquote(urlparse(self.path).path)+ if path == '/__stats':+ body = json.dumps(STATS.snapshot()).encode()+ self.send_response(200)+ self.send_header('Content-Type', 'application/json')+ self.send_header('Content-Length', str(len(body)))+ self.end_headers()+ self.wfile.write(body)+ return+ if path.lstrip('/') in LIVE:+ return self.serve_live(path.lstrip('/'))+ full = os.path.normpath(os.path.join(ARGS.root, path.lstrip('/')))+ if not full.startswith(os.path.normpath(ARGS.root)) or not os.path.isfile(full):+ self.send_response(404)+ self.send_header('Content-Length', '0')+ self.end_headers()+ return+ size = os.path.getsize(full)+ start, end, status = 0, size - 1, 200+ rng = self.headers.get('Range')+ if rng and rng.startswith('bytes='):+ a, _, b = rng[6:].partition('-')+ try:+ start = int(a) if a else max(0, size - int(b))+ end = min(int(b), size - 1) if (a and b) else size - 1+ except ValueError:+ start, end = 0, size - 1+ if start >= size:+ self.send_response(416)+ self.send_header('Content-Range', f'bytes */{size}')+ self.send_header('Content-Length', '0')+ self.end_headers()+ return+ status = 206+ ctype = {'.m3u8': 'application/vnd.apple.mpegurl', '.ts': 'video/mp2t', '.mkv': 'video/x-matroska'}.get(+ os.path.splitext(full)[1].lower()) or mimetypes.guess_type(full)[0] or 'application/octet-stream'+ self.send_response(status)+ self.send_header('Content-Type', ctype)+ self.send_header('Accept-Ranges', 'bytes')+ self.send_header('Content-Length', str(end - start + 1))+ if status == 206:+ self.send_header('Content-Range', f'bytes {start}-{end}/{size}')+ self.end_headers()+ rec = STATS.begin(path, [start, end], self.client_address[1])+ if head:+ STATS.end(rec, 'head')+ return+ result = 'done'+ is_ts = full.lower().endswith('.ts')+ try:+ with open(full, 'rb') as f:+ f.seek(start)+ pos = start+ limit = ARGS.drop_after_mb * 1048576 if ARGS.drop_after_mb > 0 else None+ sent = 0+ while pos <= end:+ n = min(CHUNK, end - pos + 1)+ if limit is not None and sent + n > limit:+ n = int(limit - sent)+ if n <= 0:+ result = 'dropped'+ self.reset()+ break+ chunk = f.read(n)+ if not chunk:+ break+ if is_ts and ARGS.ts_flip > 0:+ chunk = flip_ts(chunk, pos, ARGS.ts_flip, ARGS.seed)+ if not SHAPER.wait(len(chunk), STOP):+ result = 'reset'+ self.reset()+ break+ self.wfile.write(chunk)+ pos += len(chunk)+ sent += len(chunk)+ STATS.add(rec, len(chunk))+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):+ result = 'client-closed'+ self.close_connection = True+ STATS.end(rec, result)++ # ---- live MPEG-TS relay -------------------------------------------------------------+ def serve_live(self, name):+ feed = LIVE[name]+ q = feed.subscribe()+ self.send_response(200)+ self.send_header('Content-Type', 'video/mp2t')+ self.send_header('Cache-Control', 'no-cache')+ self.send_header('Connection', 'close')+ self.end_headers()+ self.close_connection = True+ rec = STATS.begin('/' + name, None, self.client_address[1])+ rnd = random.Random(ARGS.seed + rec['id'])+ result = 'done'+ gen = SHAPER.generation+ try:+ while not STOP.is_set():+ try:+ chunk = q.get(timeout=1.0)+ except queue.Empty:+ continue+ if SHAPER.in_outage() or SHAPER.generation != gen:+ result = 'reset'+ self.reset()+ break+ if SHAPER.stalled():+ while SHAPER.stalled() and not STOP.is_set():+ time.sleep(0.05)+ # the stream moved on during the stall; a real stalled TCP link delivers the backlog+ if ARGS.ts_drop > 0:+ kept = bytearray()+ for off in range(0, len(chunk) - TS + 1, TS):+ if rnd.random() >= ARGS.ts_drop:+ kept += chunk[off:off + TS]+ chunk = bytes(kept)+ self.wfile.write(chunk)+ STATS.add(rec, len(chunk))+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):+ result = 'client-closed'+ finally:+ feed.unsubscribe(q)+ STATS.end(rec, result)+++class ControlHandler(http.server.BaseHTTPRequestHandler):+ """Statistics on a second port that no outage, stall or rate limit touches."""++ def log_message(self, fmt, *a):+ pass++ def do_GET(self):+ body = json.dumps(STATS.snapshot()).encode()+ self.send_response(200)+ self.send_header('Content-Type', 'application/json')+ self.send_header('Content-Length', str(len(body)))+ self.end_headers()+ self.wfile.write(body)+++class LiveFeed:+ """ffmpeg -re -stream_loop -1 -c copy -f mpegts - -> every subscriber's bounded queue."""++ def __init__(self, path):+ self.path = path+ self.lock = threading.Lock()+ self.queues = []+ ffmpeg = ARGS.ffmpeg+ cmd = [ffmpeg, '-nostdin', '-hide_banner', '-loglevel', 'error', '-re', '-stream_loop', '-1', '-i', path,+ '-c', 'copy', '-muxdelay', '0', '-f', 'mpegts', '-']+ self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)+ threading.Thread(target=self.pump, daemon=True).start()++ def pump(self):+ size = TS * 7 * 8 # 10528 bytes, a whole number of TS packets+ buf = b''+ while not STOP.is_set():+ data = self.proc.stdout.read(size)+ if not data:+ break+ buf += data+ usable = len(buf) // TS * TS+ chunk, buf = buf[:usable], buf[usable:]+ if not chunk:+ continue+ with self.lock:+ for q in self.queues:+ try:+ q.put_nowait(chunk)+ except queue.Full:+ pass # a stalled client loses data, like a real overloaded link++ def subscribe(self):+ q = queue.Queue(maxsize=4000)+ with self.lock:+ self.queues.append(q)+ return q++ def unsubscribe(self, q):+ with self.lock:+ if q in self.queues:+ self.queues.remove(q)++ def close(self):+ try:+ self.proc.kill()+ except OSError:+ pass+++class Server(socketserver.ThreadingMixIn, http.server.HTTPServer):+ daemon_threads = True+ allow_reuse_address = True+ request_queue_size = 64+++def main():+ global ARGS, SHAPER, LOG+ p = argparse.ArgumentParser()+ p.add_argument('--root', required=True)+ p.add_argument('--port', type=int, default=0)+ p.add_argument('--port-file', default='')+ p.add_argument('--rate-mbps', type=float, default=0.0)+ p.add_argument('--stall-at', default='')+ p.add_argument('--stall-seconds', type=float, default=10.0)+ p.add_argument('--outage-at', type=float, default=-1.0)+ p.add_argument('--outage-seconds', type=float, default=8.0)+ p.add_argument('--drop-after-mb', type=float, default=0.0)+ p.add_argument('--ts-flip', type=float, default=0.0)+ p.add_argument('--ts-drop', type=float, default=0.0)+ p.add_argument('--live', action='append', default=[])+ p.add_argument('--ffmpeg', default=os.environ.get('FFMPEG', 'ffmpeg'))+ p.add_argument('--seed', type=int, default=48)+ p.add_argument('--log', default='')+ ARGS = p.parse_args()+ ARGS.root = os.path.abspath(ARGS.root)+ SHAPER = Shaper(ARGS)+ if ARGS.log:+ LOG = open(ARGS.log, 'w', encoding='utf8')+ for spec in ARGS.live:+ name, _, path = spec.partition('=')+ LIVE[name] = LiveFeed(os.path.join(ARGS.root, path) if not os.path.isabs(path) else path)+ if SHAPER.outage:+ threading.Thread(target=outage_watcher, daemon=True).start()+ server = Server(('127.0.0.1', ARGS.port), Handler)+ port = server.server_address[1]+ control = http.server.ThreadingHTTPServer(('127.0.0.1', 0), ControlHandler)+ threading.Thread(target=control.serve_forever, daemon=True).start()+ if ARGS.port_file:+ with open(ARGS.port_file + '.control', 'w') as f:+ f.write(str(control.server_address[1]))+ with open(ARGS.port_file, 'w') as f:+ f.write(str(port))+ log(dict(event='listening', port=port, args=vars(ARGS)))+ print(f'listening on http://127.0.0.1:{port}', flush=True)+ try:+ server.serve_forever(poll_interval=0.2)+ except KeyboardInterrupt:+ pass+ finally:+ STOP.set()+ for feed in LIVE.values():+ feed.close()+ server.server_close()+++if __name__ == '__main__':+ main()