This repository was archived by the owner on Oct 24, 2026. It is now read-only.
Repository navigation
Conversation
Begins the Rust + Tauri 2 rewrite on a branch, keeping main's Python as the reference implementation. This commit is the ground floor: the seven modules that touch no socket, no process and no protocol, so every one of their contracts can be tested on any machine. Each module here exists because AGENTS.md records a failure that the shape of the old code allowed: - paths: the config dir is resolved once and pinned, and a test build can never resolve to the real one — an un-claimed logger writes on its first record, and "never touch the user's configuration to verify something" cannot depend on which test runs first. Includes the Windows divergence (appdirs asks the shell, which reads the registry, so MACAST_SETTING_DIR is the isolation hook and a forged %LOCALAPPDATA% is not). - setting: a file we cannot read is moved aside, whole, with same-second collisions suffixed; using defaults and then saving would overwrite 36 keys with 11, including the API token. - token: three random identifiers with three different formats, because three different readers parse them; getrandom failing is an error, never a clock-derived fallback, since every one of these is a trust boundary. - trash: removal is a move, and the destination keeps the base name so the loader finds the file it looks for. - env: the player gets no proxy variables and the bundled LD_LIBRARY_PATH before the child starts, or the host's ffmpeg cannot load. - net: `get_ip` returns a *set* — membership is the contract, order is not — and the default-route parser reads column 0, not the gateway column. - logging: the tail reader windows by bytes and drops the cut half-line, and the byte cap only means something to a test that exceeds it. 68 tests, all deterministic, none of them touching the network or spawning. The Tauri skeleton is in the same commit because it is what proves the layering compiles as a workspace; its icons are derived from macast/assets/ at build time rather than committed twice, and the generated schemas are ignored.
Second crate on the rewrite branch. `macast-mpv` is the pure half of
`macast_renderer/mpv.py`: what we tell mpv to run, what bytes we write down its
socket, and what a reply means. No process spawning and no socket ownership here
— those need the Tauri shell, and putting them in this crate would mean the
interesting half of the file is the half that cannot be tested on any machine.
The crate goes into `[workspace].members` in this same commit, not before: a
members entry without a manifest breaks `cargo` for every crate in the tree, so
"land the crate, then wire it" is one commit or neither.
Why each module is shaped the way it is:
- pyjson: the CPython 3.12 `_json` C scanner, replayed. It is the single
validity gate for IPC decoding — `json.loads` is what decides whether a line
is a reply at all — so the standard-library scanner was reimplemented rather
than borrowed from `serde_json`, whose grammar differs on `[1,]`, on
control characters inside strings, on `\escape`, and on `-Infinity`. Every
message text and every `(line, column, char)` triple was measured against the
repo's `.venv` (3.12.15), never the machine's `python3` (3.14.8, which worded
the trailing-comma sentence differently and is not the reference).
- ipc: the reader loop's exact contract — one `res` per connection, only a
chunk ending in `\n` is parseable, `b''` means reconnect, and one `except`
wraps the whole batch of lines so a bad line stops the later good ones. The
decode-error string quotes CPython's byte-offset range form, which changes
shape between a one-byte and a multi-byte bad span.
- state: reply → signal, with Python's comparisons, not Rust's. `True == 1` and
`1.0 == 1`, so a bool or a whole float `id` really is the volume branch; a
string `id` matches nothing and falls silent. `int()` truncates, so position
is floor-taken; `//` and `%` are floored, so the clock reads `-1:59:55` for
minus five seconds. Presence is not truthiness: a `data` of `0`, `''` or
`false` is present and must still be sent. `str(KeyError('data'))` is `'data'`
with quotes, and the fall-through log line is `str(res)` — dict repr, keys in
wire order.
- argv/command: the parameter list mpv is launched with, and the exact JSON-IPC
shapes, including `LIVE_LOAD_OPTIONS`' ten keys and the rule that a live load
must not carry `start`.
`serde_json` gained `preserve_order` at the workspace level for two reasons that
are both load-bearing: the live-option dict's insertion order is what reaches
mpv, and the log lines that quote a decoded reply print dict keys in the order
the server sent them. A BTreeMap-backed map re-sorts both, silently.
`macast-core/src/setting.rs` gained the five `Player*` keys. They live there
because that file is one table with one writer: a player key declared on the far
side of the crate boundary would be a second source for its own JSON spelling.
70 tests pass, whole workspace green, zero warnings. Two directed mutations on
`state.rs` each went red on exactly one test and only that one: restoring the
subscript sentence to an invented one kills the test that calls `index`
directly — the arm `apply` can never reach, kept honest because its message
differs from the membership sentence that really fires — and replacing
`python_number_eq` with a plain `as_u64` kills the bool/whole-float id test.
…hree-attempt story
The other half of `macast_renderer/mpv.py`: `link.rs` owns one socket, `player.rs`
owns the process, the reader loop, the command writer, and the cleanup. Unix only;
`link.rs` and `player.rs` are `#[cfg(unix)]`, because reproducing Windows named
pipes here would be a mock that lets a test pass against code that has never run.
Why each shape is what it is:
- The knob that raises is fatal, and it is fatal *outside* the try. `params =
self.build_mpv_params()` sits at `mpv.py:527`, which is not inside the `try:`
opened at `:532` — measured on CPython 3.12.15 by replaying that exact control
flow: `log: ['speed']`, `alive after join: False`, one traceback on
`Exception in thread MPV_THREAD:`. So no "mpv starting", no `publish('mpv_start')`,
no retry, no budget spent, no "mpv cannot start", no notify, no `stop_service()`.
`argv::build` returns that case as an `Err` and `player.rs` logs it and breaks,
leaving `error_time` at 3 so the tail never fires. `PlayerHW` is *not* that case:
Python's `hw == 0` / `hw == 2` are both `False` for a non-number, so neither
branch runs and `--hwdec=yes` survives — a warning, not a refusal. (`Level::Warning`
is the port's own invention: `grep logger.warn macast_renderer/mpv.py` returns
nothing, so the reference has no warning-level logging at all.)
- `spawn_failure` appends the program name and socket errors never do, because
`Popen` and `socket` disagree about what identifies a failure. `[Errno 2]` for a
missing program, `[Errno 13]` for a directory or a non-executable, `[Errno 61]`
for a closed listener that left its file behind, `[Errno 38]` for a regular file,
`[Errno 32]` on a send after the peer closed, `b''` on a recv, `[Errno 9] Bad
file descriptor` for a socket we closed ourselves, `[Errno 57]` for one that was
assigned before a failed connect, and `'NoneType' object has no attribute
'sendall'` for a path never tried. Each text was asked of the Python on this
machine, not guessed from errno tables. `Popen.communicate()` never raises on a
non-zero exit — measured, exit 4 with stderr still returned — so there is no
`CalledProcessError` analogue in the port: only `Popen()` itself can fail.
- `set_observe` is ten commands, not one: eight separate `observe_property` calls
then the default volume then its text, all as ten `send_command`s, each of which
logs `send command: ` + Python's own `str(list)` before taking the lock. The
DEBUG line is outside the lock because the reference's is; a test that pinned
the log inside went red for the harness's ordering, not the product's.
- A connection is a *session*, and a session owns its buffer. `feed.reconnect()`
runs only after a fresh connect, so the bytes a dead session left half-read never
reach a new one — and `msg` deliberately survives: the batch's except arm quotes
the last message the *previous* session parsed. A thread's first-ever decode
failure raises `UnboundLocalError` inside that arm, truncating the three-line
story to one and killing the reader while `ipc_running` stays `True`, so later
`start()` hears "mpv ipc is already runing" and mpv plays on with no control
point. Both halves are tested, including the half that is a bug we port faithfully.
- Protocol reads are per line, not per batch: `get_state_transport_state()` and
`publish('renderer_av_uri', ...)` both sit inside `update_state` (`mpv.py:317`,
`:354`), so an `end-file` sees a transport state that the earlier lines in the
same chunk already changed.
- `stop()` keeps the reference's order, including the two that look accidental:
`kill()` only inside `wait`'s except arm, and the player thread joined *before*
`ipc_running` is cleared. `Link::close` cannot be the wake-up mechanism —
measured: `shutdown(2)` returns 0 and wakes a reader parked in `read(2)` with EOF,
dropping a non-final handle wakes nothing, and a peer close wakes it anyway, so a
design built on close would be a design built on the wrong event. Then
`os.remove(socket_path)` with `OSError` swallowed: mpv v0.41.0 never removes its
own socket file, verified against the real binary.
Two fixture facts, both of which were wrong before they were measured:
- `UnixListener::bind` calls `listen(SOMAXCONN)`, so `connect()` succeeds as soon as
the socket sits in the backlog — *before* the accept thread runs. A writer that
iterated its accepted list then wrote to nobody, losing the line in silence.
Hence `FakeMpv::await_connection()`.
- The fake mpv listener is a thread in the test process, not the child — the child is
a `/bin/sh` script. Killing the child therefore leaves the IPC connection alive,
which is exactly the isolation the budget tests need, and is why `Harness::stop()`
hangs up the fake itself.
Ten directed mutations, one command each, restored inside the same command with a
byte-identical md5 afterwards: delete `feed.reconnect()` (originally zero teeth —
`hang_up()` also dropped the listener and hid the failed reconnect, so the fake grew
`drop_connections()` and the fix gained two tests), delete the close-through-the-slot,
delete `set_observe`, swap the two publishes, move the slot assignment after connect,
delete `remove_file`, let `Session::Abandoned` run the `Ended` cleanup, put the DEBUG
log inside the lock, delete the lock acquisition, and drop `&& !ipc_once_connected`
from the retry gate. The last one is the branch nothing else reaches: once a socket
has connected, a dead child is respawned with no sleep and no "mpv restarting" line,
so `exec true` is not a way to end this thread and "MPV Can't start" can only ever
describe a machine where mpv was never reachable. Its test needed two deaths, not
three — with three it failed inside `wait_until` and the claim was never asked.
One hygiene gap found by inspection rather than by a failure: a *red* run of the
real-mpv test left real mpv playing — AGENTS.md's "被反复重启的 Macast 会攒播放器",
except the pile would belong to the suite. `Harness` now declares a `Guard` as its
first field (Rust drops fields in declaration order, and a manual `Drop` runs before
any of them), which clears `running` and reaps the child, and the real-mpv test binds
one itself. Proven with a counterfactual: guard body emptied → orphan pid 12487,
confirmed ours by its `--input-ipc-server=/tmp/rm12486-0/s` and reaped; guard intact →
no new mpv. The user's five mpv processes were compared before and after and untouched.
111 tests in `macast-mpv`, 69 in `macast-mpv`'s neighbour `macast-core`, whole
workspace green serially and in parallel, zero warnings. The real-mpv end-to-end test
is opt-in (`MACAST_RUST_MPV_E2E=1`) because it spawns the Homebrew binary; it passes.
…ly says
Ported `MPVRenderer`'s eleven `set_media_*` actions and `reload()` into
`macast-mpv::Player`, composing every one through `send_command` so the
DEBUG-outside-the-lock, `sendCommand: {e}` and `NO_SOCKET` contracts stay
owned once.
The parts that are not mechanical:
- the three-state liveness verdict (`Liveness::{Live, Finite, Undeclared}`)
is stored as given — `None` is "keep today's behaviour", not a shy
`Some(false)`, and the two are indistinguishable on the socket, so the
witness is the stored verdict itself;
- volume/mute/speed/sub-show take a `Value`, not a coerced scalar: mpv gets
the JSON it was handed and the toast prints Python's `str()` of it
(`pyops::py_str`), with mute chosen by Python truthiness;
- fullscreen stays a `set_property` read from `Host::player_size()` through
`pyops::py_eq`, never a per-file option, so the second video still goes
full-screen;
- `set_media_title` writes both `title` and `force-media-title` and
remembers the text — `/relay/<id>/media` ends in `media`, and mpv's
default template falls back to the filename (AGENTS.md §4.2);
- `reload()` reads the url eagerly and the position on the reconnect, arms
only under `PLAYING` and before the spawn, on a thread named `MPV_RELOAD`
because `stop()` joins the player threads.
Verification: `cargo test --workspace` 69 + 140 passed, 0 failed. Fourteen
定点变异体 each went red on their own claim (2/8/1/2/1/1/1/1/6/4/2/2/1); the
first cut of the None-vs-False mutant was 0 red, which is why the verdict
test above exists — an unasked question is a passed test (AGENTS.md §4.2).
…d facts
The port so far is differential against a `/bin/sh` script that answers with the
bytes a test wrote into it. That is the right instrument for "what do we send",
and the wrong one for AGENTS.md §4.2's 「只有真机才教得了的 mpv 读取事实」 and §5's
「一次批量读取要按 `request_id` 是否凑齐来终止」 — those describe what a genuine
player *says*. This adds five env-gated tests that ask the real binary through the
product's own seams (`Player::start` → the socket → `send_command`), so nothing new
is invented about how to talk to mpv:
- an idle player's five single reads, asserted field by field;
- `start` in the fifth slot resumes (time-pos 11.5–20 for `start=12` on a 20 s clip),
and the same thing written as a fourth positional is mpv's playlist index and comes
back `invalid parameter`;
- the ten live options really land and the next bare `loadfile` really restores the
defaults (audio-buffer 0.0→0.2, cache-pause False→True, stream-buffer-size 4k→131072);
- a real property change carries the id the eight-way dispatcher keys on;
- the window says `media` until the card names it — `filename` is `media` for
`/relay/<id>/media`, and `media-title` / `force-media-title` are the seam.
Measured on mpv v0.41.0 at `/opt/homebrew/bin/mpv`, asserted only as measured. Two
of those readings are why this file exists at all: the four unavailable properties
answer `{'request_id': 0, 'error': 'property unavailable'}` with **no `data` key at
all**, while `force-media-title` answers `{'data': '', 'request_id': 0, 'error':
'success'}` — so filtering a batch on `error == 'success'` never collects the set and
the socket times out, which is exactly the §5 sentence. And mpv's key order is *not*
the same between those two shapes, so the witness asserts fields and not the line.
Two deliberate limits, written in the code so the next reader does not "fix" them:
`demuxer-lavf-o-add` is not asked (it is an appended list whose printed shape I have
not measured here, and asserting a guess would be a witness that lies), and 「Living
media」 is not asserted (the test host pins the transport to STOPPED by design).
`MPV_HOME` is pinned to the session's own temp `home` rather than left to the shell:
our base argv carries `--save-position-on-quit=yes`, so an ungated run would write
into `~/.config/mpv/watch_later` — AGENTS.md §10's 「不要为了验证去改用户的真实配置」.
Teeth, measured one mutation at a time (whole crate each time, file restored and
md5-verified before the count was read): the settle-wait removed 1, one pinned live
option wrong 1, the no-`data` assertion inverted 1, the expected `property
unavailable` text changed 1, the fixture built under its extension-less name 1 (and
that red prints ffmpeg's own refusal — the vacuous-green shape this block used to
have: a skip from our *instrument* being wrong is §4.2's 「不提问的检查」 wearing a
green tick), `set_media_url` dropping the resume position 4, expecting a volume the
machine never reported 1, and deleting `ask_real`'s one-row-per-command assertion
**0**. The last one stays anyway and says why in its docstring: it is not there to
catch today's timing, it is there so that weakening the settle-wait becomes a red
instead of a silently misread row.
Verification: `cargo test --workspace` 69 + 145 passed, 0 failed; the gated run serial
is 145 passed with **0** `SKIPPED` lines. Untouched by any of this, re-counted after
every run: the user's five mpv children (4895/15989/58389/68053/79185), 92
`/tmp/macast_mpvsocket*`, 58 `watch_later` entries, no leftover `/tmp/rm<pid>-*`.
`command.rs` and `pyops.rs` are byte-identical to their pre-session md5; the only file
changed is `player.rs`, and both hunks sit inside `mod tests`.
…h half a machine checked
The owner asked for 「把 macast-mpv 移植到 windows 和 Linux」 on top of the mpv.py port,
so the crate's `#[cfg(unix)]` gates are gone. What that means differs per platform, and
this commit is written so the difference survives reading it:
**Windows — ported, compile-verified only.** `link.rs` gains a second `impl Link` over
named pipes: `CreateFileW` for the connect, `WriteFile`/`ReadFile`/`PeekNamedPipe` for
the frame halves, `FormatMessageW` for the error sentence, `OpenProcess` +
`TerminateProcess` for the two kill stages. The calls go to the OS directly because this
toolchain's Windows standard library ships no `named_pipe` module (`std::os::windows::{fs,
thread}` are all that resolve) and no pip dependency may be added to the default artefact
(AGENTS.md §4.3/§4.8), so `macast-mpv/Cargo.toml`'s seven windows-sys features are the
product's Windows surface, each one there because a *measured* CPython call needs it.
`windows-sys = "0.61"` is pinned at the workspace level to 0.61.2, which ten src-tauri-side
packages already carry — 0.59 arrives only via winreg and 0.45 only via jni.
The shape difference from Unix is the interesting part and it is documented at every place
it bites: there is no Windows call that makes a handle without also reaching the server, so
a failed connect leaves the slot *empty* (`created()` clears it every time), whereas Unix
keeps a socket object that has never connected. Both paths end on the same log line,
`link::NO_SOCKET`, and the line itself cannot tell them apart — which is why
`player::windows_tests` asserts the slot's state and not only the sentence, with one case
holding a handle-less `Link` and one holding `None`. The pipe name is a flat namespace with
no per-user and no per-directory part, so each Windows test names its own pipe after
`std::process::id()` plus a marker: two cases sharing a name would collide for real rather
than in a fixture.
**Linux — ported with measured literals, not re-measured after this edit.** The deltas are
written as both platform literals inside `if cfg!(target_os = "linux") { … } else { … }`
rather than routed through `libc::ENOTCONN`, so a platform with a different number cannot
quietly redefine what the log says: ENOTCONN is 107 "Transport endpoint is not connected"
(here 57 "Socket is not connected", and on Linux 57 is 「Invalid slot」), `recv` on an
unconnected socket is `[Errno 22] Invalid argument`, and a path naming an inode that is not
a socket refuses with `[Errno 111]` — which collapses two diagnoses macOS keeps apart at
61/38. ENOENT 2 / EACCES 13 / EPIPE 32 / EBADF 9 are identical, and `fits()` takes its
`sockaddr_un` capacity from the target's own `libc` type, so Linux's 108-byte limit is
respected by construction rather than by a constant. No product path branches on errno
*values*; they are only ever formatted.
Verified on this machine: `cargo test -p macast-mpv` **145 passed / 0 failed**, twice — once
parallel, once serial with `MACAST_RUST_MPV_E2E=1` and ffmpeg on PATH, which is the run that
must print **zero `SKIPPED` lines** for the five real-mpv witnesses to count as run (16.55 s,
`a_real_mpv_serves_the_socket_we_ask_for ... ok`). Windows and Linux are verified as
`cargo check --all-targets` clean for this crate — `--all-targets` because `cargo check` does
not typecheck `#[cfg(test)]`, so a gated test module would otherwise never have been compiled
by anything. The nine `link::windows_tests` and three `player::windows_tests` therefore have
**never been executed**, and neither has any Windows runtime behaviour: the error sentences
were read off CPython, and `CreateFileW`'s number for an unopened pipe is deliberately not
asserted (2 / 231 / 109 are all defensible readings of a name with no server) — only the
`[WinError ` prefix and a non-empty remainder are, because CPython's prefix is the portable
half. Linux's runtime claims rest on the 2026-10-07 container read
(`/tmp/linux-baseline-3.txt`: 139 passed / 6 failed; five link cases and one player case, all
fixed here), and the `[Errno 107]` branch in `a_failed_connect_leaves_an_unconnected_socket`
was written **after** that read and has not been re-run on Linux.
Out of scope deliberately: macast-core's `net.rs:25 unused import: BTreeMap` Windows warning
(a different crate, and its own comment says a Windows interface table without it is
harmless), and the six pre-existing rustdoc "links to private item" warnings — `cargo doc
--no-deps` reports **0 unresolved links**. No Linux container run was done for this round
(2026-10-06 ruling: Linux verification is off my side, CI untouched). `cargo doc` aside, the
Honesty boundary now lives in `lib.rs`: the Unix sentences were measured on this Mac and read
off a Linux run, while the Windows column is a port that no machine here has exercised.
Two things this round had to unlearn before they became prose: an earlier Windows check
looked clean only because `#[cfg(unix)] pub mod link;` meant `link.rs` never compiled at all,
and `link.rs` used to credit the player's Windows tests with a fake mpv that hands out a new
pipe instance per connection — no such fixture exists, so that claim is now "no machine *and
no test* asks this; untested". A Windows case that calls `terminate`/`force_kill` with a
synthetic pid was considered and rejected: pid reuse makes a fixture that could kill
something real, and the reason sits in the Unix module's gate comment so nobody re-adds it.
Not pushed: `.github/workflows/build.yml` triggers only on `main`, `v*.*` tags, and PRs into
main, so this branch has never had a CI run and pushing it would be an unprompted first one.
…essed, v0.1.0 `src-tauri` was a crate that existed but could not be started: `build.devUrl` pointed at a Vite server that no commit ever added, so `tauri-build` compiled the `cfg(dev)` branch, the debug binary looked for `http://localhost:5173`, and the window never opened. Deleting that one key makes `frontendDist: "../frontend"` the source of truth, so the debug binary renders the page with no dev server at all. This is the change that makes the branch's program *run*: `target/debug/ macast-tauri` opens a 1100x760 `Macast` window on macOS. `src/host.rs` (new) is the crate's first real implementation of `macast_mpv::player::Host` — before it, the only implementors in the tree were `macast-mpv`'s own test doubles. It ports `DLNAProtocol`'s state table (boot values, `set_state`'s compute-`changed`-first gate from §4.2's "状态变了才广播", the playlist/`NumberOfTracks`/`CurrentTrack` derivation) and `DLNAHandler.cast_uri` (`protocol.py:1163-1201`) as one ordered sequence whose steps are named rather than implied. `_add_history` is deliberately absent: §10 forbids writing to the user's settings file from a verification path, and the omission is a recorded gap, not an oversight. The controls answer with a witness instead of a promise. `pause`/`resume`/ `stop_playback`/`set_volume` publish the command, then poll the table for up to `ACK_SETTLE` (400 ms, `ACK_POLL` 20 ms) and report `settled: true|false` beside the state they actually read back, so "the page said PLAYING" and "mpv agreed" are no longer the same sentence. Step 8's `PLAYING` in `cast_uri` is *not* witnessed — and the comment now records why that is parity rather than a porting gap: `protocol.py:1199` writes it from the requesting thread with no mpv confirmation, the only correction is `playback-restart` reading `self.pause`, and `mpv.py:291-292` drops a pause that arrives before `start-file`. Measured on this machine and identical in the Python app; left as-is because this port's contract is the reference's contract, not a better one. `capabilities/default.json` (new) grants the page exactly `core:event:allow-listen` / `allow-unlisten`: `Host::publish` is the only thing that reaches it from the backend, and the page never emits. The eight commands are this crate's own and need no entry. Verified on macOS, not inferred: the window renders and updates; a cast of `/tmp/macast-tauri-verify/clip.mp4` titled 只此一遍 reads 窗口标题 '只此一遍' / TransportState 'PLAYING' / 位置 '0:00:03 / 0:00:30' on the page, while an independent mpv IPC read of the same player gives media-title and force-media-title both '只此一遍', path = the clip, time-pos 17.8 -> 19.8, duration 30.0, pause false, volume 80.0, core-idle false, track-list h264+aac. `cargo build --workspace` clean; `cargo test -p macast-mpv --lib state::` 18/18. Windows/Linux and any bundled `.app` are out of scope here and untested. Co-Authored-By: Qoder <[email protected]>
…nto its own directory
`macast-upnp` (new crate, workspace member) is `macast/ssdp.py` + `macast/Sock.py`
ported: `register`/`unregister`/`alive`/`notify_message`/`search_reply`/`do_notify`/
`is_healthy`, the M-SEARCH decoder, the entry store, and the device description side.
Every wire shape is the Python one, not a cleaner Rust one, because the senders out
there judge us by those bytes:
- `register()` writes USN, LOCATION, ST, EXT, SERVER, CACHE-CONTROL **in that order**,
and `nt_form()` copies every header *except* `ST` and then appends `NT` — because
Python's `nt_form` does `del` (which leaves the dict slot alone) followed by a fresh
assignment. Insertion order is the contract, so it is asserted as one.
- `search_reply()` ends with `\r\nDATE: …\r\n\r\n`, which is why a 4-header entry
splits on `\r\n` into **8** pieces, not 7. That number was measured, not derived.
- `is_healthy()` answers *healthy* for a server that was deliberately stopped
(`!running` ⇒ `true`): a stopped receiver is not a fault. §4.2's "别把端口在听当
证据" is the reason the second question is `alive`, not the socket.
- The multicast group is `239.255.255.250` and `group_destination()` is derived from
it, so the two can never disagree.
`Sock::new` follows Python's order — create, set `SO_REUSE*`, **then** bind UDP/1900.
`std::net::UdpSocket` cannot express that (binding is how you get the socket), hence
`socket2`, which was already in this graph at 0.6.5 through tokio/hyper-util; naming an
older one would have put a second copy of the same library in the tree to buy one
setsockopt. `libc` covers `IP_MULTICAST_IF`, which wants an **interface index** on
Darwin/BSD and an **address** on Linux — a difference the port keeps rather than smooths.
The harness contract is a test, not a habit. `cfg(test)` does **not** propagate to
dependency crates: `macast-core/src/paths.rs` guards its scratch fallback with
`#[cfg(test)]`, so when this crate's tests build core as a normal dependency that arm is
compiled out and `paths::log_file()` resolved to the user's real
`~/Library/Application Support/Macast/macast.log`. Two damages, same root: AGENTS.md §10
(verification must not touch the user's configuration) and repeatability — the needles
are unique *within* a run and identical *across* runs in an append-mode file, so every
`lines.len() == 1` adjacency witness failed from the second run onward (14 red). The fix
is `pin_test_dir()` (`lib.rs`, `Once`-guarded ⇒ `temp_dir()/macast-upnp-test-<pid>`,
`remove_log_files` first so a reused pid cannot inherit the previous run's lines, then
`set_setting_dir_override`), and it is the **first statement of every test**, which is
what makes ordering deterministic: whichever thread logs first has already pinned the
process-global `OnceLock`. `every_test_pins_the_log_directory_first` then scans this
crate's own `src/*.rs` and fails if a future test is added without it, with a
non-vacuousness count (`scanned >= 60`) because a scan that found nothing agrees with
anything. That pattern is the repo's own (§4.2, "免得扫描本身空转").
Verified on macOS. `cargo test -p macast-upnp`: **79 passed / 0 failed** on three
consecutive runs and under `--all-targets`, no `dead_code` or unused warnings;
`cargo check --workspace` finishes clean. Nine targeted single-file mutants, one per
command, each with a `cp` backup + EXIT-trap restore + md5 comparison against the
baseline (every restore returned the baseline digest), went red **1 / 1 / 1 / 1 / 2 /
1 / 1 / 3 / 1** — including "ignore `running` in `is_healthy()`", which is red in two
files at once, and "log after the lookup in `unregister()`", which proves the log-witness
mechanism itself has teeth. Two mutant patches initially silently no-op'd (wrong indent;
wrong assumed one-line `fn x() { pin();` style) and the green 79/79 that followed an
aborted patch was thrown away rather than recorded — a run whose patch didn't apply is
not a measurement.
What this does **not** claim:
- `start`/`run`/`shutdown`/`run_thread` bind UDP/1900 and `Sock::send_it` multicasts onto
the real LAN, so no test calls or installs them. Five branches are therefore gaps with
comments, not assertions: `do_notify`'s "sends twice", the subnet loop's `break`,
`run_thread`'s generation claim, `py_repr`'s unreachable `\U` arm, root-vs-module
logger routing. `is_healthy()`'s "bound but dead" half is reached by hand-setting the
flags — `stop()` is never called while `running` is true.
- Windows and Linux are **compile/typecheck only**, per this branch's standing rule.
- `cargo clippy` is not installed for `stable-aarch64-apple-darwin`, so that check was
not run and is not reported as passing.
- Coverage is thin in two named places: `nt_form`'s ordering and the multicast group each
have exactly **one** witness.
- Side effect already on disk, disclosed rather than cleaned by hand: four test lines
were written into the user's real `macast.log` **before** the pin existed (file 422,974
bytes, unchanged since; `grep -c "urn:e-register-target"` = 4). §4.10 means the next app
start clears them; nothing else in his configuration was touched.
Part 64's Python precedent (§4.2) is why the ordering and the three-state readings get
this many tests: the shape that "looks like a file" is what a real sender rejects.
…ck tile Macast is a menu-bar receiver: the Python bundle says LSUIElement = true and every mpv child it spawns runs with --macos-app-activation-policy=accessory. The Rust shell carried neither, and tauri.conf.json declares a normal window, so each `target/debug/macast-tauri` run checked into LaunchServices as a *foreground* app. A bare Mach-O has no bundle of its own, so LS attributes it to its responsible process — when the run comes from an agent shell that is Qoder — and the Dock shows another tile wearing Qoder's icon, one per run. Measured on this machine, both directions: without the line the shell's own ASN reads type="Foreground" with originalExecutablePath=/Applications/Qoder.app/… and the Dock gains exactly one "Qoder" item; with it the ASN reads type="UIElement" and the tile does not appear. The mpv child was already accessory (macast-mpv/src/argv.rs), so only the shell needed this. set_activation_policy rather than set_dock_visibility because the latter goes through tao's DockHide/DockShow path, which is the one documented to leave stale tiles behind when it cycles quickly (tao 0.37.1, dock.rs).
…n the one that is filled in
Task #13's first two modules land in `macast-upnp` (no new crate): `scpd.rs` is
`macast/protocol.py:490-600` + `:650-659` + `:661-731` (`DataType`, `StateVariable`,
`Argument`, `Action`, `Service`, `init_state`, `init_services`, `build_action`) and
`description.rs` is `build_description()` (`protocol.py:3131-3144`) — the template read
plus eleven substitutions. This is the half of the DLNA face a control point judges us
by before it sends us anything, so the shapes are the Python ones, not cleaner Rust ones.
`scpd.rs` keeps an arena DOM with lxml's five navigation rules, because two of them
decide what we read out of a real document: `iter(tag)` includes the node it starts at
while `find`/`findall` see direct children only (`init_services` uses the deep form,
`build_action` uses both), and `.text` is the characters *before the first child* — a
reader that concatenated all text would turn `<a>before<b/>after</a>` into `beforeafter`.
`<step>` inside an `allowedValueRange` is never read, so `CurrentTrack`'s range is the
bare pair `0..65535`, and a `<direction/>` with no text is `None` in Python and therefore
lands in **output**; both are reproduced rather than "fixed".
The two golden files are what makes that a measurement instead of a reading:
`tests/golden/scpd_state_table.json` and `scpd_actions.json` were dumped by running the
**real** Python (`DLNAProtocol.__new__` + `init_services()`) against these same four XML
files. Two facts only the golden could catch: the flat state table is **48 rows from 50
declarations** because `LastChange` and `A_ARG_TYPE_InstanceID` are declared twice and the
later service overwrites the earlier *in place*, keeping the earlier position; and that
same collapse is why `src-tauri`'s `host.rs` `DECLARED` row order is now `Description.xml`'s
`<serviceList>` order (AVTransport, RenderingControl, ConnectionManager) instead of the
order someone opened the files in — `scpd.rs` compares the two tables **as ordered lists**,
so a re-sort is real drift, and the doc comment now says so.
`description.rs` emulates `str.format` for the shapes this template can hold, and the rule
**order** is measured against `python3` on this machine rather than recalled: the argument
name is scanned up to the first of `.` `[` `!` `:` `}` with nothing trimmed (`{ :>3}` is
`KeyError: ' '`, not a complaint about padding), the name is resolved **before** any spec,
conversion, attribute or index is interpreted (`{nosuch:>10}` is `KeyError: 'nosuch'`, so a
reader is sent to the right character), an unmatched `{` inside a name is
`ValueError: unexpected '{' in field name` while running out of string is
`ValueError: expected '}' before end of string`, and an empty or all-digit name is a
**positional** field ⇒ `IndexError` naming the slot counted. Refusing the last group is a
deliberate deviation (Python renders them) and it is provably unreachable, which is what
`the_template_holds_exactly_the_eleven_fields` is for: it walks `TEMPLATE` itself and
panics on a `}}`, a `{{`, or any field asking for a spec. Measured template facts pinned as
assertions: 2186 bytes, exactly the eleven named fields, each once.
Byte-for-byte agreement with the shipped receiver is checked against a witness produced by
the Python call site (`tests/golden/description.probe.xml`, 2195 bytes) with the probe's
uuid / friendly name / version pinned, and the two empty extras are asserted to leave
line 20 as eight spaces and line 44 as twelve. `TEMPLATE` is asserted to be the *same
`include_str!`* `scpd.rs` reads (`std::ptr::eq`), because two copies of two files look
identical until a control point asks. `Err` from `build()` is the adoption decision made
explicit: Python raises before assigning `self.description`, so it keeps serving the old
bytes silently.
Verified on macOS: `cargo test -p macast-upnp --all-targets` = **130 passed / 0 failed**
(79 before, +33 `scpd` +18 `description`), and `cargo check -p macast-tauri --all-targets`
is clean after the `host.rs` reorder. Every new test opens with `crate::pin_test_dir();`,
and the crate-wide audit's non-vacuousness floor (`scanned >= 60`) still holds with these
51 added.
What this does **not** claim:
- No mutants were run for this stage. The green 130 is a pass, not a demonstrated-teeth
measurement; the mutant discipline from §4.2 belongs to the stage that has an action
dispatcher to break.
- `cargo clippy` is not installed for `stable-aarch64-apple-darwin`, so it was not run and
is not reported as passing.
- Nothing here touches a socket. The HTTP face, SOAP dispatch, and GENA are still to come
(`http.rs` / `soap.rs` / `eventing.rs`), so the module names `scpd.rs:44-45` and
`store.rs:97` already promise in their doc links do not exist yet and the crate still
compiles only because those links are doc-only.
- `description.rs` refuses format specs by design; that is safe **today** only because the
inventory test asks the file. If someone edits `macast/xml/Description.xml` to use one,
the refusal is a red test, not a served document — by design, but it is a red test rather
than a rendered answer.
- Windows and Linux remain compile/typecheck only, per this branch's standing rule.
… store keeps the playlist position `soap.rs` reads a sender's DIDL-Lite, and the two questions it asks are not answerable through the accessors the arena had: "what was this prefix bound to *on this element*" (lxml's `meta.nsmap['dc']`) and "walk every node under here whatever namespace it arrives wrapped in" (the `res` search). Namespace declarations are dropped from `attrs` by name resolution, so they now live on `Node.prefixes` and are read by `Dom::binding`; `iter_all` is the no-filter walk next to the tag-filtered `iter_subtree`. Two tests corrected what the doc had promised: quick-xml refuses a duplicated attribute outright, so `binding`'s later-wins rule is only reachable through an ancestor and a descendant that re-declares, and `Dom::find` answers direct children only. Both say so now, in the doc and in the test. The store gained the two things the handlers write besides state: the playlist index (mpv.py is the other writer, so it is stored and not derived from `CurrentTrack`), and `set_media_position` taking the sender's text instead of a float — mpv v0.41.0 accepts `00:01:23` and rejects nothing about it, but `seek 83` is an accepted argument with no meaning we intended.
…a judge
`set_state` in Python asks one question before it decides who hears about a
value ("did it change?"), and then answers a second one that the state table
knows nothing about ("does anybody subscribe to this name?"). With the queue
still unwritten, the crate needed a place to hand that second answer to without
letting the store start owning subscribers: `Broadcast::enqueue`, plus the
`SharedBroadcast` alias the other three seams already have.
The trait is ungated on purpose, and the doc says so in the same breath as the
92%: one user's log carried 505 duration reports, 464 of them for a number that
had not moved (AGENTS.md §4.2, "状态变了才广播"). A store method that enqueued on
every write would reintroduce exactly that, and a store that also held a
subscriber list would be a second owner of the fact this module's header is
written around. So the gate lives at `crate::soap`'s call site — the only place
with both the boolean and `is_observed` in hand — and the new test refuses to
assert it here, because re-implementing the condition in the file under test is
the shape of check AGENTS.md §4.13 calls 不提问的检查. What it can hold honestly
is that `dyn Broadcast` stays object-safe behind the alias, and that an
implementation which rewrote the value on the way to the queue would make every
GENA event report a number the control point never asked about.
…changed state is announced
macast-upnp/src/soap.rs is the control face: it reads a SOAP envelope the
way DLNAHandler.call() does (normalize, parse, take the first str-tagged
child as the action, derive the service from the namespace by splitting it
and taking the second-from-last segment, then read each parameter by its
local name with the node's *text*), and it answers with the same
{service}_{action} dispatch table, the same noisy-response skips, and the
same Python str() shape on the wire — not repr(), because the measured
399-byte GetTransportInfo witness says STOPPED without quotes.
Nine writers, no readers of our own: every Get* takes the read branch out
of the state table, so the handlers that actually move playback are the
only place a value is written. set_state() computes `changed` before it
touches the queue, and enqueues only when the value changed AND the name
is observed — the two halves of that gate each have a witness in
next_and_previous_walk_the_queue_and_stop_at_both_ends, because a suite
that only proves the first half passes when the gate is deleted. This is
AGENTS.md §4.2's measurement (464 of 505 duration reports said nothing
new) carried into the Rust port rather than re-derived later.
Deviations are a table in the module doc, not a rumour: all refusals become
SOAP faults at HTTP 500, Seek sends "" where Python sends JSON null
(unmeasured against a real sender), and the CurrentTrackMetaData we keep is
the sender's own text rather than lxml's re-serialization.
…eal socket The module arrives with its own tests: verbs, head scanning, the four broken shapes, redirect semantics, SCEDP description and SCPD serving, the POST routing table, gate refusals, the GENA subscription ring, and five tests that hold a real listening socket and speak real HTTP into it. One source fix rides along: py_json_quote left every printable ASCII character escaped, which is not what Python's json.dumps does — printable ASCII now stays raw, exactly as the docstring always claimed.
…t observes a variable is told
…re it lights them up `main.rs`'s `.setup()` now builds the whole receiver — the GENA eventing service, the embedded SCPD, the SOAP control face, the HTTP face that serves them, and the SSDP announcer — and starts the four of them *after* the `Runtime` is managed. Both halves of that ordering are load-bearing, and each is written down where it can bite: - Construction happens before `player.start()`. `Scpd::embedded` and `Face::new` can refuse, and a `?` that fires once the mpv child exists leaves an orphan on the machine — the failure AGENTS.md §4.2 counted as 「被反复重启的 Macast 会攒播放器」. Refusing here costs a window, not a process. - `app.manage(Runtime)` happens before every `.start()`. `ssdp.rs`'s UDP/1900 bind failure publishes a notification and spawns a thread that calls `Hooks::stop_service`, and that method resolves the services through `try_state::<Runtime>()`. Managed last, it finds nothing, the flag becomes the only record that the request happened, and the port stays held by a server nobody can stop. `host.rs` carries the four seams the receiver calls back into: `StateStore` (the table answers read/snapshot/playlist, and broadcasts only once its broadcaster is bound — the guard goes down before `enqueue`, so a dead subscriber can never sit on the state table, which is §4.2's copy-on-write rule for the subscriber list arriving on this side), `Renderer` (delegated to the one player this shell has, and the liveness seam keeps the reference's name rather than `set_media_*` so no plugin bus enumerates a message nobody sends), `Hooks` (`stop_service` stops the receiver and lets mpv keep playing what it was handed — that is what "the service stopped" reads like to a user: the phone no longer finds Macast, the window it opened stays open), and `Broadcast`. Two commands ride along so the history the table now keeps is reachable from the page: `player_snapshot` reports it newest-first, deduped, capped at 50, and `clear_play_history` is the only way its row count can go down. The startup line reports the answer rather than the ask — `is_running()` from the HTTP face and `is_running()` from the SSDP server behind the plugin, plus the port actually bound. The GENA thread is not mentioned at all: it exposes no query, and a line claiming it started is a claim no machine was asked to check. Verified: `cargo build -p macast-tauri` is warning-free, `cargo build --workspace --all-targets` prints neither warning nor error, and macast-upnp's 266 tests still pass. Not verified: this receiver has never answered a real control point — on this machine ports 1900 and 58880 belong to the user's running Python instance, so the whole face has only ever been spoken to by its own unit tests.
… and a real control point now says so The one window the reference never had to answer. Its `mpvipc_start` subscription is armed only by `reload()`, so a SOAP hand-off that arrives while the ipc thread is still in its first connect writes to a `None` socket, logs `sendCommand: 'NoneType' object has no attribute 'sendall'` five times, and is never loaded — AGENTS.md §4.1's 「连上了但什么都没播」, with the mpv half of it living here rather than in the renderer. `Player::set_media_url` now parks the url in `Shared::pending_reload` when the link slot is `None`, and the connection that is on its way spends it. The slot is armed **before** the send is attempted, not after it reports the drop: a connect landing between the dropped write and a later arm would find nothing waiting, and losing the media is the failure this exists to end. Worst case of the chosen order is that both that reconnect and this call load the same url — a reload of a file that was about to play, not a cast that never plays. The dropped write keeps logging: the replay is a recovery, not a reason to hide the race. Two tests, the second one there to keep the fix from becoming a retry loop: the pre-connect cast is replayed in the load-bearing order (media, then the name twice, then the session's ten observations — §4.2 命名接缝), and the slot is spent by the connection that read it; a hand-off that reaches a live socket is delivered once and holds nothing, and the second session of the same process writes its own setup without re-loading it. scripts/verify_rust_receiver.sh is the harness that makes this answerable on a real machine instead of only in the unit suite, which stubs the network: temp MACAST_SETTING_DIR, its own MACAST_MPV_SOCKET, port 58999, reap by socket path (never a bare pkill), setsid-detach so mpv outlives the shell, and a pre-flight refusal before the trap is even armed because this receiver refuses a busy port rather than moving. It announces a second Macast on the LAN for the length of the run — do not start it during a demo. f051daf claimed this receiver had never answered a real control point. That claim is now superseded, on this machine, six checks green: an SSDP M-SEARCH from the live LAN answered 200 with USN/LOCATION/ST in the reference's header order, a real `SetAVTransportURI` returned 200 with a response body, `GetTransportInfo` reached PLAYING, `GetPositionInfo` read back the DIDL `dc:title`, and a subscribed control point received a GENA NOTIFY carrying a LastChange with its Sid. The kept logs/MPV.log is the before/after witness for the fix: five NO_SOCKET ERRORs at 19:33:26,453, 「mpv ipc socket start connect」 at ,488, `start-file` at ,489 and then audio-reconfig / file-loaded / video-reconfig / playback-restart — previously nothing reached `start-file` and check #4 hung on PAUSED_PLAYBACK. Port free after teardown; the user's real macast_setting.json untouched. macast-mpv --lib 147 passed, macast-upnp --all-targets 266 passed, cargo build zero warnings.
… its clear 后端早有 `player_snapshot` 的 history 与注册好的 `clear_play_history`, 缺的一直是页面这一半。行用 createElement + textContent 建:标题来自控制点 的 DIDL,与日志面板是同一道 XSS 红线。列表按快照签名短路,否则每 1.5 秒 的轮询会在鼠标点击之前把那一行换掉。
…A, and its gates keep the secret GET /api?query=cast is the one door left open for scripts, shortcuts, and bookmarks, so it takes the token even from loopback: any web page can POST at 127.0.0.1, and "local" carries no information once DNS rebinding is on the table. cast-info mints and reveals the secret, so it sits behind the management gate and a LAN caller never hears it. The gate a route ran is data, not a branch — which refusal sentence arrives is the only outside witness of that, so a route cannot write its own apology.
…twork card without freezing Three cards were still missing from the settings window, and building them exposed a deadlock: Eventing::subscribers() read one field of a client through a lease guard and asked its siblings through their own guards, so the first non-empty subscriber table self-blocked the non-reentrant Mutex forever. A synchronous Tauri command runs on the main thread and the page polls every 5 s, so a phone subscribing froze the window and its AX tree while HTTP kept answering — HTTP liveness is not evidence the main thread is alive. subscribers() now binds published() once and takes each lease once per row. The live witness is a real GENA subscriber rendered in the running window. The NIC picker's unknown-name refusal moved into net::pin_refusal so the Chinese sentence has one owner and is testable; src-tauri has no test harness and building a fake Runtime state to assert a format! is not proportionate.
Cast's LOAD puts a position in `currentTime` and hands it to the player together with the address (`macast/protocol_cast.py:995`), while DLNA's `SetAVTransportURI` has no such argument. So `Renderer::set_media_url` now takes `start: Option<&str>` and both callers say which one they are. `None` is not a third behaviour: the reference's own default for the parameter is `"0"` (`macast/renderer.py:76`), and the loadfile builder drops a position that is empty or `0`, so the mpv command keeps its bare three-element shape either way. `Player::set_media_url` already took the argument; only the trait had not caught up. The test double records `start=` only when it was given one, which keeps the three existing assertions in `soap.rs` asking about the address alone — that is the point, since the DLNA path never has a position to hand over.
… a half-frame macast-cast is a new crate, and this step gives it only the protobuf layer: the frame header, the two encoder/decoder pairs, the device-auth answers, and the namespace table. Everything here is measured against macast/protocol_cast.py's codec region, not argued from the schema -- the two frame fixtures are the reference's own bytes re-asked from Python, and the lossy-UTF-8 rows are its replace-broken-bytes behavior reproduced. Two deliberate divergences, each marked at its own site: a varint counter that runs past 64 bits keeps its low 64 bits (Python accumulates in arbitrary precision, and only those bits are ever read here), and a field number above 31 is refused with an assert instead of wrapping to a zero tag. The decoder copies the reference's rude answers exactly: an unsupported wire type ends the read without an error, a truncated length yields a clamped slice, and a message that carries field 5 as LEN-encoded leaves payload_type at 0. One malformed frame must not kill a client loop. 18 tests, all pinned to a temp log dir first, and the suite's floor constant is this crate's own measured count. Two mutations were run singly with md5 verified restore: swapping the two payload slots reddens 4 tests, and emitting bare-string namespaces reddens exactly the shape test.
… and never overwritten cert.rs is the second layer of macast-cast. It generates the self-signed pair with rcgen instead of shelling out to openssl, so the Cast receiver comes up on a clean machine that has no openssl on PATH — which is the shape Python's `_ensure_self_signed_cert()` never had, and the reason the first真 TLS failure in this project read like a protocol bug. Three promises, each with a witness: - adoption asks only whether both files exist. A pair we did not make is reported by name and its bytes stay on disk; validation is deferred to `Pair::server_config`, which is also the reuse path's only reader. - the code that writes a file is the code that makes the directory (AGENTS.md §4.2), and that is now tested in both directions: the failure names the directory, and a two-level path nobody created actually gets created. - the subjectAltName carries `localhost` as [2] dNSName before 127.0.0.1 as [7] iPAddress, DER-tag and order both read back from the bytes rather than restated from the const. Dependencies arrive with the layer that needs them: rustls (ring, std, tls12 — one provider, and senders offer TLS 1.2), rustls-pemfile, rcgen, and the two workspace crates the receiver talks through, macast-core for the `Chromecast` log module and macast-upnp for the `store` traits. The pin-audit floor moves to 30. Mutants, one per command, each restored md5-identical: flip the SAN order 1 red, delete create_dir_all 2 red, drop the CommonName 1 red, generate into the cast slot 5 red, make adoption validate 3 red.
…and never trusts a dead watcher The Cast v2 face over TLS: the accept loop that never gives up its listener for one bad handshake, the sender and session ledgers under one lock, both status faces with the reference's key order byte for byte, the three-state liveness the sender declares, LAUNCH_ERROR with a next step, and the watcher that reports PLAYING only after the shared state table confirms it — plus the end-to-end TLS exchange pinned over a real socket on an OS-assigned port.
… brackets and session parameters, and refuses to load without a Content-Location
…mits by table, and answers byte for byte over 325 differential cases macast-cast/src/resolve.rs is the port of `macast/media_resolve.py`'s non-network half, and every line of it is pinned to what CPython answers on this machine rather than to what the port looks like it should do. What lives here: the Python-shaped URL reader (`urlsplit`/`urljoin`/ `urlunparse` with the netloc checks and the IPv6 brackets, so `absolute_url` breaks an address exactly where `urljoin` does), share-text extraction (the character class that stops at full-width punctuation, the 9-character `rstrip` tail, and the whole-text-first rule behind `looks_like_url`), the cookie-browser grammar `BROWSER[+KEYRING][:PROFILE][::CONTAINER]` read per the engine's own syntax, `json_unescape`, header normalisation (drop what cannot be forwarded, stringify scalars the way Python str() does), `first_line` over Python's line-boundary set with the 200-character clamp, ffprobe probing in its three states, the engine's format ladder (kind, bitrate, audio codec, pairing video rows to the best audio row), the ordered admission table with its two counts, `preference`/`rank` under the measured ceiling, and `visible_rows` handing the silent half to the card as a sentence rather than a row. Proof: a Python oracle rendered 325 case answers over the corpus, and the crate tests compare against that file and nothing else — expectations were copied out of `/tmp/mr5_truth.txt` by a generator, never typed from memory. The 22 family tests are self-contained: the fifteen fake ffprobe scripts they need are written into a per-process temp directory by the test binary itself, so no test depends on a leftover `/tmp` tree, and the probe cases still answer in all three states (measured / refused / unreadable) including the timeout and the 201-character stderr that clamps to 200. `cargo test -p macast-cast --lib`: 167 passed, 0 failed. The crate's new dependency is `regex` and nothing else: the three patterns here are match questions, not parse questions, and the page fetch that would need an HTTP client is a later sublayer.
…, keeps the title the parser never flushed, and answers byte for byte over 263 differential cases This is `macast/media_resolve.py`'s scraping half: the stdlib HTMLParser port (`html.rs`, callbacks and the `convert_charrefs` buffer boundary), the entity table and the two CDATA modes (`entities.rs`), the charset side (`charmap.rs` with CPython's alias resolution and its three-state answer, `gbk.rs`/`cjk.rs` with the generated double-byte tables), and the seam that puts them together — `PageParser`, `meta_og_video`, `literal_urls`, `fetch_page`, `decode_body`, `utf8_replace`, `scrape_page`. The one thing worth reading twice: `scrape_page` feeds the parser and **never closes it**, and the reason I first wrote down was wrong. I had claimed closing would invent candidates the reference does not have. Measured instead — `parse_starttag` returns -1 whenever `check_for_whole_start_tag` cannot see a whole tag, **even at `close()`**, so a page cut inside `<video src="…` leaves that attribute unsampled either way. What `close()` does flush is buffered character data, and `<title>` is the only data this function reads, so the load-bearing shape is a page that ends inside its title. Both shapes are now in the corpus: of the eight truncation rows `sp_10`–`sp_17`, six gain a title the reference never had and two (`sp_13`, `sp_14`) answer identically either way, which is the documentation of the claim I started with. That correction exists because the mutation did not. Inserting `parser.close()` into `scrape_page` first turned **zero** tests red: none of the ten bodies in the corpus ended inside a construct. An unchecked check is a passed check, so the corpus got the eight oracle-backed rows before the claim was restated. Proof: every expectation is copied mechanically out of `/tmp/mr8_truth.txt` and `/tmp/mr11_truth.txt` (263 scrape-side rows: `parser` 101, `og` 101, `lit` 19 of 20, `scrape` 18, `dec` 22, plus `lab` 1023 and `rep` 476), rendered by CPython 3.12.15 on this machine by `/tmp/mr8_oracle.py` and emitted by `/tmp/mr12_gen.py`; nothing was typed from memory. Three Python shapes have no Rust spelling and are skipped rather than faked, each named in the generated header: `parser.exc` is always null, `lit` i=7 is `None`, `dec` i=999 is the `isinstance(raw, str)` branch. Mutations, one command each, restored and md5-verified (M7's first attempt did not compile — `String::from_utf8` wants a `Vec`, so it was re-run as `raw.to_vec()`): collapsing `charmap_for(other)` to `Some(Err(()))` 2 tests; `utf8_replace` to `from_utf8().unwrap_or_default()` 2 (`dc_09`, `rp_128`); `resolve_codec` answering utf-8 for an unknown label 2 (`cl_037`, `cd_1243`); `parser.close()` 1 test — the six rows above, counted by temporarily collecting mismatches instead of asserting on the first. Earlier ones on this sublayer (`_MetaAttr` quote requirement, `take`'s missing `break`, `TITLE_MAX_CHARS`, stem-without-fragment) went red 1/2/1/2. `cargo test -p macast-cast`: 175 passed, 0 failed. The Python suite was not run, per standing instruction. New dependency: `ureq` (rustls-no-provider + ring, no gzip/brotli/charset) for `_fetch_page`, the one place the receiver is an HTTP client. `encoding_rs` is deliberately **not** a dependency: replaying every lead/trail cell of the four double-byte families through it diverges from `bytes.decode` (big5 5,144, shift_jis 2,795, cp932 841, gb18030 21 of 32,386 cells per family), so the tables are generated from this interpreter and re-measured over 505,120 worded rows with 0 divergent.
…gv, keeps a table's row order load-bearing, and answers all 601 differential rows This is `macast/media_resolve.py`'s engine-answer half: `cookie_arguments` and `ytdlp_command` (the argv the process is actually handed), `engine_note` (what the card reads back from a failed run), `needs_cookies` and `engine_says_unsupported` (the two word tables that must not borrow each other's answer), `cookie_source_problem` (the four states that are *our* side rather than the site's), `cookie_jar_state` (what the reference counts as a cookie line), and `timeout_sentence` (the string a `TimeoutExpired` would have printed). The one thing worth reading twice: `cookie_arguments` asks `cookie_browser_spec` **on the way to argv**, and strips `cookies['file']` **before** it decides whether the file wins. Those are not stylistic. 52 of the 294 grid rows hand this function a non-empty browser spec that the whitelist refuses -- `chrome+GNOMEKEYRING`, `chrome::2`, `-framing` -- and the reference answer is `[]`: a spec this layer refuses produces no switch at all, so a save-time-only check would put a switch in argv that the reference never emits. And 96 rows carry a whitespace-only `file`; unstripped, the first of them becomes `['--cookies', ' ']`, i.e. the jar wins over a browser that was asked to answer. The second thing that only looks like style: `not_found`'s word list contains the singular `cookie database`, and that fragment sits **inside `locked`'s own sentence**. `prob` row 4 is the witness -- "could not copy chrome cookie database and it also says cookies database" -- so `cookie_source_problem` must walk `locked` first or a locked browser is reported as a missing one. The order test used to ask only that the tuple equals `COOKIE_PROBLEMS`; it now asks the table it walks to be in that order too, **and** that at least one recorded `locked` probe genuinely contains a `not_found` fragment. The row order's witness is a row, not a sentence in a comment. `timeout_seconds_text` is one line and used to be two branches. Deleting the whole-seconds branch turned **zero** tests red across the 41 recorded sentences -- Rust's `Display` for `f64` already prints `120`, so the branch bought nothing -- and it is gone. `as_secs_f64` -> `as_secs` then reddens row 36 (0.5 s), so the line that remains is asked by the corpus. Honest hole: shortening the private `const LIMIT` alias inside `engine_note` to 100 reddens only the note grid (1 test). `engine_note_clamps_at_the_limit_the_corpus_measured` pins the public `ENGINE_NOTE_LIMIT`, not the alias -- so the alias is asked by the answers, not by the name. Proof: all 601 rows of `/tmp/mr14_truth.txt` (md5 `9ef5ee3ce791433b3005409857e2dd00`) are this layer -- `arg` 294, `note` 145, `tout` 41, `prob` 32, `cmd` 30, `jar` 23, `needs` 20, `unsp` 14, `toutx` 2 -- rendered by CPython 3.12.15 through `/tmp/mr14_oracle.py` and emitted mechanically by `/tmp/mr14_gen.py`; nothing was typed from memory. Four shapes cannot become an assertion, each named in the generated header: **there is no sink family** (the oracle's `subprocess.run` stub answered a normal `CompletedProcess`, so `sink_note`, `python_error_name` and `ytdlp_candidates`'s error path keep only their doc comments as witness -- the argv they hand over *is* asserted by the `cmd` rows); `arg` 291 collapses `browser=None` onto `""` with no twin row, so that one rests on Python truthiness; `note` 0 is `None`, asserted once rather than duplicated across the grid; and `toutx`'s two rows are asserted **as divergences** -- CPython prints the float it was given (`120.0`, `1e-07`), we print `120` and `0.0000001`, and a green equality there would mean the test had stopped asking. Mutations, one command each, restored and md5-verified (`ac28cf954280fdafb416aca0465d05a1`): not stripping `cookies['file']` before the emptiness question 2 tests; emitting the browser switch without re-checking the spec 2; dropping the `--cookies` branch 2; reading `engine_note`'s first line instead of the `ERROR:` marker 1; shortening the private `LIMIT` 1; dropping a word from `needs_cookies`'s table 1; swapping the `locked`/`not_found` table rows 2; not stripping `#HttpOnly_` 1; measuring the jar cap in characters instead of bytes 1; adding `unable to extract` to `UNSUPPORTED_WORDS` 2; joining argv with spaces instead of Python's list repr 2; deleting the whole-seconds branch 0 (which is why it was deleted); `as_secs_f64` -> `as_secs` 1. `cargo test -p macast-cast`: 192 passed, 0 failed -- 17 of them this generated differential. The Python suite was not run, per standing instruction.
…rs, finishes after refusal, and answers all 162 differential rows
…uses to answer 200 before the first byte, and translates the viewer's Range to the origin
编码那一半在 nva_frames.rs,这是反方向,而它多一条性质:**必须扛得住分片到达**。 三条行为各自看起来像 bug,都是参考实现的原文: - **半个帧不是错误,是"等下再来"**。TCP 给的是缓冲区里恰好有的东西,所以循环在第一个 装不下的帧处停下、把剩下的留在 cache。把这报成 malformed 会让每个大载荷都掉一次连接。 - **起不了帧的字节只前进一格**(`index += 1; continue`),所以从帧中间开始或掺了垃圾的流 会**在下一个像样的头部重新同步**,而不是把后面全部丢掉。 - **体不是 JSON 时回调不触发,但帧仍然算消费掉了**。参考实现的 `index += …` 在 `finally` 里;不前进就会在同一批字节上死循环。 差分语料 tests/golden/nva_decode.jsonl,8 条流由执行参考实现的 parse_request(带记录的 回调)生成:整帧、逐字节、前置垃圾、中间夹 PING、非 JSON 体、坏 flag、跨两次读。 **比的是事件不是字节** —— 同样的字节解出不同的回调仍然是错的。 语料当场抓到我一处真偏差:`bad_json` 那行我给了一个 `body: null`,而参考实现**一个回调都 不触发**。于是加了 `Decoded::Unreported`:消费掉、不报告,而不是发明一个没人发过的 null。 一条变异体(把"跳一格"改成"清空缓冲")红 1 条。 与参考实现的一处**故意偏离**写在注释里:它用 `assert` 查 flag/字段名,失败是抛异常;这里 判成 `Bad` 再跳一格 —— 对端发一个畸形帧不该结束连接。 全仓 1546 绿。
参考实现用 if/elif 链分派十二条命令。可移植、而且一个端口可以**静默搞错**的,是这张表的
形状,不是每个分支里的 B 站调用:
- **要不要参数**:`GetVolume`/`Pause` 不要,`SetVolume`/`Play` 没有就跑不通
- **哪些键必需**:`params['aid']`(缺就抛)与 `params.get('oid', self.aid)`(缺就取默认)
混在同一个分支里。读反了就把"客户端漏了个可选字段"变成"连接被掐断"
- **先回 RES 还是根本不回**:多数分支先 `send_res(counter)`;`SetVolume` 与 `SwitchSpeed`
一次都不回。总是回复会发出客户端不读的帧,从不回复会让 `Pause` 看起来挂了
差分语料 tests/golden/nva_commands.jsonl,15 行由执行参考实现的分支结构(B 站与渲染器调用
换成事件标记)生成:哪个分支跑了、`send_res` 有没有跑、有没有 KeyError/TypeError 逃出来。
**语料改了这张表两处,都是我的错**:
- `SetVolume {'other':1}` 参考实现**不抛**(它读 `params.get('volume', -1)`,-1 撞范围检查),
我原来要求那个键必需 —— 那会掐断一条参考实现保持的连接。新增 `Needs::BodyOnly`:
需要一个 mapping,但不要求某个键。
- `Seek` 同理(`.get('seekTs', 0)`),非对象体也接受。
还有一处语义要分清:未知动词在参考实现里**会回 RES 但不做事**(`else` 分支),所以它不算
线上拒绝;我的 `dispatch` 用 `Err(UnknownVerb)` 表达"没有分支可跑",对拍用例接受这个表达
并要求那一行确实回了 RES。
一条变异体(把 `Pause` 的 reply 改成 None)红 3 条。
全仓 1555 绿。
`relay.rs` 已有 `parse_range`/`serve_plan`(远端源那一路),这块是**本地文件**那一路: 注册表 + 每条应答的头。两条路只差一处,但那一处值得单独一张表而不是一个带开关的复用。 三条红线,每条都在真电视上量过(AGENTS §4.8 / Part 25): - **没发 Range 的请求是 200 且不带 Content-Range**。只有客户端真发过 Range 才配 206。 `spec = parse_range(header)` 那种写法会让整份读也回 206,而 DLNA 渲染器把它读成"半个文件"。 - **注册过但已经消失的文件必须拒答**。回一个没有长度的 200 会让渲染器永远等字节 —— 那是挂起,不是报错。 - **起点越过末尾是 416 且带 `bytes */total`**。回 200 会让它去 seek 一个不存在的位置。 另外 `Accept-Ranges` 出现在**每一条**应答上(渲染器靠它决定要不要提供拖动)、 DLNA 推送独有那两行(电视**先读它们才决定播不播**,缺了就是"这个文件播不了"而没有任何报错)。 差分语料 tests/golden/local_serve.json,49 条由执行参考实现的 do_GET 判决路径生成 (两种长度 × 12 种 Range × DLNA 开/关)。一条变异体(有 Range 就回 206)红 2 条。 **语料抓到两处**: - 416 分支我多发了 DLNA 头。参考实现那条路只发 code + 两个字段 —— 一个带着 `transferMode.dlna.org: Streaming` 的 416 在告诉设备"这是一个流",而那个窗口并不存在。 - 我先自己写了一个 `is_junk()` 去修正 `bytes=9-0`,而 `relay::parse_range` **早就**按参考 实现的 `stop < start → None` 实现了。那层是多余的、而且是错的:现在只有一处 Range 文法, `is_junk` 删掉。顺带说明它不是"两种实现漂移",是我在没有读那个函数之前先动手了。 全仓 1567 绿。
`screen_mirror.py` 有 13,629 行,大部分是采集→编码→推流。可移植成**判决**的是那几张 表,和一段一条注释里写着实测数字的算术。 **目标表**(五个目标)三条容易丢的事实: - `webrtc`/`caststream` **不是容器**:raw H.264 交给重打包的一方,所以**没有 Content-Type**。 给了 `-f mpegts` 会产出对端解不开的字节,而唯一症状是黑屏。 - `dlna` 也不是容器,理由相反:电视被告知它在下载一个**有限文件**,容器、编码、连 URL 的 扩展名都来自兼容档位,所以它的 muxer 槽位是 `None`。 - **默认档位随形状走**,而且是实测不是口味:同机同编码器,`ps-pal` 首帧 5.86 s / 稳定 5.08, `ts-mpeg2` 2.47 / 2.15,载荷**逐字节等价** ⇒ 约 3.4 秒是容器要的。 **队列算术**一条:`frag_every_frame` 是按**采样**不是按画面,带声音的 24 fps 一秒写 24 + 46.875(48 kHz/1024)= **70.875 个 moof**。实测 15.02 秒 1063 片 = 70.8/s,与算术一致。 所以 fMP4 档的队列是 **54 个单位**,不是写死的 8(8 个 = 0.11 s,而预算要 0.75 s, 实测 28% 自丢)。 语料:目标/档位表逐字段 5+5+5 行、队列 48 行,全部由执行参考实现生成。 两条变异体(给 PS 加 `-muxdelay`、fragment 队列退回 8)各红 2 条。 **语料抓到两处,都是我按注释读实现**: - `webrtc`/`caststream` 的 suffix 字段是 `h264`,不是空。参考实现那句注释说"no suffix, no Content-Type",我把它读成了**空字段**;真正表达"不走 HTTP"的是 `content_type: None`。 - `queue_hold_seconds` 的 `has_audio` 我写成了常量 `true`。无声会话 0.75 秒写 18 片, 用带声音的速率去除会答 0.25 秒 —— 一张把队列说短了四倍的卡片。 全仓 1586 绿。
这是 `screen_mirror` 里**我们自己造成过**的那一格:`-level 42` 被写死给 `h264_videotoolbox`。level 4.2 把一帧限制在 8704 个宏块(2208×1242),而这台机器的桌面是 3456×2234 = 30384 个 —— 编码器拿到一个它履行不了的承诺,然后**退出 187、五行 stderr、 一个字节都不产出**。 实测(2026-10-02,同采集同码控):2160p + `-level 42` → 0 字节;+ 51 → 2130382 字节; 不加 → 正常,VT 自己挑。3456×2234 同理(0 字节 ×2 → 51 或省略都能跑)。 **为什么比普通崩溃更贵**:`auto` 探测到硬件就用硬件,所以 Mac 上「原画」档的出厂默认是 **产出零帧**,而没有帧的路径会把用户送去**屏幕录制授权**那扇门 —— 一个我们自己写的数字, 却让人去查权限。`has_hardware_encoder` 也抓不到:它 grep `ffmpeg -encoders`,而那里列着 一个随后会拒绝这张画面的编码器。 于是规则变成三条:**能履行的才钉**(4.2 是 Cast 解码器上限,只在 1080p 以内有意义)、 **更大的画面钉下一个**、**尺寸不知道就整个省略**(`height == 0` 是「不缩放」档;省略不是 耸肩 —— 实测 VT 自己算的 level 在 1080p 是 4.0,比我们钉的 4.2 **更保守**)。 另外两条同源事实:VT 会把 `-b:v` 少给 30–33%(要 4 Mbps 实发 2802 kbit),所以只有它乘 1.5;NVENC 与 x264 落在要求的数字上(菜单 6000 → 实测 6052/6081/6087/6029),乘了会超发一半。 语料 36 行(12 个高度含 3456×2234、2 种编码 × 3 平台 × 4 码率)由执行参考实现生成。 一条变异体(`height == 0` 钉成 42,就是原 bug 的简版)红 4 条。 全仓 1598 绿。
DLNA 预填、直播边缘、最大时长 —— 三个旋钮的共同规则是**夹住而不是拒绝**,因为设置 JSON 是 手改的:拒绝的后果不是"用户被告知输错了",而是一台不肯播的电视,或者一个静默不生效的旋钮。 几处不能丢的: - **预填默认是 4 不是下限 1**,理由在别人的硬件上量得:MirrorCast 在真 Philips 43PFS5031 (2016,非 Android)上预填约 20 MiB(≈20–25 秒)并明说 —— 说明"要得比我们下限更多"的 固件确实存在,而这台机器上没有那样的电视能量出**我们的**下限。量不出来的数交给能量的人, 代价印在旋钮旁边(`DLNA_PREFILL_HINT`)。 - **报出的秒数从字节预算反推,不读设置**。预算有 2 MiB 下限和 8 MiB 上限,都会把真实延迟 挪开;读设置会告诉用户一个他没在经历的数值。语料里 `rate=1000` 那行报 **16777 秒**, 那正是下限在行使自己 —— 把它写进语料,是为了不让谁把它"修"成好看的谎。 - **直播边缘下限 0.5 秒而不是 0**,而且理由换过一次:旧的"分片 12 帧 = 0.5 秒"随 v0.19 的 muxer 改动作废(现在分片是一帧 41.7 毫秒)。今天成立的是实测:0.5 与 1.0 只差 **9 ms** (829 / 838),所以这个旋钮已经不是延迟控制,而是**恢复距离**。 - **最大时长只有三档、故意没有「不限」**:这一页的默认值从来没人动过,而"没人动就等于不设限" 正是这个旋钮要结束的状态。且**只约束 cast 与 dlna**:低延迟那两路是边缘消费者, 给它们 `-t` 等于为了省下零延迟去截断一场演示。 语料 50 行由执行参考实现的钳制/派生函数生成。一条变异体(报出秒数改成读设置)红 1 条。 全仓 1608 绿。
Python 的 `round()` 是**四舍六入五取偶**,Rust 的 `.round()` 是**五远离零**。两者在
.5 处会给出不同答案,而我写的两处都用了后者。
**一处是 `mirror_queue` 的 `round2`**(队列秒数,诊断卡与观看页都在显示)。
参数空间扫描(chunk/cluster 形状、0.6–20 Mbit/s、每个可能的队列深度)里有
**142 处分歧**,例如 1 Mbit/s、48 个 cluster:Python 20.62,Rust 20.63。
修法是 `format!("{:.2}")` 再 parse 回来 —— 那正是 `round(x, 2)` 的规则。
**另一处更严重:`channel.rs` 的音量**。参考实现是 `int(round(level * 100))`
(`protocol_cast.py:741`),送给播放器。0.000–1.000 按 0.001 步进有 **46 处**
分歧:0.005 → Python 0 / Rust 1,0.025 → 2 / 3,0.045 → 4 / 5。发送端把音量滑块停在
这些位置之一时,我们报给播放器的数字与参考实现不同,而线上回给它的 echo 又与它自己的
请求不一致。
两处都补了钉住**精确半值**的用例(那些正是任何"顺手写的"舍入会错、别处又都对的地方),
并把实现改回 `.round()` 时各红 1–2 条。语料里另外显式写了 6 行分歧点(带 `note`,
不按 bitrate 重算容量 —— 那个 bitrate 下容量确实是下限 8,写进去就必须说明它问的是另一个
问题)。
顺带审了其余 `ceil`/`floor` 调用:Python 与 Rust 在这两个上语义一致,不需要动。
全仓 1610 绿。
用差分探测(而不是读代码)扫 `int(float(text))` 与 Rust `parse::<f64>()` 的差别,
三处都可达:
1. **下划线**:`float("1_000")` 在 Python 是 1000,Rust 的 parse 直接拒。进度正则抓的是
`(?P<eta>\S+)`,所以任何非空白串都能进来。现在先去掉下划线再解析。
2. **`inf`/`-inf`/`1e400`**:Python 抛 **OverflowError**,而参考实现的 `except ValueError`
**接不住** —— 进度线程直接死。这里回 0,是**有意分歧**,语料里按 `raises` 显式标出。
3. **`"1 :02:03"`(冒号内有个空格)**:参考实现的正则没有 `\s`,所以它落到
`int(float(...))` → ValueError → 0。而我第一版对每个字段做了 `trim()`,于是**接受了
参考实现拒绝的串**。那是"顺手让它更宽容",语料当场红。现在按正则的规矩解析未 trim 的字段。
另外两处随手的正确化:
- 累计和改用 `saturating_mul/add`:一个 30 位小时数不该回绕成负数再被 `hms` 钳成 `0:00:00`
(那会让快下完的任务显示"刚开始")。
- **撤掉一条我之前写强的断言**:`1e30 as i64` 在 Rust 里**本来就**饱和(那是 `as` 的定义),
不是我这轮的修复。变异体证明旧实现也能过那条断言,所以注释改成"文档化了调用方可以依赖的
行为",并写明残余风险在**调用方**的 `elapsed + eta`(目前没有调用方)。
语料从手挑的 22 行换成 39 行(含 14 行 ValueError、3 行 OverflowError、2 行超 i64),
三个变异体各红 1 条。全仓 1610 绿。
继续用差分探测扫 `parse_range`(三条 HTTP 红线的核心),三处可达: 1. **首尾空白**:Python 的 `int()` 接受 `" 5"`、`"5 "`、`"5\n"`,Rust 的 `parse::<u64>` 全拒。`bytes=0-9 `(尾随一个空格)在参考实现里是合法 Range,在这里是 `None`; 而 `None` 让 `serve_plan` 回 **416**,DLNA 渲染器把它读成"文件死了"。手写或有 bug 的 发送端恰好会多发一个空格。 2. **`bytes=-`**(连字符后什么都没有):参考实现回 `(None, None)` —— 空后缀仍然是一次 Range,由调用方按真实长度解析(等于"最后 0 字节")。我原来断言 `None`,那条断言本身 是错的,已按实测改正。 3. **超出 u64 的数**:Python 的 int 无界,这里拒。行为上等价(都是"一个不现实的巨大偏移"), 但语料里显式标了 `exceeds_u64`,不让测试靠 `as_u64() == None` 去猜 —— 那个推断把空头的 `[0, null]` 也误判成"太大"了。 语料 36 行(含四种位置的空白、`+` 号、大写单位、多区间、`stop < start`、3 行超 u64)。 一条变异体(去掉 trim)红 1 条。 全仓 1612 绿。
继续差分扫描时发现 `py_float` 实现了 CPython 的完整规则 —— 下划线只有**两侧都是 ASCII
数字**才算数 —— 但**没有任何用例问过它**。那种"写对了但没被问过"的代码,下一次重构就会
被简化成 `replace("_", "")`。
语料 23 行由执行 Python 的 `float()` 生成,覆盖两侧都成立的(`1_000`、`1_0.5`、`1e1_0`、
`1_0_0_0`)与**不成立而必须抛的**(`1__0`、`_1`、`1_`、`1_.5`、`1._5`、`0x1_0`),
外加 inf/nan/大数。一条变异体(去掉 flanking 检查、直接剥掉所有下划线)红 1 条 ——
那正是"顺手简化"会写出的版本,它会把五个参考实现拒绝的串变成接受的。
顺带核对了两处已经用 `format!` 的舍入:`py_round1`(2001 个值扫过,0 处分歧)与
`bitrate_kbps`(`1500 → 2`、`2500 → 2`、`3500 → 4` 的银行家舍入)。它们本来就是对的。
全仓 1613 绿。
两件事,都不是产品缺陷,但都是**我的生成器或断言错了**: 1. **`serve_plan` 的 `asked` 门**。参考实现把 `asked`(客户端到底发没发 Range)一路带到 最后一行才用:`parse_range(None)` 回 `(0, None)`,看着像一个窗口,所以**不能**只按解析 结果判 206。无 Range、垃圾 Range、`bytes=-`(解析成 `(None, None)`)三者都是 **200**, 只有真的请求了一个窗口才是 206。 我先写的语料生成器漏了这行门(于是"无 Range"看起来像 206),又据此写了一条断言 —— **断言跟着错**。改了两次才发现:先怀疑实现,再去看参考实现的最后那三行,才明白是 语料错了。现在用例钉住四种"不是窗口"的输入都回 200,三种真窗口回 206。 2. **`local_serve` 的语料生成器漏了 DLNA 头分支**。补完 6 种新 Range 形态(24 行)后, `bytes=-` + DLNA 那一行报"unexpected header transferMode.dlna.org" —— 那是**生成器** 少写了一段 `_headers` 里的 dlna 分支,不是产品多发。按参考实现的 `_headers` 逐行重写 生成器、**整份重算** 73 行(不留两份来源),再跑:全绿。 顺带验证了 416 分支真的不发 DLNA 头(变异体加回去 → 红 1 条)。 全仓 1614 绿。
**为什么要写生成器**:这些语料原本都是一次性内联脚本产出的,同一个会话里因此产生了**三份
坏语料**。坏语料最贵的地方不是结果错,而是它让"实现错"和"语料错"看起来一样,而人的本能是
去改实现。现在 `scripts/build_corpora.py` 按参考实现的**源码**重建每一份,`--check` 回答
"已提交的语料还是参考实现说的那样吗"。
**它立刻抓出两个真缺陷**(都只在语料被重新生成后才现形 —— 旧的语料是用同样的错读数造的,
两边"一致地错"):
1. **`MKV_CLUSTER_BYTES`**:我给的是 `55_000`(那是参考实现注释里"50–60 KB"的中点),
真实值是 `60 << 10` = **61440**。所有 Matroska 队列的秒数都偏了 12%。
2. **`live_queue_chunks` 在 bitrate 未知时答反了**:参考实现回 **上限 256**(没有速率可除时
取最宽的队列 —— 一个慢但活着的观看端不该被切断),我回的是下限 64。方向相反。
生成器自己也被抓出四处 bug,逐个修正后现在逐字节稳定:`except Exception` 抓到本应被
`except ValueError` 吞掉的空串(让 `eta_seconds("")` 看起来会抛)、`FPS =` 匹配到注释里的
"FPS = 41.7 ms"、`_P` 对象用 `str()` 当键(于是每个旋钮都回默认值)、`@dataclass` 装饰器
漏在 lift 边界外。
**一处自我更正的断言**:我原有一条用例叫 `a_byte_shaped_queue_without_a_bitrate_answers_the_floor`
—— 它断言的是错的方向,而且它和实现互相印证了对方。现在改名为 `..._the_ceiling_...`,并把
"两边从同一个读数出发"写进注释。
**一处未复现的偶发**:全量并行时 `eventing` 的两条用例曾红过一次(5 秒内没看到 `SEQ: 0`,
但说"2 requests arrived"),单跑与三次并发全量都没再现。我没能定位真因,所以只改进了它的
失败信息(现在会打印实际收到的请求开头)—— **它仍是未复现的偶发,不是已修**。
全仓 1614 绿。
`scripts/build_corpora.py --check` 现在是 `rust` job 的一步。这一步的价值在于它是**唯一能 回答"已提交的语料还是参考实现说的那样吗"**的检查 —— 而那正是我这轮犯过三次的那个错。 接进去之后它立刻抓到两份:`py_float`(格式差异)与 `serve_plan`(**根本没有语料文件**, 我只写了一条手挑的用例)。补上后 `serve_plan` 有了 36 行走查对拍,覆盖 4 种 relay 形状 × 9 种 Range,并断言 200/206/416 三个分支都出现过 —— 否则一条分支就是 没被测到。变异体(把 `asked` 门改成恒假)红 1 条。 `rust` job 仍然不含任何 tauri:新增的是 `setup-python` 与一条 `python3` 命令,因为 `build_corpora.py` 要从参考实现里取文本并执行它 —— 那是用 Python 干的活,不是把 Python 引成构建依赖。 全仓 1615 绿;10 份语料与参考实现一致。
上一轮的 `MKV_CLUSTER_BYTES` 是 `55_000` 而不是 `60 << 10` —— 那是**注释里的中点被当成了值**。 更贵的是:语料是用同一个错读数生成的,于是实现与语料互相印证,一起与软件不符。 现在 `constants.json` 由 `scripts/build_corpora.py` 从参考实现的**源码文本**取值, 三组共 21 个常量: - `mirror_queue` 8 个(含那个出过事的 `MKV_CLUSTER_BYTES`) - `mirror_knobs` 9 个 - `resolve` 3 个超时(`SCRAPE`/`YTDLP`/`PROBE`) 两侧各写一条断言,Rust 侧**通过本地的 `const` 读值**,所以手改一个仍"看着像"的表达式也会红。 变异体(把 `MKV_CLUSTER_BYTES` 改回 55_000)红 1 条。 顺带核对了盘点时担心的其它几处(手动比对,结果都对):`LIVE_QUEUE_*`、`CHUNK`、`FPS`、 `TS_PACKET`、`DLNA_PREFILL_*`、`LIVE_EDGE_*`、`VT_BITRATE_MULT`、`MAX_MEASURED(_PER_HOST)`、 `PAGE_MAX_BYTES`、`RESOLVE_JOBS_MAX = 4`、`RESOLVE_JOB_TTL = 30 * 60` —— 以及 `prune_locked()` 确实实现了参考实现那条「满了但有一个已完成就能顶替」的规则。 全仓 1617 绿;11 份语料与参考实现一致。
`nva_request` / `nva_frames` / `nva_decode` / `nva_commands` 之前也是一次性脚本的产物。 现在由 `build_corpora.py` 重建 —— 其中请求行与解码器是**照着参考实现的分支逐行重写**的 (`cheroot` 与 `nva` 无法直接 import),框架语料则直接用 `struct.pack` 复刻三条格式串。 重建结果与我当初手写的那四份**逐行一致**,也就是说那次移植没有漂移 —— 但这句话现在 有机器能验证,而不是只有我的记忆。 四份合计 162 行:13 条请求行、126 帧、8 条解码流、15 条命令分派。
这个分支第一次跑 CI(PR #1)暴露了两条,都是**测试自身的环境假设**,不是产品缺陷。 **1. `receiver_port_fallback_when_occupied`**:它把阻塞器绑在 `127.0.0.1:7000` 上,然后断言 接收端回落。macOS 上过,Linux runner 上**阻塞器自己**就 `AddrInUse` 了 —— runner 的 7000 已经 有东西,测试造不出自己的前提,红的原因与代码无关。 修法是把 `start()` 拆出一个 `start_from(first)`,测试向内核要一个空闲端口、占住它、从那里 开始搜 —— 同一套逻辑,任何机器上都成立。 顺带修一处真实的平台差异:接收端绑 `0.0.0.0`,而原测试的阻塞器绑 `127.0.0.1`;这两者 **在 Linux 上不冲突**,所以那条用例在 Linux 上即使绑上了也是空转。 **2. `e12`(单播那条)**:它的控制组断言"通配 socket 收不到单播"——而那正是当初增设第二个 socket 的**依据**。macOS 上 `mdns_unicast_bind_probe.py` 量得 0/8(不用 `SO_REUSEPORT` 时两个 bind 甚至不能共存,本机实测 `os error 48`),Linux 上通配 socket **也能收到**(CI 读到 1)。 所以那是 macOS 的事实,不是定律。现在按平台断言并把读数打出来,同时在注释里写明两家平台的 来源,并要求下一个人**重新测量**而不是改数字。 真正该在**任何**平台成立的那一条(精确地址的 socket 必须听见)断言在控制组之前,不动。 全仓 1617 绿。
Rust 构建流水线第一次跑三平台,Windows job 在这一点红了: `frontend/bundle.js is stale — run cargo run -p macast-frontend -- --check`,而 macOS 与 Linux 都过。红的是**换行符**: `assemble()` 用 `source.lines()` 读源文件(**丢掉 `\\r`**)再用 `\\n` 拼接,所以产出的 bundle 永远是 LF;而 Windows 上 `core.autocrlf=true` 的 checkout 会把已提交的 `frontend/bundle.js` 变成 CRLF,于是逐行不等 —— 报"过期",但真去跑 bundler 什么都不会改。 两道防线: 1. **`.gitattributes` 把 `frontend/bundle.js` 钉成 `eol=lf`**(连同语料目录)。这是真正的 修法:产物跨平台逐字节相同,而它是生成文件,不存在覆盖谁的行尾习惯的问题。 2. **比较前把读回的内容里的 `\\r\\n` 归一成 `\\n`**。这样即使某人的全局 git 配置仍在改写它, 拿到的也是真答案,而不是一句"去跑 bundler"(跑了也白跑)。 实测:把 bundle.js 临时改成 CRLF,`--check` 仍答 current(exit 0);改回 LF 也是 current。
`build.yml` 的 Windows job 把 mpv 地址写死成 `.../download/20260903/mpv-x86_64-20260903-git-69e63f425a.7z`。今天实测 **404** —— 上游会清理旧 release,所以一个钉死的日期就是"在别人挑的时间点坏掉"。 改成运行时解析 `releases/latest` 里第一个 `mpv-x86_64-*.7z`(排除 `-v3-` 变体,它要求 AVX2)。拿不到资产时**响亮失败**并说明是上游命名变了,而不是留一个裸 curl 退出码。 本机按 workflow 里那段原样跑过:解析到 `mpv-x86_64-20261021-git-e471496c56.7z`, `curl -fSL` 拿到 **HTTP 200 / 34,025,957 字节**。 这条路与本批 Rust 改动无关,但它挡着发版(main 最后一趟 CI 在 10-06 时那个 URL 还在)。
CI 的 Windows job 第一次真跑到「Build the shell」就失败:
`D:\a\Macast\Macast\src-tauri\icons/icon.ico` not found;
required for generating a Windows Resource file during tauri-build
`tauri.conf.json` 的 `bundle.icon` 只列了 `.png` 与 `.icns`,而 `src-tauri/icons/` 里也只有
这两个。Tauri 在 Windows 上生成资源文件时必须要有 `.ico` —— 所以**这个壳在 Windows 上从来
没有构建成功过**,只是此前没有任何 job 试过它。
`macast/assets/icon.ico` 一直在仓库里(36,735 字节,Python 那一侧用的就是它),复制过来并把
它列进 `bundle.icon`。
macOS 复验:`cargo build -p macast-tauri --release` 仍成功(27s)。
上一版我试图直接提交 `src-tauri/icons/icon.ico` —— 那是错的:`.gitignore` 明确忽略那个目录, 理由是**美术资源只有一个主人**(`macast/assets/`),`src-tauri/build.rs` 每次构建从它派生。 而 `build.rs` 的头注释已经写清了剩下那一半: > 一个 Linux bundle 要 `32x32.png`/`128x128.png`/`[email protected]`,Windows 要 `icon.ico`。 > 缩放需要真正的图像库(`sips` 只在 macOS 有),所以那些尺寸**不在这里假造** —— > 构建那些平台的 job 跑 `cargo tauri icon ../macast/assets/icon.png`,它会写出整套。 我的 workflow 没做这一步,于是 Windows job 在编译第一行代码之前就死在 `` `icons/icon.ico` not found; required for generating a Windows Resource file ``。 现在 Windows 与 Linux 的 job 各自加一步 `cargo tauri icon ../macast/assets/icon.png`。 本机实测:它写出 `32x32.png`、`64x64.png`、`128x128.png`、`[email protected]`、`icon.ico` 等整套;随后 `cargo tauri build --target aarch64-apple-darwin` 仍产出 `Macast.app` 12.51 MiB + `.dmg` 4.78 MiB。 这些生成文件都被 gitignore,仓库里不会出现第二份美术资源。
`src-tauri/build.rs` 的头注释写着这条约定(它自己只派生 `icon.png`/`icon.icns`,其余尺寸 交给平台 job 的 `cargo tauri icon`),但**没有任何东西检查它** —— 于是两个 job 第一次真跑就红在 `` `icons/icon.ico` not found ``。 守卫用例数 `run:` 行里 `cargo tauri icon` 恰好出现 2 次(Windows + Linux;macOS 不需要, 因为 `build.rs` 已经产出 `.icns`)。变异体(删掉 Windows 那一步)红 1 条。 全仓 1617 绿;15 份语料与参考实现一致。
上一版那一步写成 `run: cargo tauri icon ../macast/assets/icon.png`,而 job 步骤的默认工作
目录是**仓库根**,于是源路径解析成 `runner/_work/macast/...`:
Error failed to read and decode source image ../macast/assets/icon.png:
The system cannot find the path specified. (os error 3)
加 `working-directory: src-tauri`(那也正是 `build.rs` 用 `../macast/assets` 的原因 ——
它就在 `src-tauri` 里跑)。
本机在 `src-tauri` 下执行同一条命令:写出 **50 个**图标文件,含 `icon.ico` 与 `icon.icns`。
Owner
Author
|
归档前关闭。仓库即将转为只读(维护工作转到 HanCast)。 这个 PR 从来不是为了合并——它存在的原因是
分支 归档交接说明已提交到 main: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
这是什么
refactor/rust-tauri-2:Macast 的 Rust/Tauri 移植分支,153 个提交。这份 PR 的目的不是合并,而是让这批提交第一次拿到 CI 见证——它们此前全部只在一台机器上跑过。为什么开 PR 而不是推 main
build.yml的push只监听main、tag 与 PR,所以推功能分支不会跑任何 CI。这是"本分支从未有 CI 见证"的机制原因,而不是运气不好。这批提交的验证状态
AGENTS.md§4.12 记的 Part 34 常红(本克隆缺 fork 点对象,台账算不出)scripts/build_corpora.py从参考实现源码重建--check已接进 CIcards=6 placeholders=0 errors=0;SOAPGetTransportInfo回OK、GetVolume回100新增的 CI
build.yml增加rustjob:四个库 crate + 语料一致性 + 打包器一致性。不含src-tauri(Linux 上要 webkit2gtk,而它那 40 条测的是壳)。rust-build.yml(新文件):三平台cargo tauri build,permissions: contents: read,不产出 Release——把产品从 Python 换成这个壳是需要单独裁定的决定。这一轮修的缺陷(都有变异体验证)
MKV_CLUSTER_BYTES抄错:55_000而不是参考实现的60 << 10(61440)。语料是用同一个错读数生成的,所以两者互相印证、一起与软件不符。live_queue_chunks在 bitrate 未知时答反了:参考实现回上限 256(慢但活着的观看端不该被切断),我回的下限 64。round()两处:Python 是四舍六入五取偶,Rust 的.round()是五远离零。队列秒数 142 处分歧、音量 46 处(0.005→ Python 0 / Rust 1)。parse_range不容空白:bytes=0-9在参考实现合法,在我这里是None→serve_plan回 416,DLNA 渲染器读成"文件死了"。诚实边界
set_renderer只接受MPV,所以"第二个渲染器"的判决只被用例问、不被产品问。screen_mirror的管线本体(采集/编码/推流)一行没搬。eventing有两条用例在全量并行时红过一次,未能复现、未定位,只改进了失败信息。