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++
Finish #48: HLS best variant, live reconnect tuning, interlaced damage tolerance, verified matrix
Veyra Goal Agent5d9e57f8baf5
diff --git a/docs/NETWORK_BUFFER_48_PLAN_2026-10-17.md b/docs/NETWORK_BUFFER_48_PLAN_2026-10-17.mdindex 0068cc40..05ede60b 100644--- a/docs/NETWORK_BUFFER_48_PLAN_2026-10-17.md+++ b/docs/NETWORK_BUFFER_48_PLAN_2026-10-17.md@@ -67,7 +67,7 @@- 解复用线程循环:`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 后的前瞻 = 队列跨度。+- 播放位置由引擎每轮写入(音频时钟或最后呈现 PTS)。**前瞻(lead)= 队列里等待的包的时长之和 + 消费方已取走但尚未播到的部分(上限 5 s)**,不再用“最后入队包结束时间 − 播放位置”:10 分钟 1% 丢包测试中,HTTP-TS 流中途重新开始(时间戳回跳 600 s),旧算法的前瞻一直“满”,队列已空却不再读,永久卡死;换成与时间戳无关的时长累加后消除。另有保险:视频消费方发现队列空,生产者无视前瞻继续读(仍受字节上限约束)。- 码率估计:容器 `bit_rate` 或队列字节 / PTS 跨度(≥3 s 样本后取实测);下载速度 = 解复用线程“读包中”的字节 / 读包耗时(EMA),另报 2 秒窗口平均。- 状态机:`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,建议加大缓冲或下载后播放”。绝不降速播放、不报错黑屏。@@ -79,6 +79,7 @@- 退避 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):重新打开,丢弃首个视频关键帧之前的包,时间戳平移使新连接首个关键帧紧接上一连接结束时间(连续时间线,音视频同一平移量),队列首包带“不连续”标记,解码器 `flushBuffers()`,帧带 `Discontinuity` 使图历史重置;重连后的音频包若解码报 `AVERROR_INVALIDDATA` 视为坏包跳过(连续 8 次才算失败)。+- **直播流中途重新开始 / 时间戳突变**(编码器重启、损坏的时间戳;只对直播):视频关键帧的时间戳相对上一个入队包回跳超过 1 s 或前跳超过 3 s,就按重连同样的方式重新锚定(同一平移量让时间线连续,不连续标记,解码器与图历史重置,3 s 内到达的旧时间线音频包丢弃);带突变的非关键视频包按损坏时间戳丢弃,等关键帧。只有音频的突变视为声音的缺口,原样通过。点播只记日志。没有这一条,引擎在流重启后画面冻结到新时间戳追上时钟为止(实测 28 s)。- HTTP 同时打开 FFmpeg `reconnect`、`reconnect_streamed`、`reconnect_on_network_error`、`reconnect_delay_max`(内层快速重试),HLS 设 `seg_max_retry`。### 3.4 损坏容错(C1)@@ -120,3 +121,31 @@(随实施逐项更新;详细命令、日志路径见 `docs/WORKLOG.md` 与 `reports/claude-network-buffer-48-20261017`。)- [x] 存档、AGENTS.md 授权、方案文档(本文件)+- [x] 共享解复用会话(C2/C3/C4/C7 核心)`c6d933c`;引擎接入、测试服务端与 `veyra_network_buffer_tests` `c4da72d`;直播重连修正 `2ad5559`+- [x] 设置、信号面板与缓冲界面(C6/C7)`0d07c9d`;服务器文件字幕扫描等待播放并限速(C5)`3e513c1`+- [x] 与时间戳无关的流控、直播时间线重启、重连间隔上限 `d46d47a`+- [x] 收尾(子会话额度用尽后由协调会话接手提交):HLS 主列表只打开最佳码率变体(Twitch 回放需要;与 mpv `hls-bitrate=max` 同法)、直播重连只做短探测并以 0.5 s 起播缓冲、带宽判定需 3 s 读包证据、码率历史按读包时间老化、`selectAudioStream()` 与解复用线程的锁、重连退避(前 15 s 每秒一次、之后每 2 s)、连接期限改为整个打开过程 40 s(死连接仍由 15 s 读期限切断)。+- [x] 隔行网络电视(1080i IPTV)的损坏画面:此前隔行分支遇到损坏帧仍直接停止(“隔行视频画面损坏或尺寸改变”),现与逐行同一策略(显示修补结果 / 等待关键帧,尺寸变化仍停止;去隔行输出不再重复计数)。新增测试素材 `av-1080i25-60s.ts`(x264 隔行 TFF)与用例 `ts-flip-1pct-interlaced`;测试程序增加 `deinterlace=1` 选项。++### 验收结果(2026-10-18,本机 RTX 5070,单次运行)++完整矩阵 `tests/claude-network-buffer-48-20261017/results/matrix-claude-verify`(收尾改动编译后的同一套程序):19/19 通过。++| 用例 | 结果 | 秒 | 用例 | 结果 | 秒 |+|---|---|---|---|---|---|+| selftest | 通过 | 0.1 | live-outage-8s | 通过 | 46.1 |+| local-ab(本地直读与会话逐帧/像素哈希一致) | 通过 | 2.8 | stop-latency | 通过 | 37.0 |+| local-engine(本地文件不走会话) | 通过 | 12.2 | ts-flip-1pct-10min-decode | 通过 | 11.2 |+| vod-fast | 通过 | 22.3 | ts-drop-1pct-10min-decode | 通过 | 11.2 |+| vod-slow(服务器慢于码率:暂停缓冲并说明原因) | 通过 | 45.4 | ts-loss-1pct-realtime | 通过 | 200.4 |+| vod-big-4k-mkv(约 70 Mbps 4K MKV,慢服务器) | 通过 | 100.4 | live-restart | 通过 | 65.3 |+| vod-stall | 通过 | 50.4 | hls(单码率 / 多码率) | 通过 | 1.0 |+| vod-outage-8s | 通过 | 27.9 | rtsp(mediamtx 只见 1 个读者会话) | 通过 | 25.1 |+| vod-reconnect-off | 通过 | 10.1 | nas-slow-io(慢速 IO 模拟) | 通过 | 40.2 |+| subtitle-scan-nas | 通过 | 18.2 | | | |++隔行损坏补测 `results/claude-interlaced`:`ts-flip-1pct-interlaced` 通过(去隔行输出 2974 场、1363 张损坏画面被容忍、无错误无重连),`ts-flip-1pct-10min-decode` 与 `local-ab` 复测通过。++真实点播(用户指定“随便找个 Twitch 试试”)`tests/claude-network-buffer-48-20261017/twitch`:公开 Twitch 回放(HLS)在引擎里播放 69 s,首帧 5.3 s、1 个连接、0 卡顿 0 重连、服务器 6.4 MB/s / 码率 0.74 MB/s、音画偏差 p95 1 ms;Twitch 剪辑(直链 MP4)30 s 播完,首帧 2.3 s、1 个连接、0 卡顿。带签名令牌的地址只在测试进程内存里,没有写进提交、文档或日志。++未验证:用户自己的直播 / 点播地址(#48 原始源)、真实 NAS / SMB 服务器(用户无服务器,用慢速 IO 与限速服务端模拟)、AMD 实卡、长时间运行。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 851f1bec..c4f5f477 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -5,6 +5,8 @@- 授权与方案:AGENTS.md 顶部同日条目;docs/NETWORK_BUFFER_48_PLAN_2026-10-17.md。分支 claude/network-buffer-48-20261017(main 26c0d61),存档 checkpoint/pre-claude-network-buffer-48-20261017 与 archives/claude-network-buffer-48-20261017(bundle 已 verify,88 工作树 / 108 脏文件)。产物 {build,tests,logs,tmp,reports,archives}/claude-network-buffer-48-20261017。- 核对:计划所述“字幕加载器对网络地址再开连接”与代码不符(网络地址不扫描字幕);实际问题是 NAS 路径整文件扫描与点播无内嵌字幕。设计改为一套共享解复用会话(含 HLS/RTSP/HTTP/NAS),理由见方案 §2。- 进度随实施追加在方案 §5。+- 2026-10-18 子会话额度用尽,由协调会话接手:核对未提交的最后一批修正(HLS 主列表最佳变体、直播重连短探测与 0.5 s 起播缓冲、带宽判定证据、码率历史老化、音轨切换锁、重连退避、40 s 打开期限)后,`tmp/claude-network-buffer-48-20261017/build.py`(无改动增量,0.7 s)+ `make_app.py`,完整矩阵 `py -3.11 -I tests/network/run_network_tests.py --out tests/claude-network-buffer-48-20261017/results/matrix-claude-verify` 19/19 通过(日志 `logs/claude-network-buffer-48-20261017/matrix-claude-verify.log`)。+- 发现并补上隔行分支的损坏帧仍会停止播放(1080i 网络电视常见):改为与逐行同一容错策略;新素材 `av-1080i25-60s.ts` 与用例 `ts-flip-1pct-interlaced`。重新编译 3 个目标 14.8 s,`--only ts-flip-1pct-interlaced,ts-flip-1pct-10min-decode,local-ab` 3/3 通过(`results/claude-interlaced`)。## 2026-10-17 采集格式与旧版入口(Linux 源码候选)diff --git a/include/veyra/media/DemuxSession.h b/include/veyra/media/DemuxSession.hindex f7bf3f33..02247a88 100644--- a/include/veyra/media/DemuxSession.h+++ b/include/veyra/media/DemuxSession.h@@ -213,6 +213,7 @@ private:bool gateKeyframe_ = false; // live reconnect or restarted timeline: wait for a video keyframeint64_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;+ double liveBackCap_ = 0.0; // seconds: the start buffer of a live stream that just reconnected (0: not applied)bool videoStarved_ = false; // the video consumer found its queue empty: reading more is always rightint timestampJumpLogs_ = 0; // diagnostics: leaps in the stream's timestamps, logged a few times per sessionstd::vector<Item> pendingAudio_; // audio read before the live gate openeddiff --git a/include/veyra/media/NetworkInput.h b/include/veyra/media/NetworkInput.hindex 591e1585..23f0a42b 100644--- a/include/veyra/media/NetworkInput.h+++ b/include/veyra/media/NetworkInput.h@@ -14,7 +14,7 @@ namespace veyra::media {// read alike, so a slow server or a Wi-Fi hiccup was reported as a failed source.// Opening a connection and reading media now have separate limits; the owner's// cancel flag (stop / source switch) still aborts every blocking call at once.-constexpr int kConnectTimeoutMs = 15000; // avformat_open_input+constexpr int kConnectTimeoutMs = 40000; // avformat_open_input as a whole (a dead connection is cut at 15 s by rw_timeout)constexpr int kProbeTimeoutMs = 30000; // avformat_find_stream_infoconstexpr int kReadTimeoutVodMs = 20000; // one av_read_frame / seek on a seekable sourceconstexpr int kReadTimeoutLiveMs = 10000; // one av_read_frame on a live sourcediff --git a/include/veyra/source/MediaFileSource.h b/include/veyra/source/MediaFileSource.hindex d6fe42b0..a4cdeb9c 100644--- a/include/veyra/source/MediaFileSource.h+++ b/include/veyra/source/MediaFileSource.h@@ -55,6 +55,7 @@ private:void resetCorruptionState();void startKeyframeWait();bool tolerateDecoderError();+ bool keepDamagedPicture(const AVFrame* frame);media::FFmpegDemuxer demuxer_;media::FFmpegVideoDecoder decoder_;diff --git a/src/media/DemuxSession.cpp b/src/media/DemuxSession.cppindex ae68b309..8afd70d9 100644--- a/src/media/DemuxSession.cpp+++ b/src/media/DemuxSession.cpp@@ -234,6 +234,108 @@ void DemuxSession::closeContext() {file_.reset();}+// ---------------------------------------------------------------------------+// HLS master playlists. FFmpeg's HLS demuxer opens every variant (its playlist and the start of its first+// segment) before the first picture: on a Twitch VOD that is seven playlists of 180 KB and about 20 MB of+// segments, longer than a slow link can deliver in the connect deadline, and all of it thrown away. The best+// variant is chosen here, like other players do (mpv: hls-bitrate=max), and only that one is opened.+// ---------------------------------------------------------------------------+namespace {++struct HlsVariant {+ int64_t bandwidth = 0;+ int64_t pixels = 0;+ bool audioGroup = false;+ std::string uri;+};++std::string hlsAttribute(const std::string& line, const char* key) {+ const std::string needle = std::string(key) + "=";+ for (size_t at = line.find(needle); at != std::string::npos; at = line.find(needle, at + 1)) {+ if (at != 0 && line[at - 1] != ',' && line[at - 1] != ':') continue; // not a longer name that ends the same way+ size_t begin = at + needle.size(), end;+ if (begin < line.size() && line[begin] == '"') {+ ++begin;+ end = line.find('"', begin);+ } else {+ end = line.find(',', begin);+ }+ return line.substr(begin, end == std::string::npos ? std::string::npos : end - begin);+ }+ return {};+}++std::string absoluteUrl(const std::string& base, const std::string& ref) {+ if (ref.starts_with("http://") || ref.starts_with("https://")) return ref;+ const auto scheme = base.find("://");+ if (scheme == std::string::npos) return {};+ const auto authorityEnd = base.find('/', scheme + 3);+ const std::string origin = authorityEnd == std::string::npos ? base : base.substr(0, authorityEnd);+ if (ref.starts_with("//")) return base.substr(0, scheme + 1) + ref;+ if (ref.starts_with("/")) return origin + ref;+ std::string directory = base.substr(0, std::min(base.find('?'), base.find('#')));+ const auto slash = directory.rfind('/');+ directory = slash > scheme + 2 ? directory.substr(0, slash + 1) : origin + "/";+ return directory + ref;+}++// The URL of the best variant when `url` is a master playlist whose variants carry their own audio; empty when it is+// not (a media playlist, another protocol, separate audio renditions, a failed fetch): the caller opens `url` itself.+std::string bestHlsVariant(const std::string& url, AVDictionary* networkOptions, const AVIOInterruptCB& interrupt, std::string* note) {+ const std::string path = url.substr(0, url.find('?'));+ std::string lower = path;+ for (auto& ch : lower) ch = char(std::tolower(static_cast<unsigned char>(ch)));+ if (!lower.ends_with(".m3u8")) return {};+ AVDictionary* options = nullptr;+ av_dict_copy(&options, networkOptions, 0);+ AVIOContext* io = nullptr;+ const int opened = avio_open2(&io, url.c_str(), AVIO_FLAG_READ, &interrupt, &options);+ av_dict_free(&options);+ if (opened < 0) return {};+ std::string text;+ uint8_t buffer[16384];+ for (int n; (n = avio_read(io, buffer, sizeof buffer)) > 0 && text.size() < (512u << 10);) text.append(reinterpret_cast<const char*>(buffer), size_t(n));+ avio_closep(&io);+ std::vector<HlsVariant> variants;+ bool separateAudio = false;+ HlsVariant pending;+ bool expectUri = false;+ size_t begin = 0;+ while (begin < text.size()) {+ size_t end = text.find('\n', begin);+ if (end == std::string::npos) end = text.size();+ std::string line = text.substr(begin, end - begin);+ begin = end + 1;+ while (!line.empty() && (line.back() == '\r' || line.back() == ' ')) line.pop_back();+ if (line.starts_with("#EXT-X-STREAM-INF:")) {+ pending = {};+ const auto bandwidth = hlsAttribute(line, "BANDWIDTH");+ pending.bandwidth = bandwidth.empty() ? 0 : std::atoll(bandwidth.c_str());+ const auto resolution = hlsAttribute(line, "RESOLUTION");+ if (const auto x = resolution.find('x'); x != std::string::npos) pending.pixels = std::atoll(resolution.c_str()) * std::atoll(resolution.c_str() + x + 1);+ pending.audioGroup = !hlsAttribute(line, "AUDIO").empty();+ expectUri = true;+ } else if (line.starts_with("#EXT-X-MEDIA:")) {+ if (hlsAttribute(line, "TYPE") == "AUDIO" && !hlsAttribute(line, "URI").empty()) separateAudio = true;+ } else if (expectUri && !line.empty() && line[0] != '#') {+ pending.uri = line;+ variants.push_back(pending);+ expectUri = false;+ }+ }+ if (variants.size() < 2 || separateAudio) return {};+ const HlsVariant* best = nullptr;+ for (const auto& v : variants)+ if (!best || v.pixels > best->pixels || (v.pixels == best->pixels && v.bandwidth > best->bandwidth)) best = &v;+ if (!best || best->audioGroup) return {};+ const std::string chosen = absoluteUrl(url, best->uri);+ if (chosen.empty()) return {};+ if (note) *note = std::format("hls master playlist: {} variants, opening only the best ({} bit/s, {} pixels)", variants.size(), best->bandwidth, best->pixels);+ return chosen;+}++} // namespace+bool DemuxSession::openContext(std::wstring* error, bool initial) {closeContext();AVFormatContext* context = avformat_alloc_context();@@ -243,7 +345,7 @@ bool DemuxSession::openContext(std::wstring* error, bool initial) {}context->interrupt_callback = {&Interrupt::callback, irq_.get()};AVDictionary* options = nullptr;- const std::string name = utf8(path_);+ std::string name = utf8(path_);if (network_) {networkMediaOptions(&options);// Short drops are retried inside FFmpeg's HTTP layer first; this session's@@ -254,6 +356,13 @@ bool DemuxSession::openContext(std::wstring* error, bool initial) {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);+ if (!initial && live_) {+ // A live stream that comes back is probed briefly: the streams are known from the first open, and the+ // full analysis (20 pictures for the frame rate) only delayed the first picture by a second or more.+ av_dict_set(&options, "analyzeduration", "400000", 0);+ av_dict_set(&options, "probesize", "1048576", 0);+ av_dict_set(&options, "fpsprobesize", "0", 0);+ }} else {file_ = std::make_unique<FileAvio>();if (!file_->open(path_, irq_.get())) {@@ -267,6 +376,14 @@ bool DemuxSession::openContext(std::wstring* error, bool initial) {context->flags |= AVFMT_FLAG_CUSTOM_IO;}irq_->arm(kConnectTimeoutMs);+ if (network_) {+ std::string note;+ const std::string best = bestHlsVariant(name, options, {&Interrupt::callback, irq_.get()}, ¬e);+ if (!best.empty()) {+ log::info("net-session", note);+ name = best;+ }+ }int result = avformat_open_input(&context, name.c_str(), nullptr, &options);av_dict_free(&options);const bool timedOut = irq_->timedOut();@@ -274,7 +391,7 @@ bool DemuxSession::openContext(std::wstring* error, bool initial) {if (result < 0) { // avformat_open_input freed the contextlog::error("net-session", std::format("open failed code={} text={} timedOut={} initial={}", result, errorText(result), timedOut, initial));file_.reset();- if (error) *error = irq_->cancelled() ? L"已取消" : timedOut ? L"连接服务器超时(15 秒内没有响应),请检查地址和网络" : L"无法连接到服务器或地址不可用,请检查网络";+ if (error) *error = irq_->cancelled() ? L"已取消" : timedOut ? L"连接服务器超时(40 秒内没有完成),请检查地址和网络" : L"无法连接到服务器或地址不可用,请检查网络";return false;}irq_->arm(kProbeTimeoutMs);@@ -464,6 +581,8 @@ double DemuxSession::resumeTargetLocked() const {// 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));+ // A live stream that has just come back restarts with half a second: the jitter buffer refills while it plays.+ if (liveBackCap_ > 0) target = std::min(target, liveBackCap_);return std::min(target, std::max(1.0, aheadSecondsLocked() - 0.5));}@@ -475,6 +594,7 @@ void DemuxSession::enterPhaseLocked(Phase phase, const char* why) {phase == Phase::Playing ? "playing" : phase == Phase::Buffering ? "buffering" : "prebuffering", why,leadSecondsLocked(), targetSeconds_, bandwidthLow_, stalls_));phase_ = phase;+ if (phase == Phase::Playing) liveBackCap_ = 0.0;phaseSinceNs_ = now;consumerCv_.notify_all();producerCv_.notify_all();@@ -484,7 +604,8 @@ void DemuxSession::updatePhaseLocked() {// Bandwidth verdict (hysteresis): the server delivers less than the stream needs.{const double bitrate = bitrateLocked(nullptr), server = serverRateLocked();- if (bitrate > 0 && readSecondsDecayed_ >= 3.0) {+ // Judged on enough evidence: 3 s of reading that delivered at least two seconds of the stream.+ if (bitrate > 0 && readSecondsDecayed_ >= 3.0 && readBytesDecayed_ >= 2.0 * bitrate) {if (!bandwidthLow_ && server < bitrate * 0.95) {bandwidthLow_ = true;log::warn("net-session", std::format("server slower than the stream: server {:.2f} MB/s < bitrate {:.2f} MB/s", server / 1048576.0, bitrate / 1048576.0));@@ -756,7 +877,8 @@ bool DemuxSession::verifyStreams() {}const auto* now = context_->streams[videoIndex_]->codecpar;const auto* before = streams_[size_t(videoIndex_)].parameters.get();- if (before && (now->width != before->width || now->height != before->height)) {+ // (a short probe may not have seen the picture size yet: only a size that is known can differ)+ if (before && now->width > 0 && now->height > 0 && (now->width != before->width || now->height != before->height)) {log::warn("net-session", std::format("reconnected source changed picture size {}x{} -> {}x{}", before->width, before->height, now->width, now->height));return false;}@@ -846,12 +968,12 @@ void DemuxSession::threadMain() {if (result >= 0) {{std::lock_guard lock(m_);- const int64_t now = nowNs();- const double dt = lastRateNs_ ? double(now - lastRateNs_) / 1e9 : 0.0;- const double keep = std::exp(-dt / 6.0);+ // The history ages with reading time, not with the idle time while the window is full: after a+ // pause one slow call (the first byte of a new HLS segment can take seconds) must not outweigh+ // everything read before it.+ const double keep = std::exp(-seconds / 6.0);readBytesDecayed_ = readBytesDecayed_ * keep + double(packet->size);readSecondsDecayed_ = readSecondsDecayed_ * keep + seconds;- lastRateNs_ = now;}onPacket(packet);continue;@@ -943,13 +1065,18 @@ void DemuxSession::onPacket(AVPacket* pkt) {// 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;+ int64_t lastDtsUs;+ {+ std::lock_guard lock(m_); // a consumer's selectAudioStream() clears the audio queue+ lastDtsUs = queue.lastDtsUs;+ }+ if (!gateKeyframe_ && dtsUs != AV_NOPTS_VALUE && lastDtsUs != INT64_MIN) {+ const int64_t step = dtsUs + offsetUs_ - 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,+ double(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_) {@@ -1215,6 +1342,7 @@ bool DemuxSession::recover(int code, const char* why) {reconnectAttempt_ = 0;++reconnects_;eof_ = false;+ liveBackCap_ = live_ && plan_.holds ? 0.5 : 0.0;log::info("net-session", std::format("reconnected after {} attempt(s), {} ms; reconnects={} live={}", attempt,std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - begin).count(), reconnects_, live_));updatePhaseLocked();@@ -1222,9 +1350,9 @@ bool DemuxSession::recover(int code, const char* why) {}closeContext();gateKeyframe_ = false;- // 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);+ // Every second for the first 15 s, then every 2 s: whenever the server comes back, the next try is at most+ // a second away, which leaves room for the keyframe wait and the start buffer inside 5 s of an outage's end.+ delayMs = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - begin).count() < 15000 ? 1000 : 2000;}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 77639f97..e84af1c7 100644--- a/src/source/MediaFileSource.cpp+++ b/src/source/MediaFileSource.cpp@@ -339,9 +339,13 @@ readAgain: // a damaged picture was dropped (corrupt policy WaitKeyframe): fetframe = decoder_.receiveFrame();if(frame){if(deinterlaceEnabled_&&((frame->flags&AV_FRAME_FLAG_INTERLACED)||deinterlacer_.active())){- if(frame->width!=int(info_.width)||frame->height!=int(info_.height)||frame->decode_error_flags||(frame->flags&AV_FRAME_FLAG_CORRUPT)){+ const bool damaged=frame->decode_error_flags||(frame->flags&AV_FRAME_FLAG_CORRUPT);+ if(frame->width!=int(info_.width)||frame->height!=int(info_.height)||(damaged&&!tolerant_)){errorMessage_=L"隔行视频画面损坏或尺寸改变,已停止处理";return SourceReadStatus::Error;}+ // Interlaced network TV (1080i IPTV) loses packets like any other stream:+ // the same damaged-picture policy applies before the picture reaches the filter.+ if(damaged&&!keepDamagedPicture(frame))continue;const auto* surface=decoder_.usingD3D11Frames()?&decoder_.hardwareSurface():nullptr;if(!deinterlacer_.active()){AVRational rate{demuxer_.nominalRateNum(),demuxer_.nominalRateDen()};@@ -481,25 +485,15 @@ readAgain: // a damaged picture was dropped (corrupt policy WaitKeyframe): fetreturn SourceReadStatus::Error;}- if ((frame->flags & AV_FRAME_FLAG_CORRUPT) || frame->decode_error_flags) {+ // Deinterlaced output inherits the flags of a picture the policy already accepted+ // before the filter; checking it again would count the same loss once per field.+ if (!deinterlacer_.active() && ((frame->flags & AV_FRAME_FLAG_CORRUPT) || frame->decode_error_flags)) {if (!tolerant_) {veyra::log::error("source-file", std::format("corrupt decoded frame flags={} decodeErrors={}", frame->flags, frame->decode_error_flags));errorMessage_ = L"源视频包含损坏画面,已停止处理";return SourceReadStatus::Error;}- // Network loss: FFmpeg has concealed what it could. Show that picture, or drop it- // and wait for the next keyframe, as the user chose.- ++corruptFramesSeen_;- const bool drop = corruptPolicy_ == media::CorruptPolicy::WaitKeyframe;- if (const auto& session = demuxer_.session()) session->addCorruptFrames(1, drop ? 1 : 0);- const auto now = std::chrono::steady_clock::now();- if (now - lastCorruptLog_ >= std::chrono::seconds(1)) {- lastCorruptLog_ = now;- veyra::log::warn("source-file", std::format("damaged picture flags={} decodeErrors={} policy={} picturesSoFar={}",- frame->flags, frame->decode_error_flags, drop ? "wait-keyframe" : "conceal", corruptFramesSeen_));- }- if (drop) {- startKeyframeWait();+ if (!keepDamagedPicture(frame)) {goto readAgain;}}@@ -700,6 +694,23 @@ void MediaFileSource::startKeyframeWait()waitKeyframeSince_ = std::chrono::steady_clock::now();}+// Network loss: FFmpeg has concealed what it could. Keep that picture, or drop it and+// wait for the next keyframe, as the user chose. Only called for tolerant sources.+bool MediaFileSource::keepDamagedPicture(const AVFrame* frame)+{+ ++corruptFramesSeen_;+ const bool drop = corruptPolicy_ == media::CorruptPolicy::WaitKeyframe;+ if (const auto& session = demuxer_.session()) session->addCorruptFrames(1, drop ? 1 : 0);+ const auto now = std::chrono::steady_clock::now();+ if (now - lastCorruptLog_ >= std::chrono::seconds(1)) {+ lastCorruptLog_ = now;+ veyra::log::warn("source-file", std::format("damaged picture flags={} decodeErrors={} policy={} picturesSoFar={}",+ frame->flags, frame->decode_error_flags, drop ? "wait-keyframe" : "conceal", corruptFramesSeen_));+ }+ if (drop) startKeyframeWait();+ return !drop;+}+bool MediaFileSource::seek(const pipeline::Rational& targetSeconds){if (!info_.opened) { return false; }diff --git a/tests/integration/NetworkBufferTests.cpp b/tests/integration/NetworkBufferTests.cppindex ca3fc2c9..559d2dff 100644--- a/tests/integration/NetworkBufferTests.cpp+++ b/tests/integration/NetworkBufferTests.cpp@@ -149,7 +149,7 @@ int sourceTest(const std::wstring& path, const std::filesystem::path& out, constdesc.path = path;desc.cancelled = &cancel;desc.preferHardwareDecode = num(o, "hw", 0) != 0;- desc.deinterlace = false;+ desc.deinterlace = num(o, "deinterlace", 0) != 0; // playback default is on; offline readers keep it offdesc.network = networkSettings(o);desc.nonBlocking = num(o, "nonblocking", 0) != 0;desc.tolerateCorruption = num(o, "tolerant", 0) != 0;@@ -229,6 +229,7 @@ int sourceTest(const std::wstring& path, const std::filesystem::path& out, const<< "\",\"error\":\"" << jsonEscape(narrow(input.errorMessage())) << "\",\"elapsedSeconds\":" << elapsed<< ",\"maxFrameGapMs\":" << maxGapMs << ",\"gapsOver500ms\":" << bigGaps << ",\"waits\":" << waits << ",\"nonMonotonic\":" << nonMonotonic<< ",\"discontinuities\":" << discontinuities << ",\"hash\":\"" << std::hex << overall << std::dec << "\""+ << ",\"deinterlaced\":" << (input.info().deinterlaced ? "true" : "false")<< ",\"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.stallsdiff --git a/tests/network/make_media.py b/tests/network/make_media.pyindex e5f52ba0..589d252f 100644--- a/tests/network/make_media.py+++ b/tests/network/make_media.py@@ -7,6 +7,7 @@av-720p30-10min.ts 10 minutes of MPEG-TS for the packet-loss runsav-720p30-60s-subs.mkv the 60 s MKV with two embedded SRT tracks (subtitle scan of a NAS-style file)live-src.ts 20 s loop source for the real-time /live.ts relay+ av-1080i25-60s.ts one minute of interlaced 1080i25 MPEG-TS (IPTV-like) for the damaged-interlaced runhls/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]@@ -63,6 +64,14 @@ def main():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'])+ if not (out / 'av-1080i25-60s.ts').exists():+ # IPTV-like 1080i25: two real fields per frame (50p folded by the interlace filter), interlaced x264 coding+ run(common + ['-f', 'lavfi', '-i', 'testsrc2=size=1920x1080:rate=50',+ '-f', 'lavfi', '-i', 'sine=frequency=1000:beep_factor=4:sample_rate=48000', '-t', '60',+ '-vf', 'interlace=scan=tff', '-c:v', 'libx264', '-preset', 'veryfast', '-b:v', '6M', '-maxrate', '8M',+ '-bufsize', '12M', '-g', '50', '-keyint_min', '50', '-sc_threshold', '0', '-flags', '+ildct+ilme',+ '-x264-params', 'tff=1', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '128k', '-f', 'mpegts',+ out / 'av-1080i25-60s.ts'])hls = out / 'hls'vod = hls / 'vod'diff --git a/tests/network/run_network_tests.py b/tests/network/run_network_tests.pyindex d8bab316..c8a963aa 100644--- a/tests/network/run_network_tests.py+++ b/tests/network/run_network_tests.py@@ -292,6 +292,27 @@ def ts_drop_decode(out, a):return finish(name, out, checks, data)+def ts_flip_interlaced(out, a):+ """1 % damaged packets in an interlaced 1080i25 TS (IPTV-like) with the player's deinterlacing on: damaged+ pictures on the interlaced path follow the same policy as progressive ones instead of stopping the source."""+ checks, data = [], {}+ name = 'ts-flip-1pct-interlaced'+ with Server(out / f'{name}-srv', ts_flip=0.01) as s:+ rc, res, sec = run_exe('source', s.url('av-1080i25-60s.ts'), out / name, dict(tolerant=1, deinterlace=1), timeout=290)+ st = server_stats(s)+ data.update(result=res, server=st, wallSeconds=sec)+ check(checks, 'plays the whole minute through the deinterlacer', rc == 0 and res and res['status'] == 'eos' and res['lastPts'] > 58,+ f"rc={rc} status={res and res['status']} lastPts={res and res['lastPts']} error={res and res['error']}")+ if res:+ check(checks, 'the deinterlacer was in use', res.get('deinterlaced') is True, str(res.get('deinterlaced')))+ check(checks, 'damage was really injected and noticed', res['corruptPackets'] + res['corruptFrames'] > 10,+ f"packets={res['corruptPackets']} frames={res['corruptFrames']}")+ check(checks, 'about 3000 fields (1 % damage may drop a few)', 2700 <= res['frames'] <= 3010, 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 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 = [], {}@@ -463,7 +484,7 @@ def subtitle_scan(out, a):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),+ ('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), ('ts-flip-1pct-interlaced', ts_flip_interlaced), ('live-restart', live_restart),('hls', hls), ('rtsp', rtsp), ('nas-slow-io', nas_slow), ('subtitle-scan-nas', subtitle_scan)]