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++
Demux session: timestamp-independent flow control, restarted live timelines, 2 s reconnect cap
Veyra Goal Agentd46d47a108e7
diff --git a/docs/NETWORK_BUFFER_48_PLAN_2026-10-17.md b/docs/NETWORK_BUFFER_48_PLAN_2026-10-17.mdindex 8754ebc7..0068cc40 100644--- a/docs/NETWORK_BUFFER_48_PLAN_2026-10-17.md+++ b/docs/NETWORK_BUFFER_48_PLAN_2026-10-17.md@@ -36,6 +36,16 @@- 会话使用范围:`http/https/rtsp` 地址,UNC 路径(`\\server\share\…`,不含 `\\?\C:\` 本地扩展路径)与 `GetDriveType==DRIVE_REMOTE` 的映射盘。测试开关 `VEYRA_TEST_FORCE_DEMUX_SESSION=1` 可让本地文件也走会话,用于与直读路径逐帧对照。- 测试用慢速 IO:`VEYRA_TEST_SLOW_IO=<MB/s>[,<ms 延迟>]` 在会话的自定义文件 AVIO 上限速并加读延迟,模拟 NAS;不新建系统共享。+实施中另有这些与计划文字不同的地方(均已按下面的“设计”一节更新):++- **重连退避**:1 s,之后每 2 s 一次(计划为 1/2/4/8 s 封顶 8 s),总预算 60 s;HTTP 内层 `reconnect_delay_max=2`。服务端无论何时恢复,下一次重试最多 2 秒后到来,给“等关键帧 + 起播缓冲”留出 5 秒内恢复的余量(首轮实测封顶 4 s 时直播 8 秒断流的恢复为 4.47 s,余量只有 0.5 s,所以改成 2 s)。+- **恢复目标上限**:慢服务器的“暂停缓冲”攒够 `clamp(60×(1−速度/码率), 起播目标, 上限)` 秒再放行,上限 20 s(“大”档 45 s),不是计划里的“约一分钟”。慢服务器填满 60 秒窗口所需的时间与播放它一样长,用户要等太久;改为较短的多次放行,每次停顿都带原因提示。+- **损坏画面**:不用 `recoverAtKeyframe()`(`skip_frame=NONKEY` 与帧线程并用时输出异常);“等下一个关键帧”改为清空解码器并丢包到干净关键帧(最长 5 秒后放行);解码器报错用漏桶计数,2 秒内超过 12 次才算真正失败。+- **被截断的包按断线处理**:包带 `AV_PKT_FLAG_CORRUPT` 且 `pb->error<0` 说明连接在包中间断了。2.0.9 的 HTTP 点播遇到服务器中途断开,MP4 解复用器正是交出这种截断包,被 `MediaFileSource` 报成“源视频包含损坏数据,已停止处理”——这是 #48 的另一个来源。现在丢弃该包并走重连。+- **HLS 主播放列表**:打开后只保留画质最高的一个变体,其余变体的流设 `AVDISCARD_ALL`,HLS 解复用器随即不再下载它们(FFmpeg 在读头时仍会取每个变体的前 1–2 个分片)。按代码推断,2.0.9 的视频解复用器只丢弃非视频流、音频管线另开一个上下文,所有画质的视频流都会持续下载;未在 2.0.9 构建上实测。+- **字幕旁路未做**:2.0.9 本来就不对网络地址扫描字幕,保持不变(网络地址不开任何字幕连接);只做 NAS 路径的“延后 + 限速 + 让出”,见 §3.5。+- 引擎在 `open()` 里经 `PlayerOptions::from()` 往返会丢掉 `PlayerOptions::deinterlace`(2.0.9 已有的缺陷,设置里的“自动去隔行”开关因此不起作用);与本任务无关,只在 `network` 字段旁保留了同样的往返,缺陷本身未改,列为后续。+## 3. 设计### 3.1 新增 / 修改的代码@@ -55,37 +65,37 @@### 3.2 解复用会话-- 解复用线程循环:`av_read_frame` → 视频包进视频队列,所选音轨的包进音频队列,字幕包进(有上限的)字幕旁路,其它丢弃。每次读包前设读期限,打开/探测用连接期限;用户停止或切源(`cancelled`)、会话销毁、seek 请求都会立即打断阻塞读。-- 队列上限:软目标 S(档位:小 8 s / 中·自动 30 s / 大 120 s;直播抖动缓冲 0.5 / 1 / 1.5 / 3 s),按“最短一路相对播放位置的前瞻”判断;同时有字节硬上限(64 / 256 / 1024 MB)取小。任一路前瞻 < S 就继续读,另一路最多超出到硬上限,避免交错偏移饿死另一路。+- 解复用线程循环:`av_read_frame` → 视频包进视频队列,所选音轨的包进音频队列,其它流(含字幕)设 `AVDISCARD_ALL`。每次读包前设读期限(点播 20 s、直播 10 s),打开用连接期限 15 s、探测 30 s;用户停止或切源(`cancelled`)、会话销毁、seek 请求都会立即打断阻塞读。+- 队列上限:软目标 S(点播:小 8 s / 中·自动 30 s / 大 120 s;直播抖动缓冲 小 1.5 s / 中 3 s / 大 6 s,自动 3 s;实现见 `NetworkBufferPlan`),按“最短一路相对播放位置的前瞻”判断;同时有字节硬上限(点播 64 / 256 / 1024 MB,直播 32 / 64 / 128 MB)。自动档在服务器偏慢时窗口可放大到 120 s / 1024 MB。任一路前瞻 < S 就继续读,另一路最多超出到硬上限,避免交错偏移饿死另一路。- 播放位置由引擎每轮写入(音频时钟或最后呈现 PTS);起播/seek 后的前瞻 = 队列跨度。- 码率估计:容器 `bit_rate` 或队列字节 / PTS 跨度(≥3 s 样本后取实测);下载速度 = 解复用线程“读包中”的字节 / 读包耗时(EMA),另报 2 秒窗口平均。-- 状态机:`Prebuffering`(起播或 seek 后,前瞻 ≥ 起播目标或 EOF 才放行)→ `Playing`(前瞻 < 低水位 0.25 s 且未 EOF → `Buffering`)→ `Buffering`(前瞻 ≥ 恢复目标或 EOF → `Playing`);`Reconnecting` 叠加在读线程上,消费方继续用队列里的包,队列见底才进入 `Buffering`。-- 自适应恢复目标(C7):持续(≥5 s 读包时间)下载速度 < 码率 × 0.95 时置 `bandwidthLow`,恢复目标 = clamp(60 × (1 − 速度/码率), 起播目标, 队列上限),使每次放行至少连续播放约一分钟;界面提示“服务器速度 x MB/s 低于视频码率 y MB/s,建议加大缓冲或下载后播放”。绝不降速播放、不报错黑屏。+- 状态机:`Prebuffering`(起播或 seek 后,前瞻 ≥ 起播目标或 EOF 才放行)→ `Playing`(前瞻 < 低水位(0.25–0.5 s,随档位)且未 EOF → `Buffering`)→ `Buffering`(前瞻 ≥ 恢复目标或 EOF → `Playing`);`Reconnecting` 叠加在读线程上,消费方继续用队列里的包,队列见底才进入 `Buffering`。档位“关闭”不停顿(`holds=false`)。+- 自适应恢复目标(C7):持续(≥5 s 读包时间)下载速度 < 码率 × 0.95 时置 `bandwidthLow`(带滞回),恢复目标 = clamp(60 × (1 − 速度/码率), 起播目标, 20 s(“大”档 45 s));界面提示“服务器速度 x MB/s 低于视频码率 y MB/s,建议加大缓冲或下载后播放”。绝不降速播放、不报错黑屏。- 暂停缓冲:会话告知 `MediaFileSource::read()` 返回 `Waiting`(引擎主循环已按活源处理,画面停在当前帧);音频线程因会话 hold 而暂停端点,设备时钟冻结,恢复后继续,不丢 PCM、不拿静音冒充同步。### 3.3 重连(C2)- 触发:读包返回非 EOF 错误、读期限超时、连续 10 秒只有损坏数据。关闭用户设置“断线自动重连”时直接报错(带原因)。-- 退避 1 / 2 / 4 / 8 s 封顶 8 s,总时长上限 60 s(可测试覆盖);用户停止立即中断;每次尝试用连接期限 15 s。+- 退避 1 s,之后每 2 s 一次,总预算 60 s(测试开关 `VEYRA_TEST_RECONNECT_BUDGET_MS` 可改);用户停止立即中断;每次尝试用连接期限 15 s。读包返回的截断包(`AV_PKT_FLAG_CORRUPT` 且 `pb->error<0`)与读期限超时同样触发重连。- 点播(可 seek 且时长已知):重新打开后 `av_seek_frame(最后入队视频 DTS, BACKWARD)`,每路丢弃 DTS ≤ 该路最后入队 DTS 的重复包,队列已有的包照常播放,解码器不重置。HLS 点播同理(按分片重新定位)。-- 直播(不可 seek):重新打开,丢弃首个视频关键帧之前的包,时间戳平移使新连接首个关键帧紧接上一连接结束时间(连续时间线,音视频同一平移量),队列首包带“不连续”标记,解码器清空,帧带 `Discontinuity` 使图历史重置。+- 直播(不可 seek):重新打开,丢弃首个视频关键帧之前的包,时间戳平移使新连接首个关键帧紧接上一连接结束时间(连续时间线,音视频同一平移量),队列首包带“不连续”标记,解码器 `flushBuffers()`,帧带 `Discontinuity` 使图历史重置;重连后的音频包若解码报 `AVERROR_INVALIDDATA` 视为坏包跳过(连续 8 次才算失败)。- HTTP 同时打开 FFmpeg `reconnect`、`reconnect_streamed`、`reconnect_on_network_error`、`reconnect_delay_max`(内层快速重试),HLS 设 `seg_max_retry`。### 3.4 损坏容错(C1)- `SourceOpenDesc::tolerateCorruption`:引擎对网络源与 `mpegts` 容器默认置真;导出、测试工具、`MediaFileSource` 默认值保持严格。-- 损坏包照常送解码器(FFmpeg 自带隐藏/修补);解码失败的单个包记数后继续;带 `AV_FRAME_FLAG_CORRUPT`/`decode_error_flags` 的帧按“损坏画面”策略:`显示修补结果`(默认)或 `等下一个关键帧`(`recoverAtKeyframe` 丢弃至关键帧)。-- 计数与限频日志(≥1 秒一条);状态“检测到网络丢包,已自动跳过 n 处”;连续 10 秒无好帧 → C2 重连。+- 损坏包照常送解码器(FFmpeg 自带隐藏/修补);解码失败的单个包记数后继续;带 `AV_FRAME_FLAG_CORRUPT`/`decode_error_flags` 的帧按“损坏画面”策略:`保持画面`(默认,显示解码器修补结果)或 `等待关键帧`(清空解码器并丢包到干净关键帧,最长 5 秒后放行)。解码器报错用漏桶计数,2 秒内超过 12 次才算真正失败。+- 计数与限频日志(≥1 秒一条);界面提示“检测到网络丢包,已自动跳过 n 处”(每会话至少隔 20 秒一次);连续 10 秒无输出 → 强制重连(两次之间至少隔 30 秒)。### 3.5 字幕(C5)-- 网络地址:不开第二、三连接。会话把字幕包旁路给字幕加载器(有上限、可丢弃);点播在起播缓冲达到目标后才读取,不与播放抢带宽。-- NAS / 映射盘:整文件扫描延后到起播缓冲达标之后,限速(受 `VEYRA_TEST_SLOW_IO` 同样影响),播放缓冲低于低水位时让出读取。+- 网络地址:不开任何字幕连接(与 2.0.9 相同:网络地址不扫描内嵌字幕,也没有字幕旁路;已知限制)。+- NAS / 映射盘(`engine::subtitleServerFile`):`SubtitleLoader::setReadGate` 由桥接按引擎的网络统计开关——会话 `Playing`、前瞻 ≥ 3 s 且服务器不比码流慢才放行(前瞻 < 1 s 即关,播放读完整个文件时也放行)。扫描在放行前不打开文件;放行后经 64 KiB 缓冲的限速 AVIO 读(≤ 40 MB/s,`VEYRA_TEST_SLOW_IO` 同样生效),门一关读取立即停住。Matroska 等容器为找字幕包要读完整个文件,所以这是整文件流量;服务器比码流慢时整个扫描不会开始。外部字幕文件(小文件)与本地文件走原来的路径。### 3.6 设置与状态(C6)-- 设置→播放:`网络缓冲`(自动/关闭/小/中/大,默认自动)、`起播预缓冲`(自动/不等待/3/5/10/20/30 秒)、`断线自动重连`(默认开)、`损坏画面`(显示修补结果/等下一个关键帧)。均为保存的偏好,下次打开地址生效。-- 信号面板(ProPage 的“信号”卡)新增“网络”行:`缓冲 18.2 s · 下载 12.4 MB/s · 重连 0`;缓冲中显示进度而不是黑屏报错。四语翻译进 `i18n/catalog.json`。+- 设置→播放:`网络缓冲`(自动/关闭/小/中/大,默认自动)、`起播预缓冲`(跟随缓冲档/不等待/3/5/10/20/30 秒)、`断线自动重连`(默认开)、`损坏画面处理`(保持画面/等待关键帧)。均为保存的偏好(`networkBuffer` / `networkPrebuffer` / `networkAutoReconnect` / `networkCorrupt`),下次打开网络视频生效。+- 信号面板(ProPage 的“信号”卡)新增“网络”行:`缓冲 18.2 s · 下载 12.4 MB/s · 重连 0`(有丢包时追加 `丢包 n`,窄卡片换行);暂停缓冲或重连时极简页在画面下方显示药丸(含原因),状态灯显示“缓冲中”而不是“输出未达标”,状态栏沿用引擎的网络提示。重连成功与丢包汇总各弹一次提示。四语翻译进 `i18n/catalog.json`(共 38 条新增)。UI 变化检测把网络统计计入(位置冻结时仍会刷新)。## 4. 测试计划与验收(每类只测一次,不做压力测试)diff --git a/include/veyra/media/DemuxSession.h b/include/veyra/media/DemuxSession.hindex db70d0ce..f7bf3f33 100644--- a/include/veyra/media/DemuxSession.h+++ b/include/veyra/media/DemuxSession.h@@ -116,6 +116,7 @@ private:struct Queue {std::deque<Item> items;size_t bytes = 0;+ int64_t durationUs = 0; // content waiting in the queue: the sum of the packets' durations (never their timestamps)int64_t firstUs = INT64_MIN; // first content time since open / seekint64_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)@@ -209,8 +210,11 @@ private:// demux thread onlyint64_t offsetUs_ = 0; // live reconnect: keeps the timeline continuous- bool gateKeyframe_ = false; // live reconnect: wait for a video keyframe+ bool gateKeyframe_ = false; // live reconnect or restarted timeline: wait for a video keyframe+ int64_t lastAnchorNs_ = 0; // when the timeline was last re-anchored (late audio of the old one is dropped for a while)bool videoDiscontinuityPending_ = false, audioDiscontinuityPending_ = false;+ bool videoStarved_ = false; // the video consumer found its queue empty: reading more is always right+ int timestampJumpLogs_ = 0; // diagnostics: leaps in the stream's timestamps, logged a few times per sessionstd::vector<Item> pendingAudio_; // audio read before the live gate openedint64_t pendingAudioBytes_ = 0;int64_t reconnectBudgetMs_ = 60000;diff --git a/src/media/DemuxSession.cpp b/src/media/DemuxSession.cppindex c7396afa..ae68b309 100644--- a/src/media/DemuxSession.cpp+++ b/src/media/DemuxSession.cpp@@ -204,6 +204,7 @@ void DemuxSession::Queue::clear() {for (auto& item : items) av_packet_free(&item.packet);items.clear();bytes = 0;+ durationUs = 0;firstUs = lastEndUs = lastDtsUs = INT64_MIN;ended = false;dedupe = false;@@ -250,7 +251,7 @@ bool DemuxSession::openContext(std::wstring* error, bool initial) {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, "reconnect_delay_max", "2", 0);av_dict_set(&options, "seg_max_retry", "3", 0); // HLS segmentsav_dict_set(&options, "multiple_requests", "1", 0);} else {@@ -395,18 +396,27 @@ uint64_t DemuxSession::aheadBytesLocked() const {return settings_.level == NetworkBufferLevel::Auto && bandwidthLow_ ? plan_.growBytes : plan_.aheadBytes;}+// A packet's share of the buffered content. Estimated durations only: timestamps are not trusted here (see below).+static int64_t itemSpanUs(int64_t startUs, int64_t endUs) { return std::clamp<int64_t>(endUs - startUs, 0, 5000000); }+double DemuxSession::leadSecondsLocked() const {- // The player reports where playback is; offline readers (export, tools, tests) do not, and for- // them the video packet last taken is the position.+ // Seconds of content downloaded beyond the playback position: what waits in a queue (the packets' durations)+ // plus what the consumers already took but playback has not reached yet. Never lastEnd - position: a damaged+ // or restarted stream makes timestamps leap (field tests: an HTTP-TS stream that starts over jumps back by+ // minutes), and a lead computed from them stayed "full" while the queues were empty, so nothing was read again.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) {+ if (q.lastEndUs == INT64_MIN) { // nothing queued since open / seekbest = 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));+ double taken = 0;+ if (position >= 0) {+ const int64_t head = q.items.empty() ? q.lastEndUs : q.items.front().startUs;+ taken = std::clamp(double(head - position) / 1e6, 0.0, 5.0); // the two may sit on different timelines: bounded+ }+ best = std::min(best, double(q.durationUs) / 1e6 + taken);};consider(video_);if (audioIndex_.load() >= 0 && !audio_.ended) consider(audio_);@@ -487,7 +497,7 @@ void DemuxSession::updatePhaseLocked() {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();+ const bool capacity = (!videoStarved_ && 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");@@ -510,6 +520,7 @@ bool DemuxSession::flowBlockedLocked() const {if (endedLocked()) return true;const uint64_t queued = video_.bytes + audio_.bytes;if (queued >= aheadBytesLocked()) return true;+ if (videoStarved_) return false;return leadSecondsLocked() >= aheadSecondsLocked();}@@ -542,6 +553,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;+ video_.durationUs -= itemSpanUs(item.startUs, item.endUs);consumedUs_ = item.startUs;av_packet_move_ref(dst, item.packet);av_packet_free(&item.packet);@@ -551,6 +563,11 @@ DemuxSession::Pop DemuxSession::popVideo(AVPacket* dst, Meta& meta, int waitMs,return Pop::Packet;}if (video_.items.empty() && endedLocked()) return failed_ ? Pop::Failed : Pop::Eof;+ if (video_.items.empty() && !hold && !videoStarved_) {+ // Out of pictures: whatever the lead says, the producer has to read on.+ videoStarved_ = true;+ producerCv_.notify_one();+ }if (waitMs <= 0 || Clock::now() >= deadline) return Pop::Empty;consumerCv_.wait_until(lock, deadline);}@@ -566,6 +583,7 @@ DemuxSession::Pop DemuxSession::popAudio(AVPacket* dst, Meta& meta, int waitMs)Item item = std::move(audio_.items.front());audio_.items.pop_front();audio_.bytes -= item.bytes;+ audio_.durationUs -= itemSpanUs(item.startUs, item.endUs);av_packet_move_ref(dst, item.packet);av_packet_free(&item.packet);meta.discontinuity = item.discontinuity;@@ -875,7 +893,8 @@ void DemuxSession::flushPendingAudio(int64_t anchorUs) {log::info("net-session", std::format("live reconnect: {} audio packets waited for the keyframe, raw {}..{} ms", pendingAudio_.size(),pendingAudio_.front().startUs / 1000, pendingAudio_.back().startUs / 1000));for (auto& item : pendingAudio_) {- if (item.startUs + 5000 < anchorUs) {+ // Before the keyframe it is not needed; far after it, it belongs to another timeline (late audio of a restarted stream).+ if (item.startUs + 5000 < anchorUs || item.startUs > anchorUs + 5000000) {av_packet_free(&item.packet);continue;}@@ -920,6 +939,37 @@ void DemuxSession::onPacket(AVPacket* pkt) {}}Queue& queue = isVideo ? video_ : audio_;+ // ---- a timeline that leaps: a restarted stream, damaged stamps ----+ // Live streams are re-anchored like a reconnect: the next video keyframe continues the old timeline, so the+ // consumers (picture clock, audio) never see time run backwards or jump ahead; before this a restarted stream+ // froze the picture until its new timestamps caught up with the clock.+ if (!gateKeyframe_ && dtsUs != AV_NOPTS_VALUE && queue.lastDtsUs != INT64_MIN) {+ const int64_t step = dtsUs + offsetUs_ - queue.lastDtsUs;+ if (step < -1000000 || step > 3000000) {+ if (timestampJumpLogs_ < 24) {+ ++timestampJumpLogs_;+ log::warn("net-session", std::format("timestamp jump {} {:.3f}s -> {:.3f}s (step {:.3f}s) key={} corrupt={} size={} live={}", isVideo ? "video" : "audio",+ double(queue.lastDtsUs) / 1e6, double(dtsUs + offsetUs_) / 1e6, double(step) / 1e6, (pkt->flags & AV_PKT_FLAG_KEY) != 0,+ (pkt->flags & AV_PKT_FLAG_CORRUPT) != 0, pkt->size, live_));+ }+ if (live_) {+ // Video: only a keyframe starts a timeline; anything else with a leap is a damaged stamp, or the+ // start of a new stream that begins mid-GOP, and waits for the keyframe. Audio right after a+ // re-anchor: a packet of the old timeline that arrived late. (A leap in audio alone is a gap in the+ // sound, not a new timeline: it passes.)+ if (isVideo) {+ if (!(pkt->flags & AV_PKT_FLAG_KEY)) {+ av_packet_unref(pkt);+ return;+ }+ gateKeyframe_ = true;+ } else if (nowNs() - lastAnchorNs_ < 3000000000ll) {+ av_packet_unref(pkt);+ return;+ }+ }+ }+ }// ---- live reconnect: wait for a video keyframe, then continue the old timeline ----if (gateKeyframe_) {if (isVideo) {@@ -934,6 +984,7 @@ void DemuxSession::onPacket(AVPacket* pkt) {}offsetUs_ = previousEnd == INT64_MIN ? 0 : previousEnd - startUs;gateKeyframe_ = false;+ lastAnchorNs_ = nowNs();videoDiscontinuityPending_ = true;audioDiscontinuityPending_ = true;int64_t videoEnd, audioEnd;@@ -1011,7 +1062,10 @@ bool DemuxSession::pushLocked(Item&& item, bool video) {if (video) ++corruptPackets_;}if (queue.firstUs == INT64_MIN) queue.firstUs = item.startUs;- queue.lastEndUs = std::max(queue.lastEndUs, item.endUs);+ // The newest end, except that a timeline which starts over (a restarted stream) is followed, not out-waited.+ queue.lastEndUs = item.endUs < queue.lastEndUs - 2000000 ? item.endUs : std::max(queue.lastEndUs, item.endUs);+ queue.durationUs += itemSpanUs(item.startUs, item.endUs);+ if (video) videoStarved_ = false;if (item.dtsUs != AV_NOPTS_VALUE) queue.lastDtsUs = item.dtsUs;queue.bytes += item.bytes;noteArrivalLocked(item.bytes);@@ -1168,8 +1222,9 @@ bool DemuxSession::recover(int code, const char* why) {}closeContext();gateKeyframe_ = false;- // 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);+ // 1 s, then every 2 s: whenever the server comes back, the next try is at most 2 s away, which+ // leaves room for the keyframe wait and the start buffer inside 5 s of an outage's end.+ delayMs = std::min(delayMs * 2, 2000);}if (stop_.load() || (cancelled_ && cancelled_->load())) return false;fail(std::format(L"网络连接中断,已重试 {} 秒仍无法恢复", reconnectBudgetMs_ / 1000));diff --git a/tests/integration/NetworkBufferTests.cpp b/tests/integration/NetworkBufferTests.cppindex 7bf89a8e..ca3fc2c9 100644--- a/tests/integration/NetworkBufferTests.cpp+++ b/tests/integration/NetworkBufferTests.cpp@@ -31,6 +31,7 @@#include <vector>extern "C" {+#include <libavutil/log.h>#include <libavutil/frame.h>#include <libavutil/pixfmt.h>}@@ -247,7 +248,8 @@ int engineTest(const std::wstring& path, const std::filesystem::path& out, constHWND 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;+ auto playerOwner = std::make_unique<engine::EngineController>();+ auto& player = *playerOwner;player.setVolume(0, true);engine::PlayerOptions options;options.settings.nrRuntime = engine::NrRuntime::NvidiaOriginal;@@ -267,6 +269,16 @@ int engineTest(const std::wstring& path, const std::filesystem::path& out, constdouble 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;+ uint64_t maxBufferedBytes = 0, capBytes = 0;+ std::vector<std::string> messages; // distinct status messages with the numbers masked+ auto masked = [](const std::string& text) {+ std::string out;+ for (const char c : text) {+ if ((c >= '0' && c <= '9') || c == '.') { if (out.empty() || out.back() != '#') out += '#'; }+ else out += c;+ }+ return out;+ };bool failed = false, seekDone = false, pauseDone = false, resumed = false;std::wstring lastStatus, failure;double clockAtBufferingStart = -1, maxClockAdvanceWhileBuffering = 0;@@ -285,6 +297,14 @@ int engineTest(const std::wstring& path, const std::filesystem::path& out, constconst auto& n = s.network;const std::string state = n.active ? stateName(n.state) : "local";++seen[state];+ if (n.active) {+ maxBufferedBytes = std::max(maxBufferedBytes, n.bufferedBytes);+ capBytes = std::max(capBytes, n.capBytes);+ if (!n.message.empty()) {+ const auto m = masked(narrow(n.message));+ if (messages.size() < 12 && std::find(messages.begin(), messages.end(), m) == messages.end()) messages.push_back(m);+ }+ }maxFrames = std::max(maxFrames, s.metrics.flow.counters.realPresented);if (firstFrameAt < 0 && s.metrics.flow.counters.realPresented > 0) firstFrameAt = t;if (n.active) {@@ -301,7 +321,8 @@ int engineTest(const std::wstring& path, const std::filesystem::path& out, constif (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); }+ // The engine's lateness percentile needs a window: the first second of pictures is not judged.+ if (s.transport == engine::TransportState::Playing && firstFrameAt >= 0 && s.metrics.flow.counters.realPresented >= 30) { 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); }@@ -319,20 +340,28 @@ int engineTest(const std::wstring& path, const std::filesystem::path& out, constconst auto finalNet = s.network;player.stop();const double stopMs = std::chrono::duration<double, std::milli>(Clock::now() - stopAt).count();+ // stop() only posts the command; the engine thread (and the session under it) is joined here, so this is+ // how long a user stop / source switch really takes to get out of a blocked connect, read or wait.+ playerOwner.reset();+ const double teardownMs = 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\":{";+ << ",\"maxLateMs\":" << maxLate << ",\"maxLateP95Ms\":" << maxP95 << ",\"stopMs\":" << stopMs << ",\"teardownMs\":" << teardownMs+ << ",\"endState\":\"" << (finalNet.active ? stateName(finalNet.state) : "local") << "\",\"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)) << "\"}";+ << ",\"maxBufferedMiB\":" << maxBufferedBytes / 1048576.0 << ",\"capMiB\":" << capBytes / 1048576.0+ << ",\"message\":\"" << jsonEscape(narrow(finalNet.message)) << "\",\"messages\":[";+ for (size_t i = 0; i < messages.size(); ++i) json << (i ? "," : "") << "\"" << jsonEscape(messages[i]) << "\"";+ json << "]}";std::cout << "RESULT " << json.str() << std::endl;return failed ? 1 : 0;}@@ -425,6 +454,10 @@ int wmain(int argc, wchar_t** argv) {return 2;}const Options options = parseOptions(argc, argv, 4);+ // ffmpeglog=<quiet|warning|verbose|debug|trace>: FFmpeg's own messages to stderr (a diagnosis aid; they+ // include URLs, so runs against signed addresses must never use it).+ if (const auto level = str(options, "ffmpeglog"); !level.empty())+ av_log_set_level(level == "quiet" ? AV_LOG_QUIET : level == "verbose" ? AV_LOG_VERBOSE : level == "debug" ? AV_LOG_DEBUG : level == "trace" ? AV_LOG_TRACE : AV_LOG_WARNING);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);if (std::wstring_view(argv[1]) == L"scan") return scanTest(argv[2], argv[3], options);diff --git a/tests/network/__pycache__/netlib.cpython-311.pyc b/tests/network/__pycache__/netlib.cpython-311.pycdeleted file mode 100644index b70d5112..00000000Binary files a/tests/network/__pycache__/netlib.cpython-311.pyc and /dev/null differdiff --git a/tests/network/__pycache__/slow_server.cpython-311.pyc b/tests/network/__pycache__/slow_server.cpython-311.pycdeleted file mode 100644index da936fbb..00000000Binary files a/tests/network/__pycache__/slow_server.cpython-311.pyc and /dev/null differdiff --git a/tests/network/run_network_tests.py b/tests/network/run_network_tests.pynew file mode 100644index 00000000..d8bab316--- /dev/null+++ b/tests/network/run_network_tests.py@@ -0,0 +1,500 @@+#!/usr/bin/env python3+"""The #48 test matrix: one run per class, no stress tests (every run <= 300 s).++ py -3.11 -I run_network_tests.py [--only name,name] [--skip-big] [--out <dir>]++Each scenario starts slow_server.py (or mediamtx for RTSP) as a child process, runs+veyra_network_buffer_tests against it, evaluates the thresholds below and writes+<out>/<scenario>.json; the run ends with <out>/summary.json and summary.md.++Thresholds (from the task):+ * 1 % damaged TS packets never stop playback (decode-speed pass over the 10 min file,+ real-time pass on the live relay)+ * an 8 s outage recovers within 5 s after the server is back (VOD: first byte served by the+ reconnect; live: the picture moves again)+ * a VOD uses one connection for the whole session+ * the packet cache stays within its configured cap+ * audio / video deviation < 40 ms (95th percentile of the engine's lateness measure)+ * a server slower than the stream pauses to buffer, with the reason in the message, and never+ ends in an error; the clock does not advance while it waits+ * RTSP opens a single session; a local file behaves as before (session on/off identical)+"""+import argparse+import json+import socket+import subprocess+import sys+import time+import urllib.request+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from netlib import APP, BASE, FFMPEG, MEDIA, TASK, Server, run_exe # noqa: E402++REASON = '服务器速度' # the bandwidth sentence of the paused-buffering message+RESULTS = {}+++def requests_of(server):+ return server.stats().get('requests', [])+++def check(checks, name, ok, detail=''):+ checks.append({'name': name, 'ok': bool(ok), 'detail': detail})+ return ok+++def finish(name, out, checks, data):+ passed = all(c['ok'] for c in checks)+ record = {'scenario': name, 'pass': passed, 'checks': checks, 'data': data}+ (out / f'{name}.json').write_text(json.dumps(record, ensure_ascii=False, indent=1), encoding='utf-8')+ RESULTS[name] = record+ print(('PASS ' if passed else 'FAIL ') + name, flush=True)+ for c in checks:+ print(' ' + ('ok ' if c['ok'] else 'FAIL ') + c['name'] + (f" [{c['detail']}]" if c['detail'] else ''), flush=True)+ return passed+++def server_stats(server):+ s = server.stats()+ return {k: v for k, v in s.items() if k != 'requests'}+++def timeline(run_dir):+ rows = []+ path = Path(run_dir) / 'timeline.csv'+ if not path.exists():+ return rows+ lines = path.read_text(encoding='utf-8', errors='replace').splitlines()+ head = lines[0].split(',')+ for line in lines[1:]:+ parts = line.split(',', len(head) - 1)+ if len(parts) == len(head):+ rows.append(dict(zip(head, parts)))+ return rows+++def standstills(rows, minimum=1.0):+ """[(start, end)] where the playback position stood still for at least `minimum` seconds."""+ out, start, last = [], None, None+ for r in rows:+ t, p = float(r['t']), float(r['position'])+ if last is None or p != last:+ if start is not None and t - start >= minimum:+ out.append((start, t))+ start, last = t, p+ return out+++# ----------------------------------------------------------------------------------------- scenarios+def selftest(out, a):+ checks = []+ p = subprocess.run([str(APP / 'veyra_network_buffer_tests.exe'), 'selftest'], cwd=str(APP), capture_output=True, text=True, timeout=60)+ check(checks, 'selftest exit code 0', p.returncode == 0, p.stdout.strip()[-200:] or p.stderr.strip()[-200:])+ return finish('selftest', out, checks, {'stdout': p.stdout[-600:]})+++def local_ab(out, a):+ checks, data = [], {}+ for name in ('av-720p30-60s.mp4', 'av-720p30-60s.mkv'):+ f = MEDIA / name+ rc1, direct, _ = run_exe('source', f, out / f'ab-{name}-direct', dict(hash=1, frames=900))+ rc2, session, _ = run_exe('source', f, out / f'ab-{name}-session', dict(hash=1, frames=900), env=dict(VEYRA_TEST_FORCE_DEMUX_SESSION=1))+ data[name] = {'direct': direct, 'session': session}+ check(checks, f'{name}: direct run ok', rc1 == 0 and direct and not direct['session'], f'rc={rc1}')+ check(checks, f'{name}: session run ok', rc2 == 0 and session and session['session'], f'rc={rc2}')+ if direct and session:+ check(checks, f'{name}: identical frames', direct['frames'] == session['frames'] == 900, f"{direct['frames']} vs {session['frames']}")+ check(checks, f'{name}: identical picture hash', direct['hash'] == session['hash'], f"{direct['hash']} vs {session['hash']}")+ check(checks, f'{name}: monotonic pts', direct['nonMonotonic'] == 0 and session['nonMonotonic'] == 0)+ return finish('local-ab', out, checks, data)+++def local_engine(out, a):+ checks = []+ rc, res, sec = run_exe('engine', MEDIA / 'av-720p30-60s.mp4', out / 'local-engine', dict(seconds=12))+ check(checks, 'plays', rc == 0 and res and not res['failed'], f'rc={rc}')+ if res:+ check(checks, 'no network session for a local file', 'local' in res['states'] and 'playing' not in res['states'] and 'buffering' not in res['states'], str(res['states']))+ check(checks, 'frames presented', res['realPresented'] >= 250, str(res['realPresented']))+ check(checks, 'A/V lateness p95 < 40 ms', res['maxLateP95Ms'] < 40, f"{res['maxLateP95Ms']:.1f}")+ return finish('local-engine', out, checks, {'result': res})+++def vod_fast(out, a):+ checks, data = [], {}+ with Server(out / 'vod-fast-srv') as s:+ rc, res, sec = run_exe('engine', s.url('av-720p30-60s.mp4'), out / 'vod-fast', dict(seconds=22))+ st = server_stats(s)+ data.update(result=res, server=st)+ check(checks, 'plays without failure', rc == 0 and res and not res['failed'], f'rc={rc}')+ if res:+ check(checks, 'first picture within 6 s', 0 <= res['firstFrameSeconds'] <= 6, f"{res['firstFrameSeconds']:.2f}")+ check(checks, 'one connection for the session', st['connections'] == 1 and st['requestCount'] == 1 and st['maxInFlight'] == 1,+ f"connections={st['connections']} requests={st['requestCount']}")+ check(checks, 'A/V lateness p95 < 40 ms', res['maxLateP95Ms'] < 40, f"{res['maxLateP95Ms']:.1f}")+ check(checks, 'cache within its cap', res['maxBufferedMiB'] <= res['capMiB'] * 1.05 + 8, f"{res['maxBufferedMiB']:.1f} of {res['capMiB']:.0f} MiB")+ check(checks, 'no buffering stall on a fast server', res['bufferingSeconds'] < 0.5, f"{res['bufferingSeconds']:.2f}")+ return finish('vod-fast', out, checks, data)+++def vod_slow(out, a):+ checks, data = [], {}+ with Server(out / 'vod-slow-srv', rate_mbps=0.2) as s:+ rc, res, sec = run_exe('engine', s.url('av-720p30-60s.mp4'), out / 'vod-slow', dict(seconds=45))+ st = server_stats(s)+ data.update(result=res, server=st)+ check(checks, 'never ends in an error', rc == 0 and res and not res['failed'], f'rc={rc}')+ if res:+ check(checks, 'pauses to buffer', res['bufferingSeconds'] + res['prebufferSeconds'] > 5, f"buffering={res['bufferingSeconds']:.1f}s prebuffer={res['prebufferSeconds']:.1f}s")+ check(checks, 'reason is given', any(REASON in m for m in res['messages']), str(res['messages'][:4]))+ check(checks, 'flagged as server slower than the stream', res['bandwidthLow'], f"server={res['serverMBps']:.2f} bitrate={res['bitrateMBps']:.2f} MB/s")+ check(checks, 'clock stands still while waiting', res['maxClockAdvanceWhileBuffering'] < 0.1, f"{res['maxClockAdvanceWhileBuffering']:.3f} s")+ check(checks, 'one connection for the session', st['connections'] == 1 and st['maxInFlight'] == 1, f"connections={st['connections']}")+ check(checks, 'cache within its cap', res['maxBufferedMiB'] <= res['capMiB'] * 1.05 + 8, f"{res['maxBufferedMiB']:.1f} of {res['capMiB']:.0f} MiB")+ return finish('vod-slow', out, checks, data)+++def vod_big_4k(out, a):+ checks, data = [], {}+ if a.skip_big or not (MEDIA / 'big-4k-av.mkv').exists():+ checks.append({'name': 'skipped', 'ok': True, 'detail': 'no big file or --skip-big'})+ return finish('vod-big-4k-mkv', out, checks, {})+ with Server(out / 'vod-big-srv', rate_mbps=6.0) as s:+ rc, res, sec = run_exe('engine', s.url('big-4k-av.mkv'), out / 'vod-big', dict(seconds=100))+ st = server_stats(s)+ data.update(result=res, server=st)+ check(checks, 'never ends in an error', rc == 0 and res and not res['failed'], f'rc={rc}')+ if res:+ check(checks, 'flagged as server slower than the stream', res['bandwidthLow'], f"server={res['serverMBps']:.2f} bitrate={res['bitrateMBps']:.2f} MB/s")+ check(checks, 'reason is given', any(REASON in m for m in res['messages']), str(res['messages'][:4]))+ check(checks, 'pauses to buffer', res['bufferingSeconds'] + res['prebufferSeconds'] > 5, f"{res['bufferingSeconds'] + res['prebufferSeconds']:.1f} s")+ check(checks, 'plays between the pauses', res['realPresented'] > 30, str(res['realPresented']))+ check(checks, 'clock stands still while waiting', res['maxClockAdvanceWhileBuffering'] < 0.1, f"{res['maxClockAdvanceWhileBuffering']:.3f} s")+ # a stop interrupts FFmpeg inside a Matroska block, its resync then starts one more TCP connect that+ # is cancelled before it sends anything (seen in FFmpeg's own log): not a second reader+ check(checks, 'one connection for the session', st['requestCount'] == 1 and st['maxInFlight'] == 1 and st['connections'] <= 2,+ f"requests={st['requestCount']} in flight<={st['maxInFlight']} tcp connections={st['connections']} (the 2nd is the stop-time resync attempt)")+ check(checks, 'cache within its cap (auto: <= 1 GiB when the server is slow)', res['maxBufferedMiB'] <= max(res['capMiB'], 1) * 1.05 + 16 and res['maxBufferedMiB'] <= 1100,+ f"{res['maxBufferedMiB']:.0f} of {res['capMiB']:.0f} MiB")+ return finish('vod-big-4k-mkv', out, checks, data)+++def vod_stall(out, a):+ checks, data = [], {}+ # 0.6 MB/s is above the 0.4 MB/s stream, so the small window fills; the 10 s stall then drains it.+ with Server(out / 'vod-stall-srv', rate_mbps=0.6, stall_at='6', stall_seconds=10) as s:+ rc, res, sec = run_exe('engine', s.url('av-720p30-60s.mp4'), out / 'vod-stall', dict(seconds=50, level='small'))+ st = server_stats(s)+ data.update(result=res, server=st)+ check(checks, 'never ends in an error', rc == 0 and res and not res['failed'], f'rc={rc}')+ if res:+ check(checks, 'paused to buffer during the stall', res['stalls'] >= 1 and res['bufferingSeconds'] > 3, f"stalls={res['stalls']} buffering={res['bufferingSeconds']:.1f}s")+ check(checks, 'playing again afterwards', res['states'].get('playing', 0) > 100 and res['finalPosition'] > 10, f"position={res['finalPosition']:.1f}")+ check(checks, 'clock stands still while waiting', res['maxClockAdvanceWhileBuffering'] < 0.1, f"{res['maxClockAdvanceWhileBuffering']:.3f} s")+ check(checks, 'one connection (a stall is not a reconnect)', st['connections'] == 1, f"connections={st['connections']} reconnects={res['reconnects']}")+ return finish('vod-stall', out, checks, data)+++def vod_outage(out, a):+ checks, data = [], {}+ f = MEDIA / 'av-720p30-60s.mp4'+ rc0, base, _ = run_exe('source', f, out / 'vod-outage-base', dict(hash=1))+ with Server(out / 'vod-outage-srv', rate_mbps=1.5, outage_at=4, outage_seconds=8) as s:+ rc, res, sec = run_exe('source', s.url('av-720p30-60s.mp4'), out / 'vod-outage', dict(hash=1, level='small'))+ st = server_stats(s)+ reqs = requests_of(s)+ outage_end = 4 + 8+ served = [r for r in reqs if r['t'] >= outage_end - 0.05 and r['bytes'] > 0]+ delay = (served[0]['t'] - outage_end) if served else None+ data.update(baseline=base, result=res, server=st, firstServedAfterOutage=served[0] if served else None, recoveryDelaySeconds=delay)+ check(checks, 'plays to the end', rc == 0 and res and res['status'] == 'eos', f"rc={rc}")+ if res and base:+ check(checks, 'reconnected', res['reconnects'] >= 1, f"reconnects={res['reconnects']}")+ check(checks, 'recovery within 5 s after the server is back', delay is not None and delay <= 5, f'{delay}')+ check(checks, 'frames identical to the undisturbed run', res['frames'] == base['frames'] and res['hash'] == base['hash'],+ f"{res['frames']} vs {base['frames']} frames, hash {'equal' if res['hash'] == base['hash'] else 'DIFFERENT'}")+ check(checks, 'no timeline break', res['nonMonotonic'] == 0 and res['discontinuities'] == 0, f"nonMonotonic={res['nonMonotonic']} discontinuities={res['discontinuities']}")+ return finish('vod-outage-8s', out, checks, data)+++def vod_reconnect_off(out, a):+ checks, data = [], {}+ with Server(out / 'vod-noreconnect-srv', rate_mbps=1.5, outage_at=3, outage_seconds=8) as s:+ rc, res, sec = run_exe('engine', s.url('av-720p30-60s.mp4'), out / 'vod-noreconnect', dict(seconds=40, level='small', reconnect=0))+ data.update(result=res)+ check(checks, 'stops with a reason instead of freezing', res is not None and res['failed'], f"rc={rc}")+ if res:+ check(checks, 'the reason says auto-reconnect is off', '自动重连已关闭' in res['failure'], res['failure'])+ check(checks, 'no reconnect attempted', res['reconnects'] == 0 and res['connections'] == 1, f"reconnects={res['reconnects']} connections={res['connections']}")+ return finish('vod-reconnect-off', out, checks, data)+++def live_outage(out, a):+ checks, data = [], {}+ with Server(out / 'live-outage-srv', live=['live.ts=live-src.ts'], outage_at=10, outage_seconds=8) as s:+ rc, res, sec = run_exe('engine', s.url('live.ts'), out / 'live-outage', dict(seconds=45))+ st = server_stats(s)+ reqs = requests_of(s)+ rows = timeline(out / 'live-outage')+ first = min((r['t'] for r in reqs), default=0)+ outage_end_engine = (10 + 8) - first + 0.3+ stands = [x for x in standstills(rows, 1.5) if x[1] > outage_end_engine - 2]+ resume = stands[0][1] - outage_end_engine if stands else None+ data.update(result=res, server=st, standstills=stands, recoverySeconds=resume)+ check(checks, 'no failure', rc == 0 and res and not res['failed'], f'rc={rc}')+ if res:+ check(checks, 'reconnected', res['reconnects'] >= 1, f"reconnects={res['reconnects']}")+ check(checks, 'picture moves again within 5 s after the server is back', resume is not None and resume <= 5, f'{resume}')+ check(checks, 'A/V lateness p95 < 40 ms', res['maxLateP95Ms'] < 40, f"{res['maxLateP95Ms']:.1f}")+ check(checks, 'plays on afterwards', res['finalPosition'] > 25, f"position={res['finalPosition']:.1f}")+ return finish('live-outage-8s', out, checks, data)+++def _ts_decode(out, name, flags, what):+ checks, data = [], {}+ with Server(out / f'{name}-srv', **flags) as s:+ rc, res, sec = run_exe('source', s.url('av-720p30-10min.ts'), out / name, dict(tolerant=1), timeout=290)+ st = server_stats(s)+ data.update(result=res, server=st, wallSeconds=sec)+ check(checks, f'plays the whole 10 minutes at decode speed ({what})', rc == 0 and res and res['status'] == 'eos' and res['lastPts'] > 585,+ f"rc={rc} lastPts={res and res['lastPts']:.1f} wall={sec:.0f}s")+ if res:+ check(checks, 'damage was really injected and noticed', res['corruptPackets'] > 100, f"packets={res['corruptPackets']} frames={res['corruptFrames']}")+ check(checks, 'about 18000 pictures (1 % damage may drop a few)', 16500 <= res['frames'] <= 18100, str(res['frames']))+ check(checks, 'no error, no reconnect', res['status'] != 'error' and not res['error'] and res['reconnects'] == 0, f"{res['error']} reconnects={res['reconnects']}")+ return finish(name, out, checks, data)+++def ts_loss_decode(out, a):+ # bit errors in 1 % of the packets of the file, served as an ordinary seekable VOD+ return _ts_decode(out, 'ts-flip-1pct-10min-decode', dict(ts_flip=0.01), '1 % damaged packets, VOD file')+++def ts_drop_decode(out, a):+ """1 % of the packets removed (continuity errors), served as a live-style stream with no length. At the end of the+ 10 minutes the server closes and the stream starts over (its timestamps jump back by 600 s): 20000 pictures take+ the run 2000 pictures into the second pass, so a stall at the restart would show."""+ checks, data = [], {}+ name = 'ts-drop-1pct-10min-decode'+ with Server(out / f'{name}-srv', ts_drop_file=0.01) as s:+ rc, res, sec = run_exe('source', s.url('av-720p30-10min.ts'), out / name, dict(tolerant=1, frames=20000, seconds=250, ffmpeglog='quiet'), timeout=290)+ st = server_stats(s)+ data.update(result=res, server=st, wallSeconds=sec)+ check(checks, 'plays 20000 pictures (the 10 minutes and the restarted stream behind them) without stopping', rc == 0 and res and res['status'] == 'limit' and res['frames'] == 20000,+ f"rc={rc} frames={res and res['frames']} status={res and res['status']} wall={sec:.0f}s")+ if res:+ check(checks, 'damage was really injected and noticed', res['corruptPackets'] > 100, f"packets={res['corruptPackets']} frames={res['corruptFrames']}")+ check(checks, 'the restart is absorbed: one continuous timeline, flagged once', res['nonMonotonic'] == 0 and res['discontinuities'] == 1 and res['lastPts'] > 650,+ f"lastPts={res['lastPts']:.1f} nonMonotonic={res['nonMonotonic']} discontinuities={res['discontinuities']}")+ check(checks, 'no gap in the pictures longer than 1 s', res['maxFrameGapMs'] < 1000, f"{res['maxFrameGapMs']:.0f} ms")+ check(checks, 'no error', res['status'] != 'error' and not res['error'], res['error'])+ return finish(name, out, checks, data)+++def live_restart(out, a):+ """A live stream that starts over (timestamps jump back) every 20 s: the picture and the sound go on."""+ checks, data = [], {}+ with Server(out / 'live-restart-srv', ts_drop_file=0.00001) as s:+ rc, res, sec = run_exe('engine', s.url('live-src.ts'), out / 'live-restart', dict(seconds=65, ffmpeglog='quiet'), timeout=200)+ st = server_stats(s)+ rows = timeline(out / 'live-restart')+ data.update(result=res, server=st)+ check(checks, 'no failure', rc == 0 and res and not res['failed'], f'rc={rc}')+ if res:+ stands = [x for x in standstills(rows, 1.0) if x[0] >= res['firstFrameSeconds'] - 0.1]+ worst = max((b - a_ for a_, b in stands), default=0.0)+ data['standstillsAfterFirstPicture'] = stands+ check(checks, 'the stream restarted (new connection per pass)', st['connections'] >= 3, f"connections={st['connections']}")+ check(checks, 'one continuous timeline across the restarts', res['finalPosition'] > 60, f"position={res['finalPosition']:.1f}")+ check(checks, 'picture never stands still for 1.5 s', worst < 1.5, f'worst {worst:.2f} s')+ check(checks, 'no buffering pause', res['bufferingSeconds'] < 1.0 and res['stalls'] == 0, f"buffering={res['bufferingSeconds']:.2f}s stalls={res['stalls']}")+ check(checks, 'A/V lateness p95 < 40 ms', res['maxLateP95Ms'] < 40, f"{res['maxLateP95Ms']:.1f}")+ return finish('live-restart', out, checks, data)+++def ts_loss_realtime(out, a):+ checks, data = [], {}+ with Server(out / 'ts-loss-rt-srv', live=['live.ts=live-src.ts'], ts_drop=0.01) as s:+ rc, res, sec = run_exe('engine', s.url('live.ts'), out / 'ts-loss-rt', dict(seconds=200), timeout=290)+ st = server_stats(s)+ data.update(result=res, server=st)+ check(checks, 'never stops (200 s real time)', rc == 0 and res and not res['failed'] and res['finalPosition'] > 150, f"rc={rc} position={res and res['finalPosition']:.1f}")+ if res:+ check(checks, 'damage noticed', res['corruptPackets'] > 50, f"packets={res['corruptPackets']}")+ # the opening (first picture) is not a freeze: only standstills after the first picture count+ rows = timeline(out / 'ts-loss-rt')+ stands = [x for x in standstills(rows, 1.0) if x[0] >= res['firstFrameSeconds'] - 0.1]+ worst = max((b - a for a, b in stands), default=0.0)+ data['standstillsAfterFirstPicture'] = stands+ check(checks, 'picture never stands still for 1.5 s after the first picture', worst < 1.5, f"worst {worst:.2f} s, first picture at {res['firstFrameSeconds']:.2f} s")+ check(checks, 'A/V lateness p95 < 40 ms', res['maxLateP95Ms'] < 40, f"{res['maxLateP95Ms']:.1f}")+ check(checks, 'no reconnect needed for 1 % loss', res['reconnects'] == 0, f"{res['reconnects']}")+ return finish('ts-loss-1pct-realtime', out, checks, data)+++def stop_latency(out, a):+ """A user stop / source switch must get out of a blocked connect, read or wait at once."""+ checks, data = [], {}+ cases = (+ ('reconnecting', dict(live=['live.ts=live-src.ts'], outage_at=6, outage_seconds=40), 'live.ts', dict(seconds=14), ('reconnecting', 'buffering')),+ ('buffering', dict(rate_mbps=0.2), 'av-720p30-60s.mp4', dict(seconds=14), ('buffering', 'prebuffering')),+ ('opening', dict(stall_at='0', stall_seconds=60), 'av-720p30-60s.mp4', dict(seconds=8), ('prebuffering', 'idle', 'local')),+ )+ for name, flags, target, opts, states in cases:+ with Server(out / f'stop-{name}-srv', **flags) as s:+ rc, res, sec = run_exe('engine', s.url(target), out / f'stop-{name}', opts, timeout=120)+ data[name] = res+ if not res:+ check(checks, f'{name}: ran', False, f'rc={rc}')+ continue+ check(checks, f'{name}: stopped while {res["endState"]}', res['endState'] in states, res['endState'])+ check(checks, f'{name}: engine torn down in < 1.5 s', res['teardownMs'] < 1500, f"{res['teardownMs']:.0f} ms")+ return finish('stop-latency', out, checks, data)+++def hls(out, a):+ checks, data = [], {}+ for which, path in (('vod', 'hls/vod/index.m3u8'), ('multi', 'hls/multi/master.m3u8')):+ if not (MEDIA / path).exists():+ continue+ with Server(out / f'hls-{which}-srv') as s:+ rc, res, sec = run_exe('source', s.url(path), out / f'hls-{which}', dict(seconds=60, frames=600))+ st = server_stats(s)+ paths = [r['path'] for r in requests_of(s)]+ segments = [p.rsplit('/', 1)[-1] for p in paths if p.endswith('.ts')]+ perVariant = {}+ for name in segments:+ perVariant[name.split('_')[0]] = perVariant.get(name.split('_')[0], 0) + 1+ data[which] = {'result': res, 'server': st, 'segmentsPerVariant': perVariant}+ check(checks, f'hls {which}: plays', rc == 0 and res and res['frames'] >= 300, f"rc={rc} frames={res and res['frames']}")+ if which == 'multi':+ # FFmpeg's HLS demuxer opens the first segments of every variant while reading the header; after that+ # only the best variant (v2) is downloaded because the session drops the other streams+ best = max(perVariant, key=perVariant.get) if perVariant else None+ check(checks, 'hls multi: the best variant carries the stream, the others stop after the header', best == 'v2' and perVariant.get('v2', 0) >= 8+ and all(n <= 2 for v, n in perVariant.items() if v != 'v2'), f'segments per variant {perVariant}')+ return finish('hls', out, checks, data)+++def rtsp(out, a):+ checks, data = [], {}+ mtx = BASE / 'tmp/issues41-45-20261016/mediamtx/mediamtx.exe'+ if not mtx.exists():+ checks.append({'name': 'skipped', 'ok': True, 'detail': 'mediamtx not found'})+ return finish('rtsp', out, checks, {})+ work = out / 'rtsp-mtx'+ work.mkdir(parents=True, exist_ok=True)++ def port():+ with socket.socket() as c:+ c.bind(('127.0.0.1', 0))+ return c.getsockname()[1]+ rport, aport = port(), port()+ cfg = work / 'mediamtx.yml'+ cfg.write_text(f'logLevel: info\nrtsp: true\nrtspAddress: 127.0.0.1:{rport}\nrtspTransports: [tcp]\nrtmp: false\nhls: false\n'+ f'webrtc: false\nsrt: false\napi: true\napiAddress: 127.0.0.1:{aport}\nplayback: false\npaths:\n test:\n', encoding='utf-8')+ procs = []+ try:+ procs.append(subprocess.Popen([str(mtx), str(cfg)], cwd=str(work), stdout=(work / 'mtx.log').open('wb'), stderr=subprocess.STDOUT, creationflags=0x08000000))+ time.sleep(0.8)+ procs.append(subprocess.Popen([str(FFMPEG), '-nostdin', '-hide_banner', '-loglevel', 'error', '-re', '-f', 'lavfi', '-i', 'testsrc2=size=1280x720:rate=30',+ '-re', '-f', 'lavfi', '-i', 'sine=frequency=1000:sample_rate=48000', '-c:v', 'libx264', '-preset', 'veryfast', '-g', '60',+ '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-f', 'rtsp', '-rtsp_transport', 'tcp', f'rtsp://127.0.0.1:{rport}/test'],+ cwd=str(work), stdout=(work / 'push.log').open('wb'), stderr=subprocess.STDOUT, creationflags=0x08000000))+ time.sleep(2.0)+ rc, res, sec = run_exe('engine', f'rtsp://127.0.0.1:{rport}/test', out / 'rtsp', dict(seconds=22))+ sessions = []+ for _ in range(3):+ try:+ body = json.loads(urllib.request.urlopen(f'http://127.0.0.1:{aport}/v3/rtspsessions/list', timeout=3).read())+ sessions = body.get('items', [])+ break+ except Exception:+ time.sleep(0.3)+ log = (work / 'mtx.log').read_text(errors='replace')+ opened = log.count('is reading from path')+ data.update(result=res, mediamtxReaders=opened, sessionsWhileRunning=len(sessions))+ finally:+ for p in procs:+ if p.poll() is None:+ p.terminate()+ check(checks, 'plays without failure', rc == 0 and res and not res['failed'], f'rc={rc}')+ check(checks, 'exactly one RTSP reader session opened (mediamtx log)', data.get('mediamtxReaders') == 1, f"readers={data.get('mediamtxReaders')}")+ if res:+ check(checks, 'picture moves', res['realPresented'] > 200, str(res['realPresented']))+ check(checks, 'A/V lateness p95 < 40 ms', res['maxLateP95Ms'] < 40, f"{res['maxLateP95Ms']:.1f}")+ return finish('rtsp', out, checks, data)+++def nas_slow(out, a):+ checks, data = [], {}+ env = dict(VEYRA_TEST_FORCE_DEMUX_SESSION=1, VEYRA_TEST_SLOW_IO=0.2)+ rc, res, sec = run_exe('engine', MEDIA / 'av-720p30-60s.mp4', out / 'nas-slow', dict(seconds=40), env=env)+ data.update(result=res)+ check(checks, 'never ends in an error', rc == 0 and res and not res['failed'], f'rc={rc}')+ if res:+ check(checks, 'goes through the shared session', res['connections'] == 1 and res['states'].get('buffering', 0) + res['states'].get('prebuffering', 0) > 0, str(res['states']))+ check(checks, 'pauses to buffer with the reason', res['bufferingSeconds'] + res['prebufferSeconds'] > 5 and any(REASON in m for m in res['messages']),+ f"buffering={res['bufferingSeconds']:.1f}s {res['messages'][:2]}")+ check(checks, 'clock stands still while waiting', res['maxClockAdvanceWhileBuffering'] < 0.1, f"{res['maxClockAdvanceWhileBuffering']:.3f} s")+ return finish('nas-slow-io', out, checks, data)+++def subtitle_scan(out, a):+ checks, data = [], {}+ f = MEDIA / 'av-720p30-60s-subs.mkv'+ paced_env = dict(VEYRA_TEST_FORCE_REMOTE_PATH=1, VEYRA_TEST_SLOW_IO=4)+ rc1, paced, _ = run_exe('scan', f, out / 'scan-paced', dict(closedSeconds=3), env=paced_env)+ rc2, toggle, _ = run_exe('scan', f, out / 'scan-toggle', dict(closedSeconds=1, toggle=1, closeAfter=1.0, closedAgainSeconds=2.0), env=paced_env)+ rc3, local, _ = run_exe('scan', f, out / 'scan-local', dict(closedSeconds=0.5))+ data.update(paced=paced, toggle=toggle, local=local)+ if paced:+ check(checks, 'server file: nothing read or published while playback is not buffered', paced['serverFile'] and paced['bytesWhileClosed'] == 0 and paced['publishedWhileClosed'] == 0)+ check(checks, 'server file: scan finishes once the gate opens', rc1 == 0 and paced['complete'] and paced['tracks'] == 2 and paced['cues'] == [60, 60], str(paced['cues']))+ check(checks, 'server file: paced (4 MB/s cap)', paced['rateMBps'] <= 4.4 and paced['scanSeconds'] >= 4.5, f"{paced['rateMBps']:.2f} MB/s over {paced['scanSeconds']:.1f} s")+ if toggle:+ check(checks, 'server file: reading stops while the gate is closed', toggle['complete'] and toggle['bytesWhileClosedAgain'] == 0, f"{toggle['bytesWhileClosedAgain']} bytes")+ check(checks, 'server file: ... and resumes to the end', toggle['bytesRead'] == toggle['fileBytes'] and toggle['cues'] == [60, 60])+ if local:+ check(checks, 'local file: scanned immediately as before', rc3 == 0 and not local['serverFile'] and local['complete'] and local['bytesRead'] == 0 and local['cues'] == [60, 60])+ return finish('subtitle-scan-nas', out, checks, data)+++ORDER = [('selftest', selftest), ('local-ab', local_ab), ('local-engine', local_engine), ('vod-fast', vod_fast), ('vod-slow', vod_slow),+ ('vod-big-4k-mkv', vod_big_4k), ('vod-stall', vod_stall), ('vod-outage-8s', vod_outage), ('vod-reconnect-off', vod_reconnect_off),+ ('live-outage-8s', live_outage), ('stop-latency', stop_latency), ('ts-flip-1pct-10min-decode', ts_loss_decode), ('ts-drop-1pct-10min-decode', ts_drop_decode), ('ts-loss-1pct-realtime', ts_loss_realtime), ('live-restart', live_restart),+ ('hls', hls), ('rtsp', rtsp), ('nas-slow-io', nas_slow), ('subtitle-scan-nas', subtitle_scan)]+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument('--only', default='')+ ap.add_argument('--skip-big', action='store_true')+ ap.add_argument('--out', default='')+ a = ap.parse_args()+ out = Path(a.out) if a.out else BASE / 'tests' / TASK / 'results' / time.strftime('%Y%m%d-%H%M%S')+ out.mkdir(parents=True, exist_ok=True)+ only = {x for x in a.only.split(',') if x}+ for name, fn in ORDER:+ if only and name not in only:+ continue+ started = time.time()+ try:+ fn(out, a)+ except Exception as exc: # a broken scenario is a failure, not a crash of the matrix+ RESULTS[name] = {'scenario': name, 'pass': False, 'checks': [{'name': 'ran', 'ok': False, 'detail': repr(exc)}], 'data': {}}+ print('FAIL ' + name + ' ' + repr(exc), flush=True)+ RESULTS[name]['seconds'] = round(time.time() - started, 1)+ summary = {'out': str(out), 'passed': [n for n, r in RESULTS.items() if r['pass']], 'failed': [n for n, r in RESULTS.items() if not r['pass']]}+ (out / 'summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=1), encoding='utf-8')+ lines = ['| scenario | result | seconds |', '|---|---|---|']+ for n, r in RESULTS.items():+ lines.append(f"| {n} | {'PASS' if r['pass'] else 'FAIL'} | {r.get('seconds', '')} |")+ (out / 'summary.md').write_text('\n'.join(lines) + '\n', encoding='utf-8')+ print('summary:', json.dumps(summary, ensure_ascii=False))+ return 0 if not summary['failed'] else 1+++if __name__ == '__main__':+ sys.exit(main())diff --git a/tests/network/slow_server.py b/tests/network/slow_server.pyindex 6b882457..c3349468 100644--- a/tests/network/slow_server.py+++ b/tests/network/slow_server.py@@ -14,6 +14,8 @@ It stands in for the slow / unreliable servers the user does not have:* --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);+ * --ts-drop-file RATIO a *.ts file is served like a live stream (200, no Content-Length, no Range, closes at+ the end) from its start with RATIO of its TS packets removed, as fast as the link allows;* /__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.@@ -199,10 +201,16 @@ class Handler(http.server.BaseHTTPRequestHandler):def log_message(self, fmt, *a):pass+ def send_response(self, code, message=None):+ log(dict(event='response', conn=getattr(self, 'conn_id', 0), code=code, path=self.path, range=self.headers.get('Range')))+ super().send_response(code, message)+def setup(self):super().setup()with STATS.lock:STATS.connections += 1+ self.conn_id = STATS.connections+ log(dict(event='connection-open', conn=self.conn_id, peer=self.client_address[1]))with ACTIVE_LOCK:ACTIVE.add(self.connection)if SHAPER.in_outage():@@ -211,6 +219,7 @@ class Handler(http.server.BaseHTTPRequestHandler):self.reset()def finish(self):+ log(dict(event='connection-close', conn=getattr(self, 'conn_id', 0)))with ACTIVE_LOCK:ACTIVE.discard(self.connection)try:@@ -250,6 +259,8 @@ class Handler(http.server.BaseHTTPRequestHandler):self.send_header('Content-Length', '0')self.end_headers()return+ if ARGS.ts_drop_file > 0 and full.lower().endswith('.ts') and not head:+ return self.serve_lossy_file(path, full)size = os.path.getsize(full)start, end, status = 0, size - 1, 200rng = self.headers.get('Range')@@ -314,6 +325,37 @@ class Handler(http.server.BaseHTTPRequestHandler):self.close_connection = TrueSTATS.end(rec, result)+ def serve_lossy_file(self, path, full):+ """The file as a live-style stream with packet loss (no length, no ranges), at link speed."""+ 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(path, None, self.client_address[1])+ rnd = random.Random(ARGS.seed + rec['id'])+ result = 'done'+ try:+ with open(full, 'rb') as f:+ while True:+ chunk = f.read(CHUNK - CHUNK % TS)+ if not chunk:+ break+ kept = bytearray()+ for off in range(0, len(chunk) - TS + 1, TS):+ if rnd.random() >= ARGS.ts_drop_file:+ kept += chunk[off:off + TS]+ if not SHAPER.wait(len(kept), STOP):+ result = 'reset'+ self.reset()+ break+ self.wfile.write(bytes(kept))+ STATS.add(rec, len(kept))+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):+ result = 'client-closed'+ STATS.end(rec, result)+# ---- live MPEG-TS relay -------------------------------------------------------------def serve_live(self, name):feed = LIVE[name]@@ -442,6 +484,7 @@ def main():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('--ts-drop-file', 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)