From 09c6fd699f01fa0e3b804bf83ece97d0bfc2e4c1 Mon Sep 17 00:00:00 2001 From: James Braid Date: Sun, 29 Nov 2026 16:47:43 -0700 Subject: [PATCH 1/4] config: count only a none at a graphics slot as no board graphics_entry() took the first board or `none` entry as the machine's board, so a `none` anywhere (a PCI slot, a port) read as "the config says no graphics board". On an Onyx 3000 with `none` at xio15/pci0/2, graphics_board() returned None instead of Ir3, which feeds the vbrick check, validation messages and the GUI summaries. A board counts wherever it is. A `none` counts only when it names the machine's graphics slot, which names_graphics() already answers. Production lines: +1 -1 --- src/config.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/config.rs b/src/config.rs index 95e99d29f..415481285 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3127,7 +3127,7 @@ impl MachineConfig { /// The machine's board: the config's own entry, else the graphics slot's default, none if the config says `none`. /// Reads the entries without placing them, so a front end may ask every frame. pub fn graphics_entry(&self) -> Option { - let mut main = self.devices.iter().filter(|d| matches!(d.device, DeviceModel::Board(_) | DeviceModel::Empty) && !Self::is_head(d)).map(|d| &d.device); + let mut main = self.devices.iter().filter(|d| (matches!(d.device, DeviceModel::Board(_)) || d.names_graphics(self.machine.profile)) && !Self::is_head(d)).map(|d| &d.device); match main.clone().find(|d| matches!(d, DeviceModel::Board(_))).or(main.next()) { Some(DeviceModel::Board(b)) => Some(b.clone()), Some(_) => None, @@ -4439,6 +4439,12 @@ mod export_tests { assert!(cfg.validate().unwrap_err().contains("no free slot"), "no VPro in an Indy"); } + #[test] + fn a_none_away_from_the_graphics_slot_leaves_the_board() { + let cfg = MachineConfig::from_toml_str("[machine]\nprofile = \"onyx3000_ip35\"\n[[devices]]\ntype = \"none\"\nat = \"xio15/pci0/2\"\n").unwrap(); + assert_eq!(cfg.graphics_board(), Some(GraphicsBoard::Ir3)); + } + #[test] fn audio_host_parses_and_defaults() { let cfg: MachineConfig = toml::from_str("").expect("parse"); From 2da87d2024ae0f0b913ef5395f2a976cf31fe189 Mon Sep 17 00:00:00 2001 From: James Braid Date: Sat, 28 Nov 2026 11:20:05 -0700 Subject: [PATCH 2/4] net: place the Ethernet's host end as a device at its port [network] picked one host end for the machine (NAT, a pcap interface, a stream peer, nothing) and kept the MAC beside it, while a serial port's host end is a device at the port. The Ethernet is a port too, so it now follows the same three steps: a `net` entry at the port gives it a host end, and `none` at the port empties it. Every machine's built-in Ethernet is a slot named `ethernet`, under the chip that owns it (hpc3, mace, or the IOC3's or BCM5701's PCI slot). `backend` is nat, pcap, pcap:IFACE, stream:tcp:IP:PORT or stream:unix:PATH, read by the shared backend parser, and `mac` is the port's station address. A port with no entry has a default NAT entry that is never written, so a config that says nothing still gets NAT. A card that brings its own Ethernet declares `CARD/ethernet` and takes the same entry; none does yet. The alias `ethernet` may repeat a slot's last path step, which the alias check refused before. The NAT gateway's own services (nat_subnet, [nfs], [[port_forward]], tftp_dir, rsh_dir, nfs_pcap_ip, rx_hold) stay where they are: one gateway serves the machine, not each port. The Indy and Indigo2 still refuse an empty Ethernet. `none` at the machine's graphics slot (gfx, gio0, a pipe slot) still only keeps the default board out and leaves the slot free, as before; at any other slot it now holds the slot, so a port stays empty and nothing else is placed there. That includes an Octane's XIO slots that are not its graphics slots, though every XIO slot takes a graphics board. `none` at the port is the one way to unplug it: `backend = "none"` on a `net` entry is refused, so there are not two spellings with different results. The station address is guest-visible (the PROM reads it from NVRAM or EEPROM, and the Fuel's host id derives from it), so it matters what an unplugged port has: no entry, hence the machine's own address. The MAC of a plugged port goes with the entry when the GUI unplugs it. iris-gui wrote `[network] mode = "nat"` into every machine it saved, so refusing the old keys would have made every saved machine fail to load. [network] mode, pcap_interface, stream and mac are read with a warning and turned into the entry in memory. Keys that say nothing (the GUI's `mode = "nat"`) are dropped where an entry exists; any other key beside an entry at the port is an error, as a serial port's tcp clash is. The GUI saves the new form. The --net-mode and --pcap-interface flags are hidden options that set the same entry after the file is read, so they beat the file's entry as --graphics beats its board. `o2.net = false` follows the key rule. In the GUI, the entry holds only the current backend's interface or peer, so switching PCAP to NAT and back forgets the interface. A remembered interface would have to be kept per machine, for little; the entry survives a save as `pcap:IFACE`. The status bar read the Ethernet through a full placement of the machine on every frame (50 to 460 us in a dev build, by machine); the app now reads it once per change of the config and the started machine's once at its start. Choosing Stream in the GUI writes an entry with no peer yet. `end()` now reads the mode from the `stream:` prefix and leaves the peer to `check`, so the mode follows the choice and `validate` reports a bad or missing peer before Start. The GUI's status, summary and interface reads use the entry (`ethernet()`) rather than `network()`, which expects a config that validates: a half-typed subnet, MAC or peer must not panic it. Production lines: +346 -157 --- CHANGELOG.md | 12 + Cargo.toml | 2 +- FEATURES.md | 17 +- HELP.md | 18 +- NETWORKING.md | 36 +-- clanker/irix/irix-install.md | 2 +- clanker/irix/networking.md | 7 +- clanker/plans/pcap-release-plan.md | 2 +- docs/dev/daynaport.md | 2 +- docs/dev/ioc3-ethernet.md | 2 +- docs/fuel-ip34.md | 6 +- docs/indigo2-ip22.md | 2 +- docs/o2-ip32.md | 8 +- docs/octane-ip30.md | 12 +- docs/tezro-ip53.md | 2 +- docs/xdmcp.md | 2 +- fuel.toml.example | 7 +- iris-gui-README.md | 2 +- iris-gui/core/src/controller/app.rs | 14 +- iris-gui/core/src/controller/help.rs | 2 +- iris-gui/core/src/controller/power.rs | 2 +- iris-gui/core/src/controller/session.rs | 21 +- iris-gui/core/src/controller/settings.rs | 12 +- iris-gui/core/src/model/hardware.rs | 35 ++- iris-gui/core/src/model/machines.rs | 8 +- iris-gui/core/src/model/summary.rs | 24 +- iris-gui/locales/en/main.ftl | 2 +- iris-gui/src/config_ui.rs | 36 +-- iris-gui/src/extra_ui.rs | 17 +- iris-gui/src/main.rs | 14 +- iris.toml | 27 +-- irix-extract/README.md | 1 - onyx2.toml.example | 7 +- origin200.toml.example | 7 +- origin2000.toml.example | 7 +- origin3200.toml.example | 6 +- src/config.rs | 294 +++++++++++++++-------- src/config/legacy.rs | 85 ++++++- src/dev/hpc3.rs | 1 + src/devices.rs | 20 +- src/ip27.rs | 1 + src/ip30_machine.rs | 10 +- src/ip32_machine.rs | 9 +- src/ip34_machine.rs | 1 + src/ip35/tests.rs | 2 +- src/ip35_machine.rs | 1 + src/ip53_machine.rs | 1 + src/main.rs | 6 +- src/net/link.rs | 2 +- src/net/mod.rs | 2 +- src/net/net_pcap.rs | 14 +- src/net/stream.rs | 6 +- src/slot_path.rs | 2 + src/sn/tests.rs | 2 +- src/topology.rs | 37 ++- src/tree.rs | 1 + tezro.toml.example | 7 +- tools/prom-boot-loop.py | 4 +- tools/tests/netbsd-indy-keyboard.py | 1 - 59 files changed, 595 insertions(+), 297 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c3532bec..d4e1a331a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -163,6 +163,18 @@ hashes are given where a change is easiest to understand by reading the commit. programs through their prescaler, including the half steps MIDI's 31250 needs. +### Ethernet + +- The Ethernet's host end and MAC are a `net` device at `ethernet`, on every + machine: `backend` is `nat`, `pcap:IFACE`, `stream:tcp:IP:PORT` or + `stream:unix:PATH`, and a port with no entry is NAT. `type = "none"` at + `ethernet` unplugs it, and the port then has the machine's own MAC. + `[network]`'s `mode`, `pcap_interface`, `stream` and `mac` are read with a + warning and saved as the entry, as are the `--net-mode` and + `--pcap-interface` flags, which replace the file's entry. An older key that + is not its default, beside an entry at the port, is an error. `tftp_dir`, + `rsh_dir`, `rx_hold` and `nfs_pcap_ip` stay. + ### IndyCam - The host camera works with cameras that offer only MJPEG, NV12, RGB or gray diff --git a/Cargo.toml b/Cargo.toml index a6510d2ed..306b54b5a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -266,7 +266,7 @@ jitv2_smc_check = ["jitv2"] # as Npcap. IRIS links dynamically and never bundles the driver, # so the runtime driver's license does not attach to IRIS. # Off by default — enable with `cargo build --features pcap`. Select at runtime -# with `[network] mode = "pcap"` in iris.toml. +# with a `net` device with `backend = "pcap"` in iris.toml. pcap = ["dep:pcap"] # Host services for IRIX programs, reached through the private system calls # 3000-3009 (iris-hostcall/): the trap in `exec_syscall` and the self-test diff --git a/FEATURES.md b/FEATURES.md index 1682c3a19..da6652835 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -414,9 +414,10 @@ takes; `--device [NAME:]TYPE[@SLOT][,KEY=VALUE]...` adds or replaces one from th |---|---|---| | `hdd` | a SCSI target, or a Fibre Channel loop ID | `path` (raw or CHD), `overlay` (copy-on-write sidecar `PATH.overlay`, or a CHD's `.diff.chd`; one emulator at a time can use it, and a `--ci` run keeps its own in the temporary directory; see [STORAGE.md](STORAGE.md)), `write_cache` (default `true`: a write completes once the host has it and a sync follows within about 5 s; `false` stores every write first), `scratch` (a host-managed raw volume; no overlay) and `size_mb` (64 when unset, for a new scratch image) | | `cdrom` | a SCSI target | `path` (a file, or an `http://` or `https://` URL, [STORAGE.md](STORAGE.md#cd-rom-images-over-http); empty means an empty tray), `discs` (more changer images), `overlay` | -| `daynaport` | a SCSI target | `mac` (`00:80:19:44:50:` when unset), `subnet` (`192.168.10.0/24` when unset, separate from ec0's). Refused on the machines with built-in Ethernet only (the O2, the Origin 200, Origin 2000 and Onyx2, the Fuel and the Tezro) and with `network.mode = "stream"`. | +| `daynaport` | a SCSI target | `mac` (`00:80:19:44:50:` when unset), `subnet` (`192.168.10.0/24` when unset, separate from ec0's). Refused on the machines with built-in Ethernet only (the O2, the Origin 200, Origin 2000 and Onyx2, the Fuel and the Tezro) and when the onboard Ethernet's backend is a `stream:` segment. | | `nvme` | a PCI slot | `path` (raw or CHD, at most 2 TiB), `overlay`, `write_cache` (as for `hdd`). An NVM Express controller with one namespace; any number per machine; see [docs/nvme.md](docs/nvme.md). | | `qla2200` | a PCI slot | A QLogic ISP2200 Fibre Channel adapter; its disks are `hdd` entries at `CARD/loopN`, N the loop ID 0 to 125. The Origin 3200 and Onyx 3000 have one fitted at `xio15/pci0/1`. See [docs/fibre-channel.md](docs/fibre-channel.md). | +| `net` | an Ethernet port (`ethernet`: the machine's own; a card that has one brings `CARD/ethernet`) | `backend`: `nat` (the default: the built-in gateway), `pcap` or `pcap:IFACE` (a host interface; needs `--features pcap`), `stream:tcp:IP:PORT` or `stream:unix:PATH` (a private segment; not shared with a DaynaPort); `mac` (`08:00:69:12:34:56` when unset; injected only into blank PROM battery-backed MAC slots). A port with no entry is NAT, and `none` there unplugs it (the MAC goes with the entry). See [NETWORKING.md](NETWORKING.md). | | `serial` | a serial port (`serial1`, `serial2`, ...; `--list-slots` lists them) | `backend`: one string or a list of `tcp:PORT` (telnet on 127.0.0.1, 0 = any free port), `unix:PATH` (raw bytes) and `log:PATH` (a transcript). The device replaces the port's default (TCP 8880 and up; under `--ci` any free port on every port but the console); with no `backend` the port is unplugged. `hostserial`, `midi_synth` and `midi_raw` put a device on the port instead. See [HELP.md](HELP.md#serial-ports). | | `ice1724` | a PCI slot | The IC Ensemble ICE1724 audio card; plays as `[audio]` sets. | | `pci_cage`, `pci_shoehorn` | an Octane XIO slot (`xio9` to `xio13`; the cage at `xio13`, alias `pci_module`) | The PCI module (slots 1 to 3) and the single-slot XIO-to-PCI adapter; see [docs/pci.md](docs/pci.md#option-boards-in-xio-slots). | @@ -428,7 +429,7 @@ takes; `--device [NAME:]TYPE[@SLOT][,KEY=VALUE]...` adds or replaces one from th | `midi_synth` | a serial port, as `hostserial` | `path` (required): a General MIDI SoundFont (`.sf2`), loaded at start. `gain` (`1.0`, 0 to 16): times the synth's own level, which leaves room for many voices; the host mix clips above full scale. Plays into the host's audio as a stream of its own (muted by `no_audio`); with `[audio] file`, into a file beside it (`out.wav` → `out-midi.wav`); `IRIS_MIDI_CAPTURE=file.wav` also records it. | | `midi_raw` | a serial port, as `hostserial` | `path` (required): a host MIDI port. A raw MIDI device (Linux: `"/dev/snd/midiC1D0"` or `"/dev/midi1"`) passes the bytes as they are, both ways; a host serial port with a MIDI interface (`"/dev/ttyUSB0"`) is set up as `hostserial` does. | | `newport`, `express`, `impact`, `vpro`, `kona` | the graphics slot (alias `graphics`) | A graphics board; see [Graphics boards](#graphics-boards). | -| `none` | any slot; `at` is required | Leaves the slot empty, so the default for it is not placed. | +| `none` | any slot; `at` is required | Leaves the slot empty, so the default for it is not placed. A graphics board slot stays free for another board; any other slot stays held. At a serial or Ethernet port it also drops the host end, as a `serial` with no `backend`; an Ethernet port's MAC goes too, and the machine's own is used. The Indy and Indigo2 always have their Ethernet. | @@ -478,11 +479,7 @@ is refused too, since the saved bus has no slot for it. A virtio-9p share cannot | Key | Default | Values and behavior | |---|---|---| -| `network.mode` | `nat` | nat, pcap, stream or off (no Ethernet; every machine but the Indy and Indigo2). Stream needs `network.stream`. PCAP needs build support and host capture permissions. PCAP works on every Ethernet; stream on every onboard one, not on a DaynaPort. | -| `network.stream` | `unset` | `tcp:IP:PORT` or `unix:PATH`: the server of the private segment for `mode = "stream"` (QEMU `-netdev stream` framing). See NETWORKING.md. | -| `network.pcap_interface` | `auto-pick when unset` | Interface name or numeric list index; PCAP only. | | `network.nfs_pcap_ip` | `unset` | Virtual LAN IP for the built-in NFS responder in PCAP mode. | -| `network.mac` | `08:00:69:12:34:56 when unset` | ec0 MAC; injected only into blank PROM battery-backed MAC slots. | | `network.tftp_dir` | `unset` | Read-only TFTP root at the NAT gateway for PROM network boot. | | `network.rsh_dir` | `unset` | Root for the built-in rsh server at the NAT gateway (TCP 514): `rsh cat\|dd\|ls\|echo\|pwd`, read-only, nothing runs on the host. | | `network.rx_hold` | `true` | Indy and Indigo2: frames for the guest wait in iris, off the virtual wire, while the next one would fill the last descriptor of its receive ring before the driver has reaped the filled ones, and for at most 100 ms. A frame that reaches a stopped receive channel is lost either way, as on the wire. `false` never waits. | @@ -600,8 +597,8 @@ Octane's 512-byte image, and its clock in `.rtc.clock`), `banks` 128 or 256 MB, largest first), `serial_log`, `headless` (serial console instead of the graphics console and keyboard), `[clock] fixed_mhz` (CP0 Count; the CPU runs at twice it, so 90 MHz is a -180 MHz O2), `[network]` including `mac` and `mode = "off"` for an unplugged -Ethernet, `[[port_forward]]`, `nat_subnet`, `[nfs]` and `[[devices]]` +180 MHz O2), a `net` device for the Ethernet (`mac`, or a `none` device at `ethernet` for an unplugged +cable), `[[port_forward]]`, `nat_subnet`, `[nfs]` and `[[devices]]` (`scsi0` and `scsi1` are its buses). See [the O2 guide](docs/o2-ip32.md). The old O2-only spellings (`o2.prom`, `o2.flash`, `o2.ram_mb`, `o2.dimms`, `o2.disks`, `o2.serial_log`, `o2.graphics`, `o2.cpu_mhz`, @@ -689,8 +686,6 @@ iris-gui does not parse this standalone option set; use its named-machine UI. | `--audio-host ` | Host audio system: `default`, `pulse`, `wasapi`, `coreaudio` or `null` (overrides `[audio] host`) | | `--nfs-dir` | Enable NFS share: path to the directory to export (enables NFS) | | `--nat-subnet` | NAT subnet in CIDR notation (e.g. 192.168.5.0/24). Gateway gets .1, guest (IRIX) gets .2. Default: 192.168.0.0/24. | -| `--net-mode` | Networking backend: "nat" (default, software gateway), "pcap" (bridge onto a real host interface; requires --features pcap), "stream" (a private segment; needs `network.stream`) or "off". | -| `--pcap-interface` | Host interface to bridge onto in PCAP mode (e.g. eth0, en0). Implies --net-mode pcap. List candidates with --list-net-interfaces. | | `--validate` | Check the configuration (parse, settings, files, directories, ports) without starting the machine; exit 0 or 1. See [HELP.md](HELP.md#checking-a-configuration). | | `--list-net-interfaces` | Print the host network interfaces libpcap can bridge onto, then exit. Requires a build with --features pcap. | | `--no-scsi-deferred-int` | Disable deferred SCSI status interrupts (default: enabled for OpenBSD/NetBSD compatibility). | @@ -936,7 +931,7 @@ cargo run --release --features gpujit # enable the graphics JITs cargo run --release --features jitv2,gpujit # MIPS JIT v2 (experimental; see "JIT compilers") cargo run --release --features idle-pause # park the CPU thread while the guest idles instead of spinning a host core cargo run --release --features ci_clock # synthetic deterministic CP0 Count clock (CI/snapshot validator only; loses realtime desktop timing) -cargo run --release --features pcap # bridge guest networking onto a real host interface via libpcap instead of the built-in NAT gateway. See [network] in iris.toml. +cargo run --release --features pcap # bridge guest networking onto a real host interface via libpcap instead of the built-in NAT gateway. See [NETWORKING.md](NETWORKING.md). cargo run -p iris-gui --release # the egui front-end, see iris-gui-README.md ``` diff --git a/HELP.md b/HELP.md index c34a2530d..22de25a12 100644 --- a/HELP.md +++ b/HELP.md @@ -136,13 +136,15 @@ Indigo2 keeps it in a serial EEPROM. A fresh or blank `nvram.bin` has no address, which prevents networking from working. **You usually don't have to do anything.** Before boot, IRIS writes a MAC into -a blank `eaddr` slot: `[network] mac` from `iris.toml` if you set one, otherwise +a blank `eaddr` slot: the `mac` of the `net` device from `iris.toml` if you set one, otherwise `08:00:69:12:34:56`. It never overwrites an address that is already there. iris-gui does the same and offers a guided prompt. Set one yourself when you run more than one emulated machine on the same network: ```toml -[network] +[[devices]] +type = "net" +at = "ethernet" mac = "08:00:69:de:ad:01" ``` @@ -893,11 +895,14 @@ path = "cdrom4.iso" # ── Networking ─────────────────────────────────────────────────────────────── +# [[devices]] # the Ethernet's host end; none is NAT +# type = "net" +# at = "ethernet" +# backend = "nat" # or "pcap:1" (--features pcap) or "stream:tcp:IP:PORT"; type = "none" unplugs +# mac = "08:00:69:12:34:56" # ec0 MAC, injected into blank NVRAM before boot + [network] -mode = "nat" # or "pcap" (--features pcap), "stream" or "off" -# pcap_interface = "1" # index, name, or '\Device\NPF_{...}' on Windows # nfs_pcap_ip = "192.168.1.250" # PCAP only: LAN IP the NFS server answers on -# mac = "08:00:69:12:34:56" # ec0 MAC, injected into blank NVRAM before boot # tftp_dir = "tftpboot" # serve read-only over TFTP at the gateway # rsh_dir = "shared" # `rsh cat|ls|echo|pwd` on this dir, read-only @@ -1112,8 +1117,7 @@ Display and audio Networking --nat-subnet NAT subnet, e.g. 192.168.5.0/24 - --net-mode nat (default), pcap, stream or off - --pcap-interface Host interface to bridge onto (implies pcap) + --device net@ethernet,backend=B The Ethernet's host end: nat (default), pcap:IFACE, stream:tcp:IP:PORT; none@ethernet unplugs it --list-net-interfaces Print bridgeable interfaces and exit --nfs-dir Export DIR over the in-process NFS server --tftp-dir Serve DIR read-only over TFTP at the gateway diff --git a/NETWORKING.md b/NETWORKING.md index 4d354f093..37a1444fc 100644 --- a/NETWORKING.md +++ b/NETWORKING.md @@ -38,18 +38,19 @@ Debian/Ubuntu, or the macOS system libpcap). cargo build --release --features pcap ``` -2. **Configure** in `iris.toml` (or pass CLI flags): +2. **Configure** in `iris.toml` (or pass `--device`): ```toml - [network] - mode = "pcap" - pcap_interface = "1" # 1-based index (recommended), or exact name, or omit to auto-pick + [[devices]] + type = "net" + at = "ethernet" + backend = "pcap:1" # 1-based index (recommended), or exact name; "pcap" alone auto-picks ``` On Windows, if you prefer the full device name (`\Device\NPF_{GUID}`), use a TOML *single-quoted* literal string (backslashes are escape characters in `"double-quoted"` strings): ```toml - pcap_interface = '\Device\NPF_{8D30ACAE-AC0F-4E05-BF89-F35AD7950663}' + backend = 'pcap:\Device\NPF_{8D30ACAE-AC0F-4E05-BF89-F35AD7950663}' ``` 3. **List interfaces**: @@ -63,8 +64,8 @@ Debian/Ubuntu, or the macOS system libpcap). Alternatively specify on the command line (the index form works here too): ``` -./target/release/iris --net-mode pcap --pcap-interface 1 -./target/release/iris --net-mode pcap --pcap-interface eth0 +./target/release/iris --device net@ethernet,backend=pcap:1 +./target/release/iris --device net@ethernet,backend=pcap:eth0 ``` Caveats: @@ -79,26 +80,27 @@ Caveats: as a separate LAN host using `[network] nfs_pcap_ip` (see [HELP.md](HELP.md)). - Wired bridges work best. Many Wi-Fi access points reject the guest's extra MAC address, so bridging onto a wireless interface may not pass traffic. -- Give each emulated machine on the LAN a distinct `[network] mac`. Indy +- Give each emulated machine on the LAN a distinct `mac` on its `net` entry. Indy and Indigo2 keep it in their NVRAM/EEPROM; newer platforms use their own identity and address setup. See [Ethernet MAC address](HELP.md#ethernet-mac-address). -Without `--features pcap`, selecting `mode = "pcap"` logs a warning and falls +Without `--features pcap`, selecting `backend = "pcap"` logs a warning and falls back to the NAT gateway, and `--list-net-interfaces` reports that the feature is missing. -## Stream segment (`mode = "stream"`) +## Stream segment (`backend = "stream:..."`) -`[network] mode = "stream"` plugs the Ethernet into a private segment served -by another program, using the framing of QEMU's `-netdev stream`: each frame -is a 32-bit big-endian length and then the Ethernet frame, without FCS. iris -is the client and connects to `stream`: +A `net` entry with `backend = "stream:..."` plugs the Ethernet into a private +segment served by another program: each frame is a 32-bit big-endian length +and then the Ethernet frame, without FCS. iris is the client and connects to +the peer in the backend: ```toml -[network] -mode = "stream" -stream = "tcp:127.0.0.1:7000" # or "unix:/run/segment.sock" +[[devices]] +type = "net" +at = "ethernet" +backend = "stream:tcp:127.0.0.1:7000" # or "stream:unix:/run/segment.sock" ``` Anything that speaks that framing works as the peer, for example another diff --git a/clanker/irix/irix-install.md b/clanker/irix/irix-install.md index 67efa400c..e067cd1ad 100644 --- a/clanker/irix/irix-install.md +++ b/clanker/irix/irix-install.md @@ -286,7 +286,7 @@ ic serial-wait --timeout 60 "Option?" ic serial-send "5" # Command Monitor ic serial-wait --timeout 10 ">> " # PROM monitor prompt -ic serial-send "setenv -f eaddr 08:00:69:de:ad:01" # optional: IRIS injects [network] mac +ic serial-send "setenv -f eaddr 08:00:69:de:ad:01" # optional: IRIS injects the net device's mac # (default 08:00:69:12:34:56) into a blank slot ic serial-wait --timeout 10 ">> " ic serial-send "setenv -f SystemPartition scsi(0)disk(1)rdisk(0)partition(8)" diff --git a/clanker/irix/networking.md b/clanker/irix/networking.md index 30a84f41f..c05b6268a 100644 --- a/clanker/irix/networking.md +++ b/clanker/irix/networking.md @@ -37,7 +37,7 @@ PROM/kernel from the `eaddr` environment variable, which real hardware stores in battery-backed NVRAM (Indy: DS1386) or a serial EEPROM (Indigo2: 93CS56). Real hardware always ships with one burned in — there's no way to leave it unset — so `Machine::new` (`src/machine.rs`, right after `Hpc3::with_net`) -backdoor-injects `[network] mac` (default `08:00:69:12:34:56`, see +backdoor-injects the `net` device's `mac` (default `08:00:69:12:34:56`, see `config::DEFAULT_MAC`) directly into the emulated chip before the CPU ever runs, rather than requiring a guest-side `setenv`: @@ -114,12 +114,11 @@ bind = "localhost" ## PCAP bridged networking (alternative to NAT) Build with `cargo build --features pcap`. Then in `iris.toml`, set -`[network] mode = "pcap"` and optionally specify a host interface with -`pcap_interface = ""`. The interface choice can be a numeric +a `net` device at `ethernet` with `backend = "pcap"`, optionally `"pcap:"`. The interface choice can be a numeric index (recommended, esp. on Windows where names are `\Device\NPF_{GUID}`), an exact name, or omitted to auto-pick. On Windows, a literal name must use a TOML *single-quoted* literal string because backslashes are escapes in -`"double-quoted"` strings: `pcap_interface = '\Device\NPF_{...}'`. +`"double-quoted"` strings: `backend = 'pcap:\Device\NPF_{...}'`. In PCAP mode the guest is a real L2 host on the physical LAN — there is NO built-in DHCP/DNS/NFS/port-forward. Configure IRIX networking for your real diff --git a/clanker/plans/pcap-release-plan.md b/clanker/plans/pcap-release-plan.md index c8d28e6a5..b64799086 100644 --- a/clanker/plans/pcap-release-plan.md +++ b/clanker/plans/pcap-release-plan.md @@ -237,7 +237,7 @@ can verify locally (build/logic); 🧪 = needs your hands-on test on that OS. - macOS: one-time admin install of **ChmodBPF** (app then runs unprivileged); quit & reopen IRIS after install. Wired-only — many Wi-Fi APs reject the bridged MAC. - Windows: Administrator + a WinPcap-compatible driver (Npcap) installed. -- Default backend stays **NAT** everywhere; PCAP is opt-in via `[network] mode = "pcap"`. +- Default backend stays **NAT** everywhere; PCAP is opt-in via a `net` device with `backend = "pcap"`. ## Resolved decisions (2026-06-20) diff --git a/docs/dev/daynaport.md b/docs/dev/daynaport.md index 74df0d53e..07b24ed8d 100644 --- a/docs/dev/daynaport.md +++ b/docs/dev/daynaport.md @@ -55,7 +55,7 @@ keeps a broken DaynaPort from disturbing the onboard NIC. Inherited from the machine-wide config: -- **Backend selection** (`[network] mode`): `nat` or, in a `--features pcap` +- **Backend selection** (the `net` device at `ethernet`): `nat` or, in a `--features pcap` build, `pcap` — a DaynaPort can be bridged onto a real host interface exactly as `ec0` can. `stream` is refused: it names the onboard Ethernet's peer. - **The NFS export** (`[nfs]`), which is served in-process with no host sockets, diff --git a/docs/dev/ioc3-ethernet.md b/docs/dev/ioc3-ethernet.md index 816d64019..0497cf5c9 100644 --- a/docs/dev/ioc3-ethernet.md +++ b/docs/dev/ioc3-ethernet.md @@ -599,7 +599,7 @@ order (`Ioc3Dma`), decodes the direct window and the 64-bit forms of §8 (`bridge.rs`); the 1-wire part supplies the station address; frames go over iris's shared network link, on the NAT gateway with its BOOTP, TFTP, NFS and port forwards, or on a host interface (`pcap`) or a private -segment (`stream`); `[network] mode = "off"` unplugs the cable. Against +segment (`stream`); a `none` device at `ethernet` unplugs the cable. Against the points above: - Reset (§4.1): after the reset write EMCR reads the reset bit and bit 21 diff --git a/docs/fuel-ip34.md b/docs/fuel-ip34.md index 0506043b0..8b4a50e70 100644 --- a/docs/fuel-ip34.md +++ b/docs/fuel-ip34.md @@ -41,15 +41,15 @@ accepts a raw payload or a supported version-six, single-segment stored or gzip container. The `iris-prom` tool shows what a PROM file holds (`cargo run -p iris-prom -- show FILE`) and writes its payload or one segment (`extract FILE`). The sample attaches a raw IRIX -disk at SCSI ID 1 and writes guest changes to its overlay. `[network] -mode` defaults to `nat`; `off` disconnects the link. +disk at SCSI ID 1 and writes guest changes to its overlay. A `net` +device at `ethernet` picks the backend, `nat` by default; `none` disconnects the link. The L1 reports firmware revision 1.48.1, the one a real Fuel's L1 prints, and the made-up brick serial `EMUN00`; `[machine] l1_revision` and `brick_serial` replace them. Its system serial is the machine's Ethernet address as twelve uppercase hexadecimal digits, the text the PROM converts back into that address, and IRIX's `sysinfo -s` and `lmhostid` -print the address's last four bytes. The address is `[network] mac`, or +print the address's last four bytes. The address is the `mac` of the `net` device at `ethernet`, or for a nonzero `[machine] emu_id` (0 to 4095) `08:00:69:e2:` and the emu_id (emu_id 7: `08:00:69:e2:00:70`, host id `69e20070`), or `08:00:69:12:34:56`; iris prints the id and the address at start-up. diff --git a/docs/indigo2-ip22.md b/docs/indigo2-ip22.md index d34952073..7bc7e93be 100644 --- a/docs/indigo2-ip22.md +++ b/docs/indigo2-ip22.md @@ -19,7 +19,7 @@ No separate build is required — the same `iris` / `iris-gui` binary supports I - **NVRAM and MAC:** the Indigo2 keeps its PROM environment and Ethernet address in a 93CS56 serial EEPROM, not the Indy's DS1386. It is loaded from `nveeprom` (default `nveeprom.bin`, `--nveeprom`) and written back with the monitor's - `nveeprom save` or automatically on normal Stop. `[network] mac` is + `nveeprom save` or automatically on normal Stop. The `mac` of the `net` device at `ethernet` is injected into a blank slot before boot; an existing MAC is retained. - **SCSI:** two WD33C93A controllers. A device goes on the second one at `scsi1/tN` (so `scsi1/t1` is id 1 there, and id 1 can be on both); diff --git a/docs/o2-ip32.md b/docs/o2-ip32.md index aea650f32..c22c85930 100644 --- a/docs/o2-ip32.md +++ b/docs/o2-ip32.md @@ -150,11 +150,11 @@ unless `serial_log_overwrite` is set. The O2's Ethernet is on IRIS's NAT gateway, as on the other machines, and takes the same settings: `nat_subnet`, `[nfs]`, `[[port_forward]]`, -`[network] mac` (the address in the 1-Wire ID chip) and `tftp_dir`. The +`tftp_dir`, and the `mac` of the `net` device at `ethernet` (the address in the 1-Wire ID chip). The guest gets 192.168.0.2 by DHCP, with the gateway and DNS at 192.168.0.1. -`[network] mode = "off"` leaves the Ethernet unplugged; `pcap` bridges it -onto a host interface instead, with no NAT services. `mode = "stream"` with -`stream = "tcp:IP:PORT"` or `"unix:PATH"` puts it on a private segment served +A `none` device at `ethernet` leaves the Ethernet unplugged; `backend = "pcap"` bridges it +onto a host interface instead, with no NAT services. `backend = "stream:tcp:IP:PORT"` or +`"stream:unix:PATH"` puts it on a private segment served by another program. Both are described in [NETWORKING.md](../NETWORKING.md). For a PROM network boot, set `[network] tftp_dir = "DIR"` and boot from the diff --git a/docs/octane-ip30.md b/docs/octane-ip30.md index be3715c35..cbca0e613 100644 --- a/docs/octane-ip30.md +++ b/docs/octane-ip30.md @@ -235,15 +235,15 @@ the built-in 4.17 is new enough for all four. The IOC3 Ethernet (an ICS1890 PHY at MII address 1) is on iris's NAT gateway, with the usual settings: `nat_subnet`, `[nfs]`, `[[port_forward]]`, -`[network] mac` and `tftp_dir`. The gateway answers on host .1 of +`tftp_dir`, and the `mac` of the `net` device at `ethernet`. The gateway answers on host .1 of `nat_subnet`, or, until the first packet routes, on whatever address in its /24 the guest asks for: an IRIX disk configured as 192.0.2.2 with a default route of 192.0.2.3 works with `nat_subnet = "192.0.2.0/24"` unchanged. When -`[network] mac` is unset the station address is 08:00:69:12:34:56; set your -own if more than one Octane shares a network. `[network] mode = "off"` -unplugs the Ethernet; `pcap` bridges it onto a host interface instead, with -no NAT services. `mode = "stream"` with `stream = "tcp:IP:PORT"` or -`"unix:PATH"` puts it on a private segment served by another program. Both +the `mac` is unset the station address is 08:00:69:12:34:56; set your +own if more than one Octane shares a network. A `none` device at `ethernet` +unplugs the Ethernet; `backend = "pcap"` bridges it onto a host interface instead, with +no NAT services. `backend = "stream:tcp:IP:PORT"` or +`"stream:unix:PATH"` puts it on a private segment served by another program. Both are described in [NETWORKING.md](../NETWORKING.md). ## Inspecting the machine diff --git a/docs/tezro-ip53.md b/docs/tezro-ip53.md index d92626ea6..65f53a13a 100644 --- a/docs/tezro-ip53.md +++ b/docs/tezro-ip53.md @@ -266,7 +266,7 @@ The L1 answers the system serial request with `LEMU`, iris's kind digit 2, ten characters into the host id `sysinfo -s` and `lmhostid` print (`d5200420`). At start-up iris prints that id and the serial. A nonzero emu_id also gives the station address `08:00:69:e2:` and the emu_id, unless -`[network] mac` names one; the address is never the id. The board serial in +The `mac` of the `net` device at `ethernet` names one; the address is never the id. The board serial in the node board's L1 record stays `EMUN00`, so the PROM keeps its NVRAM when the emu_id changes. The serial is a synthetic value, not a factory identity; a real unit's is a letter and seven digits, and whether real L1 or L2 diff --git a/docs/xdmcp.md b/docs/xdmcp.md index a7479bd7d..7bb4efc66 100644 --- a/docs/xdmcp.md +++ b/docs/xdmcp.md @@ -6,7 +6,7 @@ session. Behind IRIS's software NAT the guest isn't directly addressable, so a small application-layer gateway (ALG) makes it work — analogous to the FTP PASV gateway. Both **IRIX 5.3 and 6.5** speak XDMCP 1.0; there's no version skew. -This applies to **NAT mode** (`[network] mode = "nat"`). In **PCAP bridged +This applies to **NAT mode** (`net` backend `nat`). In **PCAP bridged mode** the guest is a real LAN host, so XDMCP works directly with no proxy. ## How it works diff --git a/fuel.toml.example b/fuel.toml.example index 8dd20f6c5..291fda077 100644 --- a/fuel.toml.example +++ b/fuel.toml.example @@ -35,12 +35,13 @@ l1_port = 18882 # type = "vpro" # model = "v12" -[network] -# Disconnected cable. For NAT, use mode = "nat". +# Disconnected cable. For NAT, delete this entry. # Keep the installed disk's working ef0 address and default route. # NAT can adopt its static gateway before routing begins. # Initial defaults: guest 192.168.0.2/24, gateway 192.168.0.1. -mode = "off" +[[devices]] +type = "none" +at = "ethernet" # Where each serial port is served: TCP on 127.0.0.1, in place of 8880 and up. [[devices]] diff --git a/iris-gui-README.md b/iris-gui-README.md index b3484edd0..c69011ec7 100644 --- a/iris-gui-README.md +++ b/iris-gui-README.md @@ -172,7 +172,7 @@ The control column holds, top to bottom: the drop-down menus, the capture button and hint, the configuration editor, and a status footer (run state, machine name, MIPS, kernel tick **Hz**, graphics FIFO depth, and the **NET** light for the internal network, or "No network" on a machine with -`[network] mode = "off"`). +a `none` device at `ethernet`). ### Menus diff --git a/iris-gui/core/src/controller/app.rs b/iris-gui/core/src/controller/app.rs index b13dbe0bf..6766439f4 100644 --- a/iris-gui/core/src/controller/app.rs +++ b/iris-gui/core/src/controller/app.rs @@ -137,6 +137,8 @@ pub struct LibraryGroup { pub struct AppController { prefs: GuiSettings, cfg: MachineConfig, + /// The Ethernet read from `cfg`, dropped whenever `cfg` may change: the status bar asks every frame. + ethernet: std::cell::OnceCell, dirty_since: Option, session: SessionController, display: super::display::DisplayController, @@ -233,6 +235,7 @@ impl AppController { let mut app = Self { prefs, cfg, + ethernet: Default::default(), dirty_since: None, session: SessionController::spawn(notify.clone()), display: Default::default(), @@ -281,9 +284,15 @@ impl AppController { /// form is driven by the settings controller. #[doc(hidden)] pub fn config_mut(&mut self) -> &mut MachineConfig { + self.ethernet.take(); &mut self.cfg } + /// Where the selected machine's Ethernet is plugged, read once per change of the config. + pub fn ethernet(&self) -> &crate::model::hardware::Ethernet { + self.ethernet.get_or_init(|| crate::model::hardware::ethernet(&self.cfg)) + } + #[doc(hidden)] pub fn prefs_mut(&mut self) -> &mut GuiSettings { &mut self.prefs @@ -598,6 +607,7 @@ impl AppController { match result { Ok(cfg) => { self.cfg = cfg; + self.ethernet.take(); self.prefs.machines.insert(name.into(), self.cfg.clone()); self.prefs.active_machine = Some(name.into()); match self.prefs.save() { @@ -704,6 +714,7 @@ impl AppController { self.select(&next, fx); } else { self.cfg = MachineConfig::default(); + self.ethernet.take(); if let Err(e) = self.prefs.root().and_then(machines::enter) { fx.push(Effect::Toast(e)); } @@ -1012,6 +1023,7 @@ impl Controller for AppController { }; let dir = self.machine_dir(); let disks_before = self.disk_paths(); + self.ethernet.take(); let (changed, more) = self.settings.apply(a, &mut self.cfg, dir); fx.extend(more); // "New disk…" on a target opens the blank-image form. @@ -1027,7 +1039,7 @@ impl Controller for AppController { self.session.send(Cmd::SetNatSubnet(subnet)); } self.session.send(Cmd::SetPortForwards(self.cfg.port_forward.clone())); - self.session.send(Cmd::SetPcapInterface(self.cfg.network.pcap_interface.clone())); + self.session.send(Cmd::SetPcapInterface(crate::model::hardware::ethernet(&self.cfg).iface)); } } } diff --git a/iris-gui/core/src/controller/help.rs b/iris-gui/core/src/controller/help.rs index 5081c7979..00c5fd758 100644 --- a/iris-gui/core/src/controller/help.rs +++ b/iris-gui/core/src/controller/help.rs @@ -199,7 +199,7 @@ impl AppController { }; // Where the guest mounts from: the NFS server's own address when // bridged; in NAT, the gateway IRIS adopted, else the subnet's. - let pcap = cfg.network.mode == iris::config::NetMode::Pcap; + let pcap = self.ethernet().mode == iris::config::NetMode::Pcap; let gw = if pcap { cfg.network.nfs_pcap_ip.map(|ip| ip.to_string()).unwrap_or_else(|| t!("help-nfs-no-server-ip")) } else { diff --git a/iris-gui/core/src/controller/power.rs b/iris-gui/core/src/controller/power.rs index 1307a95d9..6364d2dd7 100644 --- a/iris-gui/core/src/controller/power.rs +++ b/iris-gui/core/src/controller/power.rs @@ -45,7 +45,7 @@ impl AppController { pub fn status_bar(&self) -> session::StatusBar { // No serial light: the toolbar has the console, and its activity says // nothing the user needs. - self.session().status_bar(self.config(), self.is_dirty()) + self.session().status_bar(self.config(), self.ethernet(), self.is_dirty()) } pub(crate) fn session_apply(&mut self, action: SessionAction, fx: &mut Vec) { diff --git a/iris-gui/core/src/controller/session.rs b/iris-gui/core/src/controller/session.rs index 382e4c780..04e5097a3 100644 --- a/iris-gui/core/src/controller/session.rs +++ b/iris-gui/core/src/controller/session.rs @@ -15,6 +15,7 @@ use iris::config::{MachineConfig, NetMode}; use super::icons::Icon; use super::{ids, Answer, ChoiceSpec, ConfirmSpec, Effect, Enabled, PickSpec, TextSpec}; +use crate::model::hardware::Ethernet; use crate::model::handle::{Cmd, DiskMoved, EmulatorHandle, Evt, NetState, Status}; use crate::model::job::Notify; @@ -208,6 +209,8 @@ pub struct SessionController { /// The config the running machine started with (RAM, CPU and network are /// fixed until it stops). started: Option, + /// The Ethernet of `started`, read once at the start. + started_net: Option, prev_halted: bool, prev_stopped: bool, events: Vec, @@ -278,6 +281,7 @@ impl SessionController { follower: None, starting: false, started: None, + started_net: None, prev_halted: true, prev_stopped: false, events: Vec::new(), @@ -454,8 +458,8 @@ impl SessionController { } } - /// The status bar for the selected machine, whose current config is `cfg`. - pub fn status_bar(&self, cfg: &MachineConfig, unsaved: bool) -> StatusBar { + /// The status bar for the selected machine, whose current config is `cfg` and Ethernet `net`. + pub fn status_bar(&self, cfg: &MachineConfig, net: &Ethernet, unsaved: bool) -> StatusBar { let state = self.run_state(); let s = &self.emu.status; let live = matches!(state, RunState::Running | RunState::Halted); @@ -530,7 +534,8 @@ impl SessionController { } } // Network: the backend is the one the machine started with. - let mode = match shown.network.mode { + let eth = self.started_net.as_ref().filter(|_| started.is_some()).unwrap_or(net); + let mode = match eth.mode { NetMode::Pcap if !iris::build_features::PCAP => NetMode::Nat, m => m, }; @@ -539,12 +544,7 @@ impl SessionController { let (label, state, tip) = match (live, mode) { (false, _) => (t!("status-net"), LightState::Off, t!("status-net-off-tip")), (true, NetMode::Pcap) => { - let iface = shown - .network - .pcap_interface - .clone() - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| t!("common-auto")); + let iface = eth.iface.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| t!("common-auto")); match net { NetState::Active => (t!("status-net-pcap"), LightState::Active, t!("status-net-pcap-active-tip", iface = &iface)), NetState::Idle => (t!("status-net-pcap"), LightState::Fault, t!("status-net-pcap-idle-tip", iface = &iface)), @@ -717,6 +717,7 @@ impl SessionController { self.starting = true; self.prev_halted = true; self.prev_stopped = true; + self.started_net = Some(crate::model::hardware::ethernet(&cfg)); self.started = Some(cfg.clone()); self.emu.send(Cmd::Start(Box::new(cfg))); } @@ -912,7 +913,7 @@ mod tests { let s = SessionController::spawn(Arc::new(crate::model::job::NoWake)); let mut cfg = MachineConfig::default(); cfg.disk_mut(1).unwrap().path = "disks/root.img".into(); - let bar = s.status_bar(&cfg, false); + let bar = s.status_bar(&cfg, &Ethernet::default(), false); assert_eq!(bar.run_state, RunState::Stopped); assert!(bar.mips.is_none()); let disk = bar.lights.iter().find(|l| l.target == LightTarget::Disk { key: 1 }).expect("disk light"); diff --git a/iris-gui/core/src/controller/settings.rs b/iris-gui/core/src/controller/settings.rs index 60430211a..fc1570045 100644 --- a/iris-gui/core/src/controller/settings.rs +++ b/iris-gui/core/src/controller/settings.rs @@ -727,7 +727,7 @@ impl SettingsController { // Network. let modes = net_modes(); - let mode = cfg.network.mode; + let hardware::Ethernet { mode, iface } = hardware::ethernet(cfg); let mut f = vec![Field { id: field::NET_MODE, label: t!("config-net-mode"), @@ -775,7 +775,7 @@ impl SettingsController { label: t!("settings-pcap-interface"), help: Some(t!("settings-pcap-interface-help")), kind: FieldKind::Text { - value: cfg.network.pcap_interface.clone().unwrap_or_default(), + value: iface.unwrap_or_default(), placeholder: t!("common-auto"), error: None, }, @@ -1518,8 +1518,8 @@ fn set(cfg: &mut MachineConfig, field: &'static str, value: Value) -> bool { true } (field::NET_MODE, Value::Index(i)) => match net_modes().get(i) { - Some(&m) if m != cfg.network.mode => { - cfg.network.mode = m; + Some(&m) if m != hardware::ethernet(cfg).mode => { + cfg.set_net(m, None); true } _ => false, @@ -1534,10 +1534,10 @@ fn set(cfg: &mut MachineConfig, field: &'static str, value: Value) -> bool { } (field::PCAP_INTERFACE, Value::Text(s)) => { let v = (!s.trim().is_empty()).then(|| s.trim().to_string()); - if v == cfg.network.pcap_interface { + if v == hardware::ethernet(cfg).iface { return false; } - cfg.network.pcap_interface = v; + cfg.set_net(NetMode::Pcap, v.as_deref()); true } // A value of the wrong kind for the field, or a field with no setter. diff --git a/iris-gui/core/src/model/hardware.rs b/iris-gui/core/src/model/hardware.rs index 204d2283e..a31beec87 100644 --- a/iris-gui/core/src/model/hardware.rs +++ b/iris-gui/core/src/model/hardware.rs @@ -13,6 +13,24 @@ pub fn mc_machine(profile: MachineProfile) -> bool { matches!(profile, MachineProfile::IndyIp24 | MachineProfile::Indigo2Ip22 | MachineProfile::Indigo2Ip28) } +/// The Ethernet's mode and, in PCAP mode, its host interface. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Ethernet { + pub mode: NetMode, + pub iface: Option, +} + +/// The Ethernet's mode and interface as the entry says, without `MachineConfig::network`, which expects a config that +/// validates. It places every device of the machine, so a caller on a frame path keeps the answer until the config changes. +pub fn ethernet(cfg: &MachineConfig) -> Ethernet { + let net = cfg.net_end(); + match net.end() { + Ok((NetMode::Pcap, iface)) => Ethernet { mode: NetMode::Pcap, iface: iface.map(String::from) }, + Ok((mode, _)) => Ethernet { mode, iface: None }, + Err(_) => Ethernet::default(), + } +} + /// Whether `profile` has the Indigo2's motherboard EEPROM (`nveeprom`). The /// Indy keeps its PROM environment in the NVRAM, the O2 in its flash. pub fn has_nveeprom(profile: MachineProfile) -> bool { @@ -123,8 +141,8 @@ pub fn switch_profile(cfg: &mut MachineConfig, from: MachineProfile) { if !matches!(p, MachineProfile::FuelIp34 | MachineProfile::TezroIp53) { cfg.machine.emu_id = 0; } - if mc_machine(p) && cfg.network.mode == NetMode::Off { - cfg.network.mode = NetMode::Nat; + if mc_machine(p) && ethernet(cfg).mode == NetMode::Off { + cfg.set_net(NetMode::Nat, None); } // A serial entry stays only where the new machine has its port. let ports: Vec = iris::dev::serial_dev::ports(p).iter().map(|port| format!("serial{}", port.0)).collect(); @@ -231,6 +249,17 @@ mod tests { use iris::devices::ConfiguredDevice; use iris::topology::scsi_buses; + /// Choosing Stream writes an entry with no peer yet; the mode must read back as Stream so the peer can be typed. + #[test] + fn stream_with_no_peer_yet_reads_as_stream() { + let mut cfg = MachineConfig::default(); + cfg.set_net(NetMode::Stream, None); + assert_eq!(ethernet(&cfg).mode, NetMode::Stream); + cfg.set_net(NetMode::Stream, Some("tcp:127.0.0.1:")); + assert_eq!(ethernet(&cfg).mode, NetMode::Stream); + assert!(cfg.validate().is_err(), "validate reports the peer"); + } + fn switch(cfg: &mut MachineConfig, to: MachineProfile) { let from = cfg.machine.profile; cfg.machine.profile = to; @@ -286,7 +315,7 @@ mod tests { cfg.machine.emu_id = 7; cfg.machine.cpus = Some(1); cfg.jitv2.compile = JitCompile::Sync; - cfg.network.mode = NetMode::Off; + cfg.set_net(NetMode::Off, None); } _ => { cfg.devices.push(nvme()); diff --git a/iris-gui/core/src/model/machines.rs b/iris-gui/core/src/model/machines.rs index 74013b212..632069486 100644 --- a/iris-gui/core/src/model/machines.rs +++ b/iris-gui/core/src/model/machines.rs @@ -165,7 +165,7 @@ pub fn visit_paths(cfg: &mut MachineConfig, mut visit: impl FnMut(&mut String)) } DeviceModel::VirtioSerial(v) => v.ports.iter_mut().filter_map(|p| p.socket.as_mut()).for_each(&mut visit), DeviceModel::Board(b) => b.flash.iter_mut().for_each(&mut visit), - DeviceModel::XioBoard(_) | DeviceModel::PciBridge | DeviceModel::Ice1724 | DeviceModel::Qla2200 | DeviceModel::Ultra64 | DeviceModel::Empty => {} + DeviceModel::Net(_) | DeviceModel::XioBoard(_) | DeviceModel::PciBridge | DeviceModel::Ice1724 | DeviceModel::Qla2200 | DeviceModel::Ultra64 | DeviceModel::Empty => {} } } if let Some(nfs) = &mut cfg.nfs { @@ -584,8 +584,7 @@ pub(crate) mod tests { cfg.jitv2.cache_dir = dir.join("jit-cache").to_string_lossy().into_owned(); cfg.ci_socket = "tcp:127.0.0.1:19851".into(); cfg.debug.log = "scsi,l1d.*,-l1d.hit".into(); - cfg.network.pcap_interface = Some("\\Device\\NPF_{example}".into()); - cfg.network.mac = Some("08:00:69:12:34:56".into()); + cfg.set_net_end(iris::config::NetDevice::of(iris::config::NetMode::Pcap, Some("\\Device\\NPF_{example}"), Some("08:00:69:12:34:56".into()))); save(&root.0, "Indigo2 IP28", &mut cfg).unwrap(); let path = config_path(&root.0, "Indigo2 IP28").unwrap(); let back = read(&path).unwrap(); @@ -598,8 +597,7 @@ pub(crate) mod tests { assert_eq!(back.nveeprom, "nveeprom.bin"); assert_eq!(back.ci_socket, "tcp:127.0.0.1:19851"); assert_eq!(back.debug.log, cfg.debug.log); - assert_eq!(back.network.pcap_interface, cfg.network.pcap_interface); - assert_eq!(back.network.mac, cfg.network.mac); + assert_eq!(back.net_end(), cfg.net_end()); assert_eq!(back.nfs.as_ref().unwrap().shared_dir, root.0.join("shared").to_string_lossy()); assert_eq!(back.serial_log.as_deref(), Some("console.log")); assert!(dir.join("disks").is_dir()); diff --git a/iris-gui/core/src/model/summary.rs b/iris-gui/core/src/model/summary.rs index 1ac96a2f9..7de62b268 100644 --- a/iris-gui/core/src/model/summary.rs +++ b/iris-gui/core/src/model/summary.rs @@ -69,11 +69,11 @@ pub enum Network { /// What the machine's Ethernet is attached to. A build without PCAP runs /// NAT whatever the file says, so `pcap_built` false never reports a bridge. pub fn network(cfg: &MachineConfig, pcap_built: bool) -> Network { - match cfg.network.mode { - NetMode::Pcap if pcap_built => Network::Bridged( - cfg.network.pcap_interface.clone().filter(|s| !s.is_empty())), + let eth = super::hardware::ethernet(cfg); + match eth.mode { + NetMode::Pcap if pcap_built => Network::Bridged(eth.iface.filter(|s| !s.is_empty())), NetMode::Off => Network::Off, - NetMode::Stream => Network::Stream(cfg.network.stream.clone()), + NetMode::Stream => Network::Stream(cfg.net_end().end().ok().and_then(|(_, peer)| peer).map(String::from)), NetMode::Nat | NetMode::Pcap => Network::Nat(cfg.nat_subnet.clone()), } } @@ -136,6 +136,14 @@ mod tests { fn none_readable(_: &str) -> bool { false } + /// The settings panel writes the subnet as it is typed, and the summary reads the network on each change. + #[test] + fn a_half_typed_subnet_does_not_stop_the_network_summary() { + let mut cfg = MachineConfig::default(); + cfg.nat_subnet = Some("192.168.5".into()); + assert_eq!(network(&cfg, false), Network::Nat(Some("192.168.5".into()))); + } + #[test] fn o2_summary_lists_its_own_buses_by_placement() { let cfg = parse(r#" @@ -281,13 +289,11 @@ mod tests { fn network_row_follows_the_mode() { let mut cfg = parse("[machine]\nprofile = \"o2_ip32\"\n"); assert_eq!(network(&cfg, true), Network::Nat(None)); - cfg.network.mode = NetMode::Off; + cfg.set_net(NetMode::Off, None); assert_eq!(network(&cfg, true), Network::Off); - cfg.network.mode = NetMode::Stream; - cfg.network.stream = Some("tcp:127.0.0.1:5555".into()); + cfg.set_net(NetMode::Stream, Some("tcp:127.0.0.1:5555")); assert_eq!(network(&cfg, true), Network::Stream(Some("tcp:127.0.0.1:5555".into()))); - cfg.network.mode = NetMode::Pcap; - cfg.network.pcap_interface = Some(String::new()); + cfg.set_net(NetMode::Pcap, Some("")); assert_eq!(network(&cfg, true), Network::Bridged(None)); assert_eq!(network(&cfg, false), Network::Nat(None)); } diff --git a/iris-gui/locales/en/main.ftl b/iris-gui/locales/en/main.ftl index 6ef85ee2c..8ff5ea7b7 100644 --- a/iris-gui/locales/en/main.ftl +++ b/iris-gui/locales/en/main.ftl @@ -224,7 +224,7 @@ status-net-stream = Stream status-net-stream-active-tip = Stream networking. The guest is sending traffic. status-net-stream-idle-tip = Stream networking. No traffic from the guest yet. status-net-unplugged = No network -status-net-unplugged-tip = This machine has no Ethernet connection ([network] mode = "off"). +status-net-unplugged-tip = This machine has no Ethernet connection (a `none` entry at its ethernet port). status-net-check = Check status-net-check-tip = Diagnose guest networking. # $scale is a number such as 1 or 1.25. diff --git a/iris-gui/src/config_ui.rs b/iris-gui/src/config_ui.rs index cf0ce5f49..542f3fdb9 100644 --- a/iris-gui/src/config_ui.rs +++ b/iris-gui/src/config_ui.rs @@ -13,6 +13,7 @@ use iris::net::nfsudp::NfsVersion; use iris::dev::ng1::vc2_timings::NewportResolution; use crate::i18n::{subtitle, ResponseExt}; +use iris_gui_core::model::hardware::ethernet; use crate::ram::{ram_summary, ram_presets}; /// Memory-tab context: whether the VM is running and what banks were last started with. @@ -1062,7 +1063,7 @@ fn show_network( ui.heading(t!("config-tab-network")); // Only MC machines keep the editable Ethernet address in these battery - // files. Newer platforms use `[network] mac` or their generated default. + // files. Newer platforms use the `net` entry's mac or their generated default. if crate::extra_ui::mc_machine(cfg.machine.profile) { ethernet_address_row(ui, cfg, running); } @@ -1073,12 +1074,13 @@ fn show_network( // without `--features pcap`, where NAT is the only backend — so PCAP must // not appear anywhere in the UI (a dangling, non-functional option risks an // App Store rejection). Such builds also force NAT at runtime regardless of - // a stale `mode = "pcap"` carried in from an imported config. + // a stale `pcap` backend carried in from an imported config. + let mut eth = ethernet(cfg); if build_features::PCAP { Grid::new("net_mode_grid").num_columns(2).striped(true).show(ui, |ui| { ui.label(t!("config-net-mode")); ComboBox::from_id_salt("net_mode") - .selected_text(match cfg.network.mode { + .selected_text(match eth.mode { NetMode::Nat => t!("config-net-mode-nat"), NetMode::Pcap => t!("config-net-mode-pcap"), // These backends and the stream peer are also editable in Advanced. @@ -1086,20 +1088,26 @@ fn show_network( NetMode::Stream => "stream".to_string(), }) .show_ui(ui, |ui| { - ui.selectable_value(&mut cfg.network.mode, NetMode::Nat, t!("config-net-mode-nat")); - ui.selectable_value(&mut cfg.network.mode, NetMode::Pcap, t!("config-net-mode-pcap")); + let (was, mut mode) = (eth.mode, eth.mode); + ui.selectable_value(&mut mode, NetMode::Nat, t!("config-net-mode-nat")); + ui.selectable_value(&mut mode, NetMode::Pcap, t!("config-net-mode-pcap")); + if mode != was { + cfg.set_net(mode, None); + eth = ethernet(cfg); + } }); ui.end_row(); }); - if cfg.network.mode == NetMode::Pcap { - let (a, iface_committed) = pcap_interface_picker(ui, cfg, pcap_ifaces); + if eth.mode == NetMode::Pcap { + let (a, iface_committed) = pcap_interface_picker(ui, cfg, pcap_ifaces, eth.iface.clone()); if let ConfigAction::RefreshPcapIfaces = a { out.action = a; } if iface_committed { out.iface_changed = true; out.changed = true; + eth = ethernet(cfg); } ui.colored_label(Color32::from_rgb(0xd0, 0xa0, 0x40), t!("config-net-pcap-note")); @@ -1125,7 +1133,7 @@ fn show_network( // gateway. In PCAP bridged mode the guest is directly on your real LAN, so // they're meaningless — hide the whole block. (The NFS share further below // works in both modes.) - if cfg.network.mode != NetMode::Pcap { + if eth.mode != NetMode::Pcap { subtitle(ui, t!("config-net-nat-subtitle")); ui.add_space(6.0); @@ -1351,7 +1359,7 @@ fn show_network( // on the bridged LAN (see `NfsVirtualHost`), so it needs its own IP on the // guest's subnet. NAT mode mounts from the gateway and doesn't use this. The // change takes effect on the next Start (the virtual host is built then). - if cfg.nfs.is_some() && cfg.network.mode == NetMode::Pcap { + if cfg.nfs.is_some() && eth.mode == NetMode::Pcap { out.changed |= pcap_nfs_ip_row(ui, cfg, host); } if let Some(nfs) = cfg.nfs.as_mut() { @@ -1379,7 +1387,7 @@ fn show_network( // export is the single root, so the path is just "/". NAT: the gateway IP // of the configured subnet. PCAP: the in-process NFS server's own virtual // LAN IP (the guest is bridged, so there's no NAT gateway to mount from). - let gw = if cfg.network.mode == NetMode::Pcap { + let gw = if eth.mode == NetMode::Pcap { cfg.network.nfs_pcap_ip .map(|ip| ip.to_string()) .unwrap_or_else(|| t!("config-nfs-ip-placeholder")) @@ -1674,13 +1682,13 @@ fn pcap_interface_picker( ui: &mut Ui, cfg: &mut MachineConfig, pcap_ifaces: &Option, String>>, + current: Option, ) -> (ConfigAction, bool) { let mut action = ConfigAction::None; let mut committed = false; // Selected text for the combo: the current name, "Auto-pick", or the raw // value if it's something not in the list (e.g. an index or manual name). - let current = cfg.network.pcap_interface.clone(); let selected_text = match ¤t { None => t!("config-pcap-auto"), Some(v) if v.is_empty() => t!("config-pcap-auto"), @@ -1697,7 +1705,7 @@ fn pcap_interface_picker( // Auto-pick entry. let mut is_auto = current.as_deref().unwrap_or("").is_empty(); if ui.selectable_label(is_auto, t!("config-pcap-auto")).clicked() { - cfg.network.pcap_interface = None; + cfg.set_net(NetMode::Pcap, None); is_auto = true; committed = true; } @@ -1709,7 +1717,7 @@ fn pcap_interface_picker( for iface in list { let selected = current.as_deref() == Some(iface.name.as_str()); if ui.selectable_label(selected, iface.summary()).clicked() { - cfg.network.pcap_interface = Some(iface.name.clone()); + cfg.set_net(NetMode::Pcap, Some(&iface.name)); committed = true; } } @@ -1743,7 +1751,7 @@ fn pcap_interface_picker( .hint_text(t!("config-pcap-manual-hint")) .desired_width(260.0)); if resp.changed() { - cfg.network.pcap_interface = if manual.trim().is_empty() { None } else { Some(manual) }; + cfg.set_net(NetMode::Pcap, Some(manual.trim()).filter(|m| !m.is_empty())); } // Commit (reopen the live capture) only when the field loses focus, so a // running reswap doesn't fire on every keystroke. diff --git a/iris-gui/src/extra_ui.rs b/iris-gui/src/extra_ui.rs index aa43e5bd2..f061aa605 100644 --- a/iris-gui/src/extra_ui.rs +++ b/iris-gui/src/extra_ui.rs @@ -178,9 +178,20 @@ pub fn show(ui: &mut Ui, cfg: &mut MachineConfig, running: bool) { if !mc_machine(cfg.machine.profile) { modes.push(NetMode::Off); } - choice(ui, &t!("extra-network-mode"), "network_mode", &mut cfg.network.mode, &modes); - text(ui, &t!("extra-mac"), &mut cfg.network.mac); - text(ui, &t!("extra-stream"), &mut cfg.network.stream); + let net = cfg.net_end(); + let (mode, arg) = net.end().map_or((NetMode::Nat, None), |(m, a)| (m, a.map(String::from))); + let (mut new_mode, mut mac) = (mode, net.mac.clone()); + let peer = arg.clone().filter(|_| mode == NetMode::Stream); + let mut stream = peer.clone(); + choice(ui, &t!("extra-network-mode"), "network_mode", &mut new_mode, &modes); + text(ui, &t!("extra-mac"), &mut mac); + text(ui, &t!("extra-stream"), &mut stream); + if new_mode != mode { + cfg.set_net(new_mode, None); + } else if mac != net.mac || stream != peer { + let arg = if mode == NetMode::Stream { stream } else { arg }; + cfg.set_net_end(iris::config::NetDevice::of(mode, arg.as_deref(), mac)); + } let mut hold = cfg.network.rx_hold.unwrap_or(true); if ui.checkbox(&mut hold, t!("extra-rx-hold")).changed() { cfg.network.rx_hold = Some(hold); diff --git a/iris-gui/src/main.rs b/iris-gui/src/main.rs index 313e5ddff..4a171f54a 100644 --- a/iris-gui/src/main.rs +++ b/iris-gui/src/main.rs @@ -597,9 +597,9 @@ impl App { let started = self.app.session().started_config().cloned(); self.started_banks = started.as_ref().map(|c| c.banks); self.started_cpu = started.as_ref().map(|c| c.cpu()); - self.launched_net = started.as_ref().map(|c| match c.network.mode { + self.launched_net = started.as_ref().map(|c| match c.network().mode { iris::config::NetMode::Pcap if !iris::build_features::PCAP => (iris::config::NetMode::Nat, None), - mode => (mode, c.network.pcap_interface.clone()), + mode => (mode, c.network().pcap_interface), }); // Drop the previous run's textures so its last frame never // flashes before the new run renders. @@ -1265,7 +1265,7 @@ impl App { _ => (t!("status-net"), t!("status-net-off-tip")), }; // A machine with no Ethernet has no light: nothing can carry traffic. - let net_mode = if running { backend.as_ref().map(|(m, _)| *m) } else { Some(self.app.config().network.mode) }; + let net_mode = if running { backend.as_ref().map(|(m, _)| *m) } else { Some(self.app.ethernet().mode) }; let unplugged = net_mode == Some(NetMode::Off); // "check" diagnoses the guest IP against the NAT subnet — only meaningful // in NAT mode, so it's hidden in PCAP. @@ -1844,9 +1844,9 @@ impl App { if out.net.iface_changed && matches!(self.launched_net.as_ref(), Some((iris::config::NetMode::Pcap, _))) { - self.app.session().handle().send(Cmd::SetPcapInterface(self.app.config().network.pcap_interface.clone())); + self.app.session().handle().send(Cmd::SetPcapInterface(iris_gui_core::model::hardware::ethernet(&self.app.config()).iface)); if let Some((_, iface)) = self.launched_net.as_mut() { - *iface = self.app.config().network.pcap_interface.clone(); + *iface = iris_gui_core::model::hardware::ethernet(&self.app.config()).iface; } } if let Some(p) = out.net.prompt { @@ -2116,7 +2116,7 @@ impl App { // gateway (there is none). NAT mode: the gateway IRIS live-adopted while // running, else the gateway derived from the configured subnet, else the // documented default. (Matches network_check_window's derivation.) - let pcap = self.app.config().network.mode == iris::config::NetMode::Pcap; + let pcap = self.app.ethernet().mode == iris::config::NetMode::Pcap; let gw = if pcap { self.app.config() .network @@ -2435,7 +2435,7 @@ impl App { ui.end_row(); ui.label(t!("welcome-network")); // On a build without PCAP support, the runtime always uses NAT - // regardless of any imported `mode = "pcap"`, and the UI must never + // regardless of any imported `pcap` backend, and the UI must never // surface PCAP (`summary::network` reports NAT there). ui.label(match summary::network(&self.app.config(), iris::build_features::PCAP) { summary::Network::Bridged(iface) => { diff --git a/iris.toml b/iris.toml index a75d1974f..c27e63c38 100644 --- a/iris.toml +++ b/iris.toml @@ -168,10 +168,10 @@ bind = "localhost" #camera_index = 0 # ── Networking backend ──────────────────────────────────────────────────────── -# mode = "nat" (default) : built-in software NAT gateway (DHCP/DNS/ICMP/TCP/UDP +# backend = "nat" (default): built-in software NAT gateway (DHCP/DNS/ICMP/TCP/UDP # + the [[port_forward]] rules above). No host # privileges or extra libraries needed. -# mode = "pcap" : bridge the guest's raw Ethernet frames onto a real +# backend = "pcap" : bridge the guest's raw Ethernet frames onto a real # host interface (requires building with --features # pcap and elevated privileges). The guest becomes a # real L2 host on your LAN; NAT services and port @@ -180,7 +180,7 @@ bind = "localhost" # List candidate interfaces: iris --list-net-interfaces # (or, in the monitor: net interfaces) # -# pcap_interface accepts EITHER: +# "pcap:IFACE" takes EITHER: # - a 1-based index from --list-net-interfaces, e.g. "1" (easiest, esp. Windows) # - an exact device name, e.g. "eth0" / "en0" # - omit it entirely: if launched from a terminal you'll get an interactive @@ -191,20 +191,19 @@ bind = "localhost" # escape characters inside a normal "double-quoted" TOML string, so you MUST use a # 'single-quoted' TOML *literal* string (no escaping), or just use the index. # -# NOTE: the [network] header below is REQUIRED. If you uncomment `mode`/ -# `pcap_interface` but leave `[network]` commented out, the keys land in the -# top-level table and are rejected as unknown (the emulator will refuse to -# start) — they only take effect under the [network] table. - -[network] -mode = "nat" -#pcap_interface = "1" # by index (recommended) -#pcap_interface = "wlan0" # by name (Linux/macOS) -#pcap_interface = '\Device\NPF_{385F30D0-9166-45D3-BBC6-F1D9C5300AF9}' # Windows (literal '...' string!) +# The host end is a `net` device at the Ethernet port, which is NAT unless +# you place one: backend = "nat", "pcap", "pcap:IFACE", "stream:tcp:IP:PORT", +# or "stream:unix:PATH". `type = "none"` at the port unplugs it; the MAC is then the +# machine's own. +# # Ethernet station address for ec0. Defaults to 08:00:69:12:34:56 (SGI's OUI) # when unset. Backdoor-injected into NVRAM (Indy) / serial EEPROM (Indigo2) # before boot — no need to `setenv eaddr` by hand at the PROM monitor. -#mac = "08:00:69:12:34:56" +#[[devices]] +#type = "net" +#at = "ethernet" +#backend = "nat" +#mac = "08:00:69:12:34:56" # N64 development board (Ultra64 GIO card). Needs the ultra64 branch of # github.com/techomancer/gopher64, which maps the shared-memory bridge diff --git a/irix-extract/README.md b/irix-extract/README.md index a9bb5317b..5d8b052cd 100644 --- a/irix-extract/README.md +++ b/irix-extract/README.md @@ -39,7 +39,6 @@ and rsh-dir (cli option `--rsh-dir` or toml setting `network.rsh_dir`) to the fo ``` [network] -mode = "nat" tftp_dir = 'irix-extract' rsh_dir = 'irix-extract' diff --git a/onyx2.toml.example b/onyx2.toml.example index ccb81dfcb..eae1ea295 100644 --- a/onyx2.toml.example +++ b/onyx2.toml.example @@ -25,9 +25,10 @@ controller_store = "ignore/onyx2/controller.raw" # image here to override it. # io_prom = "ignore/onyx2/io6prom.img" -[network] -# Disconnected cable. For NAT, use mode = "nat". -mode = "off" +# Disconnected cable. For NAT, delete this entry. +[[devices]] +type = "none" +at = "ethernet" # Where each serial port is served: TCP on 127.0.0.1, in place of 8880 and up. [[devices]] diff --git a/origin200.toml.example b/origin200.toml.example index 7b0de1c67..18c3d77ef 100644 --- a/origin200.toml.example +++ b/origin200.toml.example @@ -21,9 +21,10 @@ cpu = "r10000" flash = "ignore/origin200/flash.raw" controller_store = "ignore/origin200/controller.raw" -[network] -# Disconnected cable. For NAT, use mode = "nat". -mode = "off" +# Disconnected cable. For NAT, delete this entry. +[[devices]] +type = "none" +at = "ethernet" # Where each serial port is served: TCP on 127.0.0.1, in place of 8880 and up. [[devices]] diff --git a/origin2000.toml.example b/origin2000.toml.example index 04e2957b4..894794842 100644 --- a/origin2000.toml.example +++ b/origin2000.toml.example @@ -25,9 +25,10 @@ controller_store = "ignore/origin2000/controller.raw" # image here to override it. # io_prom = "ignore/origin2000/io6prom.img" -[network] -# Disconnected cable. For NAT, use mode = "nat". -mode = "off" +# Disconnected cable. For NAT, delete this entry. +[[devices]] +type = "none" +at = "ethernet" # Where each serial port is served: TCP on 127.0.0.1, in place of 8880 and up. [[devices]] diff --git a/origin3200.toml.example b/origin3200.toml.example index f78956ef9..eb45059d8 100644 --- a/origin3200.toml.example +++ b/origin3200.toml.example @@ -19,8 +19,10 @@ nodes = 2 console = "l1" l1_port = 18882 -[network] -mode = "off" +# Disconnected cable. For NAT, delete this entry. +[[devices]] +type = "none" +at = "ethernet" # Where each serial port is served: TCP on 127.0.0.1, in place of 8880 and up. [[devices]] diff --git a/src/config.rs b/src/config.rs index 415481285..c86ff2fbc 100644 --- a/src/config.rs +++ b/src/config.rs @@ -259,7 +259,7 @@ pub struct DaynaportParams { pub subnet: NatSubnet, } -/// Default Ethernet station address for `ec0` when `[network] mac` is unset. +/// Default Ethernet station address for `ec0` when the `net` entry has no `mac`. /// SGI's registered OUI (08:00:69) plus an arbitrary host part; matches the /// address used throughout `clanker/irix/networking.md` and CI test fixtures. pub const DEFAULT_MAC: [u8; 6] = [0x08, 0x00, 0x69, 0x12, 0x34, 0x56]; @@ -365,9 +365,8 @@ pub enum NetMode { /// No Ethernet: the adapter is not plugged into anything. Not on the /// Indy and Indigo2, which always have a network (`MachineConfig::validate`). Off, - /// A private segment carried over a stream socket in QEMU's `-netdev - /// stream` framing, to a peer that serves it (`[network] stream`). iris - /// provides no gateway services on it. + /// A private segment carried over a stream socket, each frame behind a 4-byte length, to a peer that serves it + /// (`backend = "stream:..."`). iris provides no gateway services on it. Stream, } @@ -390,7 +389,7 @@ pub struct NetworkConfig { /// PCAP-only virtual IP for the in-process NFS server (so a bridged guest can /// mount it). None = NFS-in-PCAP not configured. pub nfs_pcap_ip: Option, - /// Ethernet station address, resolved from `[network] mac` and the + /// Ethernet station address, resolved from the `net` entry's `mac` and the /// platform's default identity. MC machines inject it into their /// NVRAM/EEPROM; newer platforms pass it to their onboard adapter. pub mac: [u8; 6], @@ -424,36 +423,16 @@ impl Default for NetworkConfig { } } -/// `[network]` section: backend selection and PCAP options. +/// `[network]` section: the gateway's services. The backend and the MAC belong to the `net` entry at the Ethernet port. #[derive(Debug, Clone, Serialize, Deserialize, Default)] #[serde(deny_unknown_fields)] pub struct NetworkSection { - /// Backend: "nat" (default), "pcap", "stream" (with `stream`) or "off", - /// which unplugs the Ethernet (not on the Indy and Indigo2). - #[serde(default)] - pub mode: NetMode, - /// Host interface to bridge onto in PCAP mode (e.g. "eth0", "en0"). - /// Run `iris --list-net-interfaces` to enumerate candidates. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub pcap_interface: Option, /// PCAP-only: the virtual LAN IP the in-process NFS server answers on, so a /// bridged guest (which is directly on your real LAN, with no NAT gateway to /// reach) can mount it. None = NFS-in-PCAP not configured. NAT mode ignores /// this and serves NFS at the gateway IP instead. #[serde(default, skip_serializing_if = "Option::is_none")] pub nfs_pcap_ip: Option, - /// Ethernet station address for the onboard adapter, e.g. - /// "08:00:69:12:34:56" (SGI's registered OUI). Defaults to - /// `08:00:69:12:34:56` when unset, or on a machine that takes - /// `[machine] emu_id` to the address that gives. Real hardware has no way to leave this - /// unset — every SGI ships with a MAC burned into NVRAM (Indy) or a serial - /// EEPROM (Indigo2) — so iris backdoor-injects it into the emulated - /// NVRAM/EEPROM before boot rather than requiring a guest-side `setenv`. - /// On Indy this only patches NVRAM if the `eaddr` slot is still blank - /// (00:00:00:00:00:00), so it never clobbers a value you've already set - /// from the PROM monitor and saved with `rtc save`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mac: Option, /// Directory served read-only over TFTP (UDP 69) at the gateway address, so /// the PROM can `boot -f bootp()`. Unset disables TFTP. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -469,10 +448,74 @@ pub struct NetworkSection { /// driver's interrupt pass. Default true. #[serde(default, skip_serializing_if = "Option::is_none")] pub rx_hold: Option, - /// With `mode = "stream"`: the server of the private segment, as - /// `tcp:IP:PORT` or `unix:PATH` (QEMU `-netdev stream` framing). + /// The older `mode`, `pcap_interface`, `stream` and `mac`, until `legacy` turns them into a `net` entry. + #[serde(default, rename = "mode", skip_serializing)] + pub legacy_mode: Option, + #[serde(default, rename = "pcap_interface", skip_serializing)] + pub legacy_pcap_interface: Option, + #[serde(default, rename = "stream", skip_serializing)] + pub legacy_stream: Option, + #[serde(default, rename = "mac", skip_serializing)] + pub legacy_mac: Option, +} + +/// A `net` entry: the host end of an Ethernet port, and its station address. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct NetDevice { + /// `nat` (the built-in gateway), `pcap` or `pcap:IFACE` (a host interface), `stream:tcp:IP:PORT` or + /// `stream:unix:PATH` (a private segment). `none` at the port unplugs it. + #[serde(default = "nat")] + pub backend: String, + /// The port's station address, e.g. "08:00:69:12:34:56" (SGI's OUI). Unset: the machine's own, which iris + /// writes into the NVRAM or EEPROM where the PROM reads it, unless that already holds one. #[serde(default, skip_serializing_if = "Option::is_none")] - pub stream: Option, + pub mac: Option, +} + +fn nat() -> String { "nat".into() } + +impl Default for NetDevice { + fn default() -> Self { NetDevice { backend: nat(), mac: None } } +} + +impl NetDevice { + /// The mode `backend` names, with the interface or peer after its colon. `none` is only what an emptied port reads + /// as; `check` refuses it in an entry. + pub fn end(&self) -> Result<(NetMode, Option<&str>), String> { + match self.backend.as_str() { + "nat" => Ok((NetMode::Nat, None)), + "none" => Ok((NetMode::Off, None)), + "pcap" => Ok((NetMode::Pcap, None)), + b if b.starts_with("stream:") => Ok((NetMode::Stream, Some(&b["stream:".len()..]))), + b => match crate::backend::split(b)? { + ("pcap", iface) => Ok((NetMode::Pcap, Some(iface))), + (kind, _) => Err(format!("backend \"{b}\": no host end {kind}; the ends are nat, pcap, pcap:IFACE, stream:tcp:IP:PORT and stream:unix:PATH")), + }, + } + } + + pub fn check(&self) -> Result<(), String> { + if self.backend == "none" { + return Err("backend none is not a host end: unplug the port with type = \"none\" at it".into()); + } + if let (NetMode::Stream, Some(peer)) = self.end()? { + crate::net::stream::StreamEndpoint::parse(peer).map_err(|e| format!("backend {}: {e}", self.backend))?; + } + self.mac.as_deref().map_or(Ok(()), |m| parse_mac(m).map(drop).map_err(|e| format!("mac: {e}"))) + } + + /// The entry for `mode`, with the interface or peer it takes. + pub fn of(mode: NetMode, arg: Option<&str>, mac: Option) -> NetDevice { + let backend = match (mode, arg) { + (NetMode::Nat, _) => nat(), + (NetMode::Off, _) => "none".into(), + (NetMode::Pcap, Some(i)) if !i.is_empty() => format!("pcap:{i}"), + (NetMode::Pcap, _) => "pcap".into(), + (NetMode::Stream, peer) => format!("stream:{}", peer.unwrap_or_default()), + }; + NetDevice { backend, mac } + } } /// Where VINO's video-in capture should come from. @@ -1489,7 +1532,7 @@ pub struct O2Section { /// Deprecated: `[clock] fixed_mhz`, which is half of it. #[serde(default, skip_serializing_if = "Option::is_none")] pub cpu_mhz: Option, - /// Deprecated: `[network] mode = "off"` when false. + /// Deprecated: `none` at the Ethernet port when false. #[serde(default, skip_serializing_if = "Option::is_none")] pub net: Option, /// Deprecated: `[[port_forward]]`. @@ -2479,7 +2522,7 @@ pub struct MachineConfig { #[serde(default)] pub vnc: VncConfig, - /// Networking backend selection (`[network]` section). Defaults to NAT. + /// The NAT gateway's services (`[network]` section). #[serde(default)] pub network: NetworkSection, @@ -3031,7 +3074,7 @@ impl MachineConfig { /// /// A *missing* file is fine (defaults are used). A file that exists but /// fails to parse is **fatal**: previously we silently fell back to - /// defaults, which hid config mistakes — e.g. a Windows `pcap_interface` + /// defaults, which hid config mistakes — e.g. a Windows pcap interface /// with unescaped backslashes would discard the entire config, so the /// emulator would quietly auto-pick a different interface and run with NAT /// instead of the settings the user wrote. @@ -3060,9 +3103,9 @@ impl MachineConfig { msg.push_str( "\n\nhint: backslashes are escape characters inside a \"double-quoted\" TOML string.\n\ For a Windows pcap interface, either use the numeric index from\n\ - `iris --list-net-interfaces` (e.g. pcap_interface = \"1\") or a TOML\n\ + `iris --list-net-interfaces` (e.g. backend = \"pcap:1\") or a TOML\n\ 'single-quoted' literal string:\n\ - \n pcap_interface = '\\Device\\NPF_{...}'\n" + \n backend = 'pcap:\\Device\\NPF_{...}'\n" ); } Err(msg) @@ -3384,8 +3427,8 @@ impl MachineConfig { }; return Err(format!("[[devices]] daynaport at \"{at}\": not available on {on} (its Ethernet is built in)")); } - if self.network.mode == NetMode::Stream { - return Err(format!("[[devices]] daynaport at \"{at}\": cannot join a stream segment: [network] stream names the onboard Ethernet's peer")); + if self.net_end().end()?.0 == NetMode::Stream { + return Err(format!("[[devices]] daynaport at \"{at}\": cannot join a stream segment: the onboard Ethernet's backend names its peer")); } } for d in &self.devices { @@ -3393,6 +3436,7 @@ impl MachineConfig { DeviceModel::TestDevice(t) => t.run().map(|_| ())?, DeviceModel::VirtioSerial(v) => v.check()?, DeviceModel::Virtio9p(v) => v.check()?, + DeviceModel::Net(n) => n.check().map_err(|e| format!("[[devices]] net: {e}"))?, _ => {} } } @@ -3518,25 +3562,14 @@ impl MachineConfig { } } } - match (self.network.mode, self.machine.profile) { - (NetMode::Off, p) if !matches!(p, MachineProfile::O2Ip32 | MachineProfile::OctaneIp30 | MachineProfile::FuelIp34 | MachineProfile::TezroIp53) && !p.is_ip35_bricks() && !p.is_ip27() => { - return Err("network.mode = \"off\" is only available on the O2, the Octane, the Fuel, the Tezro, the Origin 3200, the Origin 200, the Origin 2000 and the Onyx2 for now; the Indy and Indigo2 always have their Ethernet".into()); - } - (NetMode::Stream, _) => { - let ep = self.network.stream.as_deref() - .ok_or_else(|| "network.mode = \"stream\" needs [network] stream = \"tcp:IP:PORT\" or \"unix:PATH\"".to_string())?; - crate::net::stream::StreamEndpoint::parse(ep).map_err(|e| format!("network.stream: {e}"))?; - } - _ => {} + if self.net_end().end()?.0 == NetMode::Off && matches!(self.machine.profile, MachineProfile::IndyIp24 | MachineProfile::Indigo2Ip22 | MachineProfile::Indigo2Ip28) { + return Err("the Indy and Indigo2 always have their Ethernet: an empty ethernet slot is not available on them".into()); } if let Some(ref s) = self.nat_subnet { if let Err(e) = parse_nat_subnet(s) { return Err(format!("nat_subnet \"{}\": {}", s, e)); } } - if let Some(ref mac) = self.network.mac { - parse_mac(mac).map_err(|e| format!("network.mac: {}", e))?; - } let emu_id = self.machine.emu_id; if emu_id > crate::identity::EMU_ID_MAX { return Err(format!("machine identity: emu_id must be 0 to {}, not {emu_id}", crate::identity::EMU_ID_MAX)); @@ -3639,7 +3672,7 @@ impl MachineConfig { Ok(()) } - /// The station address when `[network] mac` is unset: the address + /// The station address when the `net` entry has no `mac`: the address /// `[machine] emu_id` gives on a machine that takes it, else /// [`DEFAULT_MAC`], which is also what emu_id 0 keeps. fn default_station_mac(&self) -> [u8; 6] { @@ -3666,23 +3699,64 @@ impl MachineConfig { .expect("nat_subnet: validate() should have caught this"); NatSubnet { gateway_ip, client_ip, netmask } }); - let mac = self.network.mac.as_deref() - .map(|s| parse_mac(s).expect("network.mac: validate() should have caught this")) + let net = self.net_end(); + let (mode, arg) = net.end().expect("net backend: validate() should have caught this"); + let mac = net.mac.as_deref() + .map(|s| parse_mac(s).expect("net mac: validate() should have caught this")) .unwrap_or_else(|| self.default_station_mac()); NetworkConfig { nfs: self.nfs.clone(), port_forward: self.port_forward.clone(), nat_subnet, - mode: self.network.mode, - pcap_interface: self.network.pcap_interface.clone(), + mode, + pcap_interface: arg.filter(|_| mode == NetMode::Pcap).map(String::from), nfs_pcap_ip: self.network.nfs_pcap_ip, mac, tftp_dir: self.network.tftp_dir.as_ref().map(std::path::PathBuf::from), rsh_dir: self.network.rsh_dir.as_ref().map(std::path::PathBuf::from), rx_hold: self.network.rx_hold.unwrap_or(true), - stream: self.network.stream.clone(), + stream: arg.filter(|_| mode == NetMode::Stream).map(String::from), } } + + /// The device a file or the command line placed at port `alias`, not the port's default. + fn port_device(&self, alias: &str) -> Option { + DevicePlacement::lenient(self, &self.devices).port(alias).filter(|(_, d)| !d.default).map(|(_, d)| d.device.clone()) + } + + /// Put `device` at port `alias` in place of the entry there; none removes it. + fn set_port_device(&mut self, alias: &str, device: Option) { + let at = DevicePlacement::lenient(self, &self.devices).port(alias).filter(|(_, d)| !d.default).map(|(i, _)| i); + match (at, device) { + (Some(i), Some(d)) => self.devices[i].device = d, + (Some(i), None) => { self.devices.remove(i); } + (None, Some(d)) => self.devices.push(ConfiguredDevice::new(alias, d)), + (None, None) => {} + } + } + + /// The `net` entry at the Ethernet port: the one a file places there, else the default. + pub fn net_end(&self) -> NetDevice { + match self.port_device("ethernet") { + Some(DeviceModel::Net(n)) => n, + Some(DeviceModel::Empty) => NetDevice::of(NetMode::Off, None, None), + _ => NetDevice::default(), + } + } + + /// Plug the Ethernet port into `mode`, with the interface or peer it takes; the port's MAC stays. + pub fn set_net(&mut self, mode: NetMode, arg: Option<&str>) { + self.set_net_end(NetDevice::of(mode, arg, self.net_end().mac)); + } + + /// Put `net` on the Ethernet port. An entry that says nothing is dropped, and `none` empties the port, MAC and all. + pub fn set_net_end(&mut self, net: NetDevice) { + let device = match net.end() { + Ok((NetMode::Off, _)) => Some(DeviceModel::Empty), + _ => (net != NetDevice::default()).then_some(DeviceModel::Net(net)), + }; + self.set_port_device("ethernet", device); + } } // --------------------------------------------------------------------------- @@ -3838,17 +3912,6 @@ pub struct Cli { #[arg(long = "nat-subnet", value_name = "CIDR")] pub nat_subnet: Option, - /// Networking backend: "nat" (default, software gateway), "pcap" - /// (bridge onto a real host interface; requires --features pcap), - /// "stream" (a private segment; needs `[network] stream`) or "off". - #[arg(long = "net-mode", value_name = "MODE")] - pub net_mode: Option, - - /// Host interface to bridge onto in PCAP mode (e.g. eth0, en0). - /// Implies --net-mode pcap. List candidates with --list-net-interfaces. - #[arg(long = "pcap-interface", value_name = "IFACE")] - pub pcap_interface: Option, - /// Check the configuration (`--config`, with any other options applied) /// without starting the machine: that it parses, that its settings agree, /// that its files and directories exist and its ports differ. Exits 0 if @@ -3936,6 +3999,12 @@ pub struct Cli { #[arg(long = "serial-log-b", value_name = "FILE", hide = true)] pub serial_log_b: Option, + /// The older network options, which become the `net` entry at the Ethernet port (see `legacy`). + #[arg(long = "net-mode", value_name = "MODE", hide = true)] + pub net_mode: Option, + #[arg(long = "pcap-interface", value_name = "IFACE", hide = true)] + pub pcap_interface: Option, + /// Physical host keyboard: `ansi` (default), `iso` or `jis`. Use `jis` /// for a Japanese keyboard with the PROM's `keybd` set to JP. #[arg(long = "keyboard", value_name = "LAYOUT")] @@ -4087,6 +4156,8 @@ impl Cli { None => cfg.devices.push(e), } } + // A flag beats the file, whether the file wrote an older key or an entry at the port. + legacy::net_flags(&mut cfg, self.net_mode, self.pcap_interface.as_deref()); if self.no_write_cache { for dev in cfg.devices.iter_mut().filter_map(|d| d.device.scsi_mut()).filter(|d| d.kind() == ScsiKind::Disk) { @@ -4151,16 +4222,6 @@ impl Cli { if self.cheritest_dump_hook { cfg.cheritest_dump_hook = true; } if let Some(ref s) = self.nat_subnet { cfg.nat_subnet = Some(s.clone()); } - if let Some(m) = self.net_mode { cfg.network.mode = m; } - if let Some(ref iface) = self.pcap_interface { - cfg.network.pcap_interface = Some(iface.clone()); - // Specifying an interface implies PCAP mode unless the user also - // explicitly asked for NAT. - if self.net_mode.is_none() { - cfg.network.mode = NetMode::Pcap; - } - } - cfg } } @@ -4802,26 +4863,26 @@ mod export_tests { assert!(cfg.validate().unwrap_err().contains("daynaport")); } - /// `mode = "stream"` needs a parseable `stream` peer, on every machine. + /// A `stream:` backend needs a parseable peer, on every machine. #[test] fn stream_mode_needs_a_peer() { for profile in [MachineProfile::default(), MachineProfile::O2Ip32, MachineProfile::OctaneIp30] { let mut cfg = MachineConfig::default(); cfg.machine.profile = profile; if profile != MachineProfile::default() { cfg.set_cpu(profile.cpus()[0]); } - cfg.network.mode = NetMode::Stream; - assert!(cfg.validate().unwrap_err().contains("needs [network] stream"), "{profile:?}"); - cfg.network.stream = Some("tcp:nope".into()); - assert!(cfg.validate().unwrap_err().contains("network.stream"), "{profile:?}"); - cfg.network.stream = Some("udp:127.0.0.1:7000".into()); - assert!(cfg.validate().unwrap_err().contains("network.stream"), "{profile:?}"); - cfg.network.stream = Some("tcp:127.0.0.1:7000".into()); + cfg.set_net(NetMode::Stream, None); + assert!(cfg.validate().unwrap_err().contains("backend stream:"), "{profile:?}"); + for bad in ["tcp:nope", "udp:127.0.0.1:7000"] { + cfg.set_net(NetMode::Stream, Some(bad)); + assert!(cfg.validate().unwrap_err().contains("backend stream:"), "{profile:?}"); + } + cfg.set_net(NetMode::Stream, Some("tcp:127.0.0.1:7000")); cfg.validate().unwrap_or_else(|e| panic!("{profile:?}: {e}")); } - let mut cfg = MachineConfig::from_toml_str("[network]\nmode = \"stream\"\nstream = \"unix:/run/x\"\n[scsi.4]\nkind = \"daynaport\"").unwrap(); + let mut cfg = MachineConfig::from_toml_str("[[devices]]\ntype = \"net\"\nat = \"ethernet\"\nbackend = \"stream:tcp:127.0.0.1:7000\"\n[scsi.4]\nkind = \"daynaport\"").unwrap(); assert!(cfg.validate().unwrap_err().contains("cannot join a stream segment")); - cfg.devices.clear(); - assert_eq!(cfg.network().stream.as_deref(), Some("unix:/run/x")); + cfg.devices.retain(|d| d.device.scsi().is_none()); + assert_eq!(cfg.network().stream.as_deref(), Some("tcp:127.0.0.1:7000")); } /// `banks` reads one to eight entries and pads; it writes four or more @@ -4853,13 +4914,13 @@ mod export_tests { o2.banks = banks_from4([64, 128, 0, 0]); assert!(o2.validate().unwrap_err().contains("largest kit goes in pair A")); o2.banks = default_banks(); - o2.network.mode = NetMode::Pcap; + o2.set_net(NetMode::Pcap, None); o2.validate().expect("a bridged O2"); - o2.network.mode = NetMode::Off; + o2.set_net(NetMode::Off, None); o2.validate().expect("an unplugged O2"); let mut indy = MachineConfig::default(); - indy.network.mode = NetMode::Off; - assert!(indy.validate().unwrap_err().contains("only available on the O2")); + indy.set_net(NetMode::Off, None); + assert!(indy.validate().unwrap_err().contains("always have their Ethernet")); } /// `try_load` returns a parse error, with the Windows backslash hint where @@ -5138,10 +5199,10 @@ mod export_tests { #[test] fn network_off_names_the_machines_that_take_it_and_a_second_controller_the_machine() { let mut cfg = ip27_config("indy_ip24", ""); - cfg.network.mode = NetMode::Off; + cfg.set_net(NetMode::Off, None); let e = cfg.validate().unwrap_err(); - assert!(e.contains("the Origin 200, the Origin 2000 and the Onyx2"), "{e}"); - ip27_config("onyx2_ip27", "[network]\nmode = \"off\"\n").validate().unwrap(); + assert!(e.contains("always have their Ethernet"), "{e}"); + ip27_config("onyx2_ip27", "[[devices]]\ntype = \"none\"\nat = \"ethernet\"\n").validate().unwrap(); let e = ip27_config("indy_ip24", "[scsi.17]\npath = \"d.raw\"\n").validate().unwrap_err(); assert!(e.contains("has no slot scsi1/t1"), "{e}"); } @@ -5230,6 +5291,37 @@ mod export_tests { assert!(!help.contains("SGI Indy")); } + /// The Ethernet's host end and MAC are a `net` entry at `ethernet` on every machine. It is read from a file, set by + /// `--device`, written back only when it says something. + #[test] + fn the_ethernet_is_a_net_entry_at_its_port() { + let slot = |p: MachineProfile| DevicePlacement::lenient(&MachineConfig { machine: MachineSection { profile: p, ..Default::default() }, ..Default::default() }, &[]).port("ethernet").map(|d| d.1.default); + for p in MachineProfile::EVERY { + assert_eq!(slot(p), Some(true), "{p:?} has a default entry at its ethernet"); + } + let mut cfg = MachineConfig::from_toml_str("[[devices]]\ntype = \"net\"\nat = \"hpc3/ethernet\"\nbackend = \"pcap:eth0\"\nmac = \"08:00:69:aa:bb:cc\"\n").unwrap(); + let net = cfg.network(); + assert_eq!((net.mode, net.pcap_interface.as_deref(), net.mac), (NetMode::Pcap, Some("eth0"), [0x08, 0x00, 0x69, 0xaa, 0xbb, 0xcc])); + cfg.set_net(NetMode::Nat, None); + assert_eq!(cfg.net_end().mac.as_deref(), Some("08:00:69:aa:bb:cc"), "the MAC stays with the port"); + cfg.set_net_end(NetDevice::default()); + assert!(!toml::to_string_pretty(&cfg.for_writing()).unwrap().contains("\"net\""), "an entry that says nothing is not written"); + let cli = Cli::parse_from(["iris", "--machine", "o2_ip32", "--device", "none@ethernet"]); + assert_eq!(cli.apply(MachineConfig::default()).network().mode, NetMode::Off); + let e = MachineConfig::from_toml_str("[[devices]]\ntype = \"net\"\nbackend = \"none\"\n").unwrap_err().to_string(); + assert!(e.contains("type = \"none\""), "{e}"); + let mut unplugged = MachineConfig::default(); + unplugged.set_net_end(NetDevice { backend: "pcap".into(), mac: Some("08:00:69:aa:bb:cc".into()) }); + unplugged.set_net(NetMode::Off, None); + assert_eq!(unplugged.net_end(), NetDevice::of(NetMode::Off, None, None), "an unplugged port has no entry's MAC"); + assert_eq!(unplugged.network().mac, unplugged.default_station_mac()); + let none = MachineConfig::from_toml_str("[machine]\nprofile = \"octane_ip30\"\n[[devices]]\ntype = \"none\"\nat = \"ethernet\"\n").unwrap(); + assert_eq!(none.network().mode, NetMode::Off); + let e = MachineConfig::from_toml_str("[[devices]]\ntype = \"net\"\nat = \"scsi0/t4\"\n").unwrap().resolved().unwrap_err(); + assert!(e.contains("does not take a net"), "{e}"); + assert!(MachineConfig::from_toml_str("[[devices]]\ntype = \"net\"\nbackend = \"tap:x\"\n").is_err()); + } + /// Every old `[o2]` key lands on the shared key it stood for, and the /// section keeps only what is the O2's alone. #[test] @@ -5256,7 +5348,7 @@ mod export_tests { assert_eq!(cfg.serial_log.as_deref(), Some("o2.log")); assert!(cfg.headless); assert_eq!(cfg.clock.fixed_mhz, Some(97.5)); - assert_eq!(cfg.network.mode, NetMode::Off); + assert_eq!(cfg.network().mode, NetMode::Off); assert_eq!(cfg.port_forward.len(), 1); assert_eq!(cfg.port_forward[0].host_port, 2292); assert!(!cfg.o2.mouse); @@ -5569,7 +5661,7 @@ mod fuel_input_tests { /// The Tezro's id is the fold of the system serial its L1 answers with, /// LEMU, the kind, the emu_id and 0; the station address follows the - /// emu_id unless `[network] mac` names one, and is never the id. + /// emu_id unless the `net` entry's `mac` names one, and is never the id. #[test] fn the_tezro_takes_its_id_from_the_l1_system_serial() { use crate::identity::hostid_from_text; @@ -5584,7 +5676,7 @@ mod fuel_input_tests { assert_eq!(hostid_from_text(&cfg.tezro_system_serial()), 0xd520_0420); assert_eq!(cfg.network().mac, [0x08, 0x00, 0x69, 0xe2, 0x02, 0xa0]); let mut cfg = identity_cfg("tezro_ip53", "emu_id = 42\n"); - cfg.network.mac = Some("08:00:69:aa:bb:cc".into()); + cfg.devices.push(ConfiguredDevice::new("ethernet", DeviceModel::Net(NetDevice { mac: Some("08:00:69:aa:bb:cc".into()), ..Default::default() }))); assert_eq!(hostid_from_text(&cfg.tezro_system_serial()), 0xd520_0420); assert_eq!(cfg.network().mac, [0x08, 0x00, 0x69, 0xaa, 0xbb, 0xcc]); identity_cfg("tezro_ip53", "emu_id = 4095\n").validate().unwrap(); @@ -5609,7 +5701,7 @@ mod fuel_input_tests { assert_eq!(cfg.network().mac, [0x08, 0x00, 0x69, 0xe2, 0x00, 0x70]); assert_eq!(hostid_from_mac(&cfg.network().mac), 0x69e2_0070); let mut cfg = cfg; - cfg.network.mac = Some("08:00:69:aa:bb:cc".into()); + cfg.devices.push(ConfiguredDevice::new("ethernet", DeviceModel::Net(NetDevice { mac: Some("08:00:69:aa:bb:cc".into()), ..Default::default() }))); assert_eq!(cfg.network().mac, [0x08, 0x00, 0x69, 0xaa, 0xbb, 0xcc]); } @@ -5688,9 +5780,9 @@ mod fuel_input_tests { cfg.banks[1] = 256; cfg.devices.clear(); assert_eq!(cfg.graphics_board(), None); - cfg.network.mode = NetMode::Off; + cfg.set_net(NetMode::Off, None); cfg.validate().unwrap(); - cfg.network.mode = NetMode::Pcap; + cfg.set_net(NetMode::Pcap, None); cfg.validate().unwrap(); cfg.set_graphics(Some(crate::devices::BoardConfig::new(GraphicsBoard::Newport))); assert!(cfg.validate().unwrap_err().contains("no free slot for a graphics board")); @@ -5859,7 +5951,7 @@ mod tezro_config_tests { cfg.validate().unwrap(); } let mut cfg = tezro(); - cfg.network.mode = NetMode::Off; + cfg.set_net(NetMode::Off, None); cfg.validate().unwrap(); } diff --git a/src/config/legacy.rs b/src/config/legacy.rs index 3d2a10741..1372b1e70 100644 --- a/src/config/legacy.rs +++ b/src/config/legacy.rs @@ -113,9 +113,10 @@ pub(super) const OLD_KEYS: &[OldKey] = &[ fold("o2.graphics", When::Load, |c| took(c.o2.graphics.take(), |on| c.headless |= !on)), // CP0 Count runs at half the CPU clock. fold("o2.cpu_mhz", When::Load, |c| took(c.o2.cpu_mhz.take(), |mhz| c.clock.fixed_mhz = c.clock.fixed_mhz.or(Some(f64::from(mhz) / 2.0)))), - fold("o2.net", When::Load, |c| took(c.o2.net.take(), |on| if !on { c.network.mode = NetMode::Off })), fold("o2.forwards", When::Load, |c| took((!c.o2.forwards.is_empty()).then(|| std::mem::take(&mut c.o2.forwards)), |f| c.port_forward.extend(f))), group(&["graphics.board", "impact.gfx", "graphics.heads", "graphics.resolution", "graphics.flash"], When::Chosen, graphics), + group(&["network.mode", "network.pcap_interface", "network.stream", "network.mac"], When::Chosen, network), + fold("o2.net", When::Chosen, o2_net), fold("octane.graphics", When::Load, |c| match c.octane.graphics.take() { Some(old) => Err(format!("octane.graphics has moved: write the board as a [[devices]] entry (was \"{}\")", old.trim())), None => Ok(false), @@ -345,6 +346,58 @@ fn graphics(cfg: &mut MachineConfig) -> Result, String> { Ok(keys) } +/// `o2.net = false` as an empty Ethernet port, unless the file already has an entry there. +fn o2_net(cfg: &mut MachineConfig) -> Result { + let Some(on) = cfg.o2.net.take() else { return Ok(false) }; + if !on { + if cfg.port_device("ethernet").is_some() { + return Err("o2.net = false and the entry at ethernet both set the Ethernet's host end; keep one".into()); + } + cfg.set_net(NetMode::Off, None); + } + Ok(true) +} + +/// The older `[network]` host-end keys as the `net` entry at the Ethernet port. What iris-gui saved as defaults leaves no entry +/// and is dropped if one is there; any other key and an entry both set the host end, so the file is refused. +fn network(cfg: &mut MachineConfig) -> Result, String> { + let n = &mut cfg.network; + let (mode, iface, stream, mac) = (n.legacy_mode.take(), n.legacy_pcap_interface.take(), n.legacy_stream.take(), n.legacy_mac.take()); + let keys: Vec<&'static str> = [(mode.is_some(), "network.mode"), (iface.is_some(), "network.pcap_interface"), (stream.is_some(), "network.stream"), (mac.is_some(), "network.mac")] + .into_iter().filter_map(|(set, key)| set.then_some(key)).collect(); + if keys.is_empty() { + return Ok(keys); + } + let mode = mode.unwrap_or(NetMode::Nat); + let arg = match mode { + NetMode::Pcap => iface, + NetMode::Stream => stream, + _ => None, + }; + let net = NetDevice::of(mode, arg.as_deref(), mac); + if cfg.port_device("ethernet").is_some() { + return if net == NetDevice::default() { Ok(Vec::new()) } else { Err(format!("{} and the entry at ethernet both set the Ethernet's host end; keep one", keys.join(", "))) }; + } + cfg.set_net_end(net); + Ok(keys) +} + +/// `--net-mode` and `--pcap-interface` plug the Ethernet port over whatever the file set there; `--pcap-interface` alone means pcap. +pub(super) fn net_flags(cfg: &mut MachineConfig, mode: Option, iface: Option<&str>) { + let (mode, flags) = match (mode, iface) { + (None, None) => return, + (m, i) => (m.unwrap_or(NetMode::Pcap), [m.map(|_| "--net-mode"), i.map(|_| "--pcap-interface")]), + }; + let kept = cfg.net_end(); + let arg = iface.or_else(|| kept.end().ok().filter(|e| e.0 == mode).and_then(|e| e.1)); + cfg.set_net(mode, arg); + for flag in flags.into_iter().flatten() { + if !cfg.old_keys.contains(&flag) { + cfg.old_keys.push(flag); + } + } +} + /// A bare drive id (`16 * controller + id`), the only way older versions /// named a drive to load or eject. pub(crate) fn drive_number(spec: &str) -> Option { @@ -832,11 +885,39 @@ mod tests { let cfg = MachineConfig::from_toml_str("[o2]\nram_mb = 256\ngraphics = false\nnet = false\ncpu_mhz = 200\n[machine]\nprofile = \"o2_ip32\"\n").unwrap(); assert_eq!(cfg.old_keys, ["o2.ram_mb", "o2.graphics", "o2.cpu_mhz", "o2.net"]); let new = cfg.resolved().unwrap().to_toml(Dump::Minimal).unwrap(); - for want in ["headless = true", "mode = \"off\"", "fixed_mhz = 100.0"] { + for want in ["headless = true", "type = \"none\"\nat = \"ethernet\"", "fixed_mhz = 100.0"] { assert!(new.contains(want), "{want} in\n{new}"); } assert!(!new.contains("[o2]"), "{new}"); let e = MachineConfig::from_toml_str("[octane]\ngraphics = \"maximpact\"").unwrap_err().to_string(); assert!(e.contains("octane.graphics has moved") && e.contains("[[devices]]") && e.contains("maximpact"), "{e}"); } + + #[test] + fn the_older_network_keys_and_flags_make_the_net_entry() { + let text = "[network]\nmode = \"pcap\"\npcap_interface = \"eth0\"\nmac = \"08:00:69:aa:bb:cc\"\n"; + let old = MachineConfig::from_toml_str(text).unwrap(); + assert_eq!(old.net_end(), NetDevice { backend: "pcap:eth0".into(), mac: Some("08:00:69:aa:bb:cc".into()) }); + assert_eq!(old.old_keys, ["network.mode", "network.pcap_interface", "network.mac"]); + assert!(!toml::to_string_pretty(&old.for_writing()).unwrap().contains("pcap_interface"), "saved in the new form"); + assert!(MachineConfig::from_toml_str("[network]\nmode = \"nat\"\n").unwrap().devices.iter().all(|d| d.device.spec().name != "net"), "the default says nothing"); + let cli = Cli::parse_from(["iris", "--pcap-interface", "eth1"]); + assert_eq!(cli.apply(MachineConfig::default()).net_end().backend, "pcap:eth1"); + let cli = Cli::parse_from(["iris", "--net-mode", "off"]); + assert_eq!(cli.apply(MachineConfig::default()).network().mode, NetMode::Off); + } + + /// A flag beats the file's entry, and an older key that is not the default clashes with one rather than being dropped. + #[test] + fn a_net_flag_beats_the_entry_and_an_older_key_clashes_with_it() { + let entry = "[[devices]]\ntype = \"net\"\nat = \"ethernet\"\nbackend = \"nat\"\n"; + let file = || MachineConfig::from_toml_str(entry).unwrap(); + assert_eq!(Cli::parse_from(["iris", "--net-mode", "off"]).apply(file()).net_end().end().unwrap().0, NetMode::Off); + assert_eq!(Cli::parse_from(["iris", "--pcap-interface", "eth1"]).apply(file()).net_end().backend, "pcap:eth1"); + assert!(MachineConfig::from_toml_str(&format!("[network]\nmode = \"nat\"\n{entry}")).unwrap().old_keys.is_empty(), "a default table says nothing"); + for text in [format!("[network]\nmode = \"off\"\n{entry}"), format!("[o2]\nnet = false\n[machine]\nprofile = \"o2_ip32\"\n{entry}")] { + let e = MachineConfig::from_toml_str(&text).unwrap_err().to_string(); + assert!(e.contains("keep one"), "{e}"); + } + } } diff --git a/src/dev/hpc3.rs b/src/dev/hpc3.rs index f4b514c90..360231ba1 100644 --- a/src/dev/hpc3.rs +++ b/src/dev/hpc3.rs @@ -1287,6 +1287,7 @@ impl Hpc3 { /// The board's slots: the HPC3 and its SCSI channels, narrow buses. pub fn slots(s: &mut Vec, guinness: bool) { crate::topology::fixed_slot(s, "hpc3", "hpc3", &[]); + crate::topology::open_slot(s, "hpc3/ethernet", &[crate::topology::DeviceFamily::Net], &["ethernet"]); for c in 0..Self::scsi_channels(guinness) { crate::topology::scsi_bus_slots(s, &Self::scsi_at(c).to_string(), "wd33c93a", 7); } diff --git a/src/devices.rs b/src/devices.rs index 17bc0634e..de02a269f 100644 --- a/src/devices.rs +++ b/src/devices.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::sync::Arc; use crate::dev::serial_dev::{SerialDeviceConfig, SerialKind}; -use crate::config::{GraphicsBoard, MachineConfig, NvmeConfig, ScsiDeviceConfig, ScsiKind, Virtio9pConfig, VirtioSerialConfig}; +use crate::config::{GraphicsBoard, MachineConfig, NetDevice, NvmeConfig, ScsiDeviceConfig, ScsiKind, Virtio9pConfig, VirtioSerialConfig}; use crate::dev::ng1::vc2_timings::NewportResolution; use crate::dev::ice1724::{Ice1724, Variant}; use crate::dev::isp2200::{card::Loop, Isp2200}; @@ -43,6 +43,8 @@ pub enum DeviceModel { Virtio9p(Virtio9pConfig), /// A device on a serial port: `hostserial`, `midi_synth` or `midi_raw`, by its kind. Serial(SerialDeviceConfig), + /// The host end of an Ethernet port. + Net(NetDevice), } /// What the test device's run-configuration register publishes and where its @@ -162,6 +164,7 @@ pub const DEVICE_TYPES: &[DeviceTypeSpec] = &[ parse: |_, o| options(o).map(|v: Virtio9pConfig| DeviceModel::Virtio9p(Virtio9pConfig { enabled: true, ..v })), slots: None, }, + DeviceTypeSpec { name: "net", family: DeviceFamily::Net, keys: &["backend", "mac"], parse: |_, o| options(o).and_then(|n: NetDevice| n.check().map(|_| DeviceModel::Net(n))), slots: None }, DeviceTypeSpec { name: "serial", family: DeviceFamily::Serial, keys: &["backend"], parse: serial_device, slots: None }, DeviceTypeSpec { name: "hostserial", family: DeviceFamily::Serial, keys: &["path"], parse: serial_device, slots: None }, DeviceTypeSpec { name: "midi_synth", family: DeviceFamily::Serial, keys: &["path", "gain"], parse: serial_device, slots: None }, @@ -231,6 +234,7 @@ impl DeviceModel { DeviceModel::VirtioSerial(_) => "virtio_serial", DeviceModel::Virtio9p(_) => "virtio_9p", DeviceModel::Serial(d) => d.kind.name(), + DeviceModel::Net(_) => "net", }; DEVICE_TYPES.iter().find(|t| t.name == name).expect("every variant has a type") } @@ -264,6 +268,7 @@ impl DeviceModel { } DeviceModel::Serial(s) if !s.backend.is_empty() => format!("serial {}", s.backend.join(" ")), DeviceModel::Board(b) if b.model != GraphicsBoard::Newport => format!("{} {}", self.spec().name, b.model), + DeviceModel::Net(n) => format!("net {}", n.backend), _ => self.spec().name.to_string(), } } @@ -284,6 +289,7 @@ impl DeviceModel { DeviceModel::Virtio9p(d) => changed(d, keys), DeviceModel::Serial(d) => changed(d, keys), DeviceModel::Board(b) => changed(b, keys), + DeviceModel::Net(d) => changed(d, keys), DeviceModel::XioBoard(_) | DeviceModel::PciBridge | DeviceModel::Ice1724 | DeviceModel::Qla2200 | DeviceModel::Ultra64 | DeviceModel::Empty => toml::Table::new(), } } @@ -354,14 +360,12 @@ impl ConfiguredDevice { let (k, v) = kv.split_once('=').ok_or_else(|| format!("--device {arg}: `{kv}` is not KEY=VALUE"))?; let value = toml::from_str::(&format!("v = {v}")).ok().and_then(|mut t| t.remove("v")).unwrap_or_else(|| v.into()); // `backend=` repeats, one host end each, or takes a list. - if k == "backend" { - let list = t.entry(k).or_insert_with(|| toml::Value::Array(Vec::new())).as_array_mut().expect("a list"); - match value { - toml::Value::Array(ends) => list.extend(ends), - end => list.push(end), + match (t.remove(k), k == "backend", value) { + (Some(old), true, new) => { + let ends = |v| if let toml::Value::Array(a) = v { a } else { vec![v] }; + t.insert(k.into(), toml::Value::Array([ends(old), ends(new)].concat())); } - } else { - t.insert(k.into(), value); + (_, _, value) => { t.insert(k.into(), value); } } } ConfiguredDevice::from_table(t).map_err(|e| format!("--device {arg}: {e}")) diff --git a/src/ip27.rs b/src/ip27.rs index a07a1fac5..4d3ed5462 100644 --- a/src/ip27.rs +++ b/src/ip27.rs @@ -381,6 +381,7 @@ pub(crate) fn slots(s: &mut Vec, profile: MachineP for d in SCSI_DEVICES { crate::topology::scsi_bus_slots(s, &format!("xio{widget}/pci0/{d}"), "isp1040", 15); } + crate::topology::open_slot(s, &format!("xio{widget}/pci0/2/ethernet"), &[DeviceFamily::Net], &["ethernet"]); } /// The PCI devices both IP27 I/O boards carry behind their Bridge: two ISP1040s and an IOC3. diff --git a/src/ip30_machine.rs b/src/ip30_machine.rs index 0380e3ac5..616b95a09 100644 --- a/src/ip30_machine.rs +++ b/src/ip30_machine.rs @@ -81,6 +81,7 @@ pub(crate) fn slots(s: &mut Vec) { use GraphicsBoard as B; const OCTANE_BOARDS: &[GraphicsBoard] = &[B::SolidImpact, B::HighImpact, B::MaxImpact, B::V6, B::V8, B::V10, B::V12]; crate::topology::pci_bus_slots(s, &format!("xio{}/pci0", crate::ip30::WIDGET_BRIDGE), "Octane system board", SYSTEM_SLOTS); + crate::topology::open_slot(s, &format!("xio{}/pci0/2/ethernet", crate::ip30::WIDGET_BRIDGE), &[DeviceFamily::Net], &["ethernet"]); for (w, aliases) in XIO_SLOTS { crate::topology::open_slot(s, &format!("xio{w}"), &[DeviceFamily::Xio, DeviceFamily::Gfx], aliases); } @@ -1547,7 +1548,7 @@ mod snapshot_tests { cfg.headless = true; // Not CI mode: its overlays share one path per process, and the // tests run in parallel; this way each sits beside its own disk. - cfg.network.mode = crate::config::NetMode::Off; + cfg.set_net(crate::config::NetMode::Off, None); let held = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); cfg.monitor_port = Some(held.local_addr().unwrap().port()); let disk = dir.join("disk.raw"); @@ -2206,6 +2207,13 @@ mod snapshot_tests { assert!(e.contains("no free slot"), "{e}"); } + /// `none` at a slot that takes a board keeps the default out and leaves the slot free for one. + #[test] + fn a_none_at_a_second_board_slot_leaves_it_free() { + let none = "[[devices]]\ntype = \"none\"\nat = \"slot_c\"\n[[devices]]\ntype = \"vpro\"\nmodel = \"v12\"\nat = \"slot_c\"\n"; + octane_with_boards(none).unwrap(); + } + /// An IMPACT is a second board in any slot but the one a board holds, beside any first board. #[test] fn a_second_impact_goes_in_any_other_slot() { diff --git a/src/ip32_machine.rs b/src/ip32_machine.rs index 55198ca4a..dc1166cc8 100644 --- a/src/ip32_machine.rs +++ b/src/ip32_machine.rs @@ -155,6 +155,8 @@ pub const CPUS: &[&Part] = &[&parts::R5000_180, &parts::R10000_250, &parts::R120 pub(crate) fn slots(s: &mut Vec) { crate::topology::pci_bus_slots(s, "pci0", "O2 system board", crate::ip32::PCI0_SLOTS); crate::topology::fixed_slot(s, "gbe", "CRIME/GBE", &["graphics"]); + crate::topology::fixed_slot(s, "mace", "mace", &[]); + crate::topology::open_slot(s, "mace/ethernet", &[crate::topology::DeviceFamily::Net], &["ethernet"]); } @@ -180,13 +182,10 @@ impl O2Machine { let kits = cfg.o2_kits(); let mem = O2Memory::from_kits(&kits)?; // The PROM's flash, and so its environment, lives in `nvram`. - // `[network] mac` is the address in the 1-Wire ID chip. `headless`: + // The net entry's `mac` is the address in the 1-Wire ID chip. `headless`: // no keyboard, so the PROM and the OS take the serial console, as on // an O2 booted without one. The GBE stays: it is part of every O2. - let mac = match cfg.network.mac.as_deref() { - Some(mac) => Some(crate::config::parse_mac(mac).map_err(|e| format!("network.mac: {e}"))?), - None => None, - }; + let mac = cfg.net_end().mac.as_deref().map(crate::config::parse_mac).transpose()?; // The SCSI devices: scsi0 is the internal bus, scsi1 the external // one. The buses are filled before the controllers exist. let scsi = [crate::dev::aic7880::Aic7880::new_bus(), crate::dev::aic7880::Aic7880::new_bus()]; diff --git a/src/ip34_machine.rs b/src/ip34_machine.rs index fb6850087..0a1c34e7b 100644 --- a/src/ip34_machine.rs +++ b/src/ip34_machine.rs @@ -119,6 +119,7 @@ pub(crate) fn slots(s: &mut Vec) { for c in [0, 1] { crate::topology::scsi_bus_slots(s, &format!("xio{HEAD_F}/pci0/{SCSI_DEVICE}/c{c}"), "isp12160 channel", 15); } + crate::topology::open_slot(s, &format!("xio{HEAD_F}/pci0/4/ethernet"), &[crate::topology::DeviceFamily::Net], &["ethernet"]); } /// The Fuel's base I/O on its XBridge's head F: the ISP12160, the IOC3 and the OHCI controller. A diff --git a/src/ip35/tests.rs b/src/ip35/tests.rs index 27e4227a1..7f13a5dc0 100644 --- a/src/ip35/tests.rs +++ b/src/ip35/tests.rs @@ -170,7 +170,7 @@ fn processor_stores_advance_the_counter_of_the_bank_they_reach() { fn the_configured_station_address_reaches_the_l1() { let dir = TempPath::dir("fuel-mac"); let mut cfg = fuel_config(&dir); - cfg.network.mac = Some("08:00:69:21:43:65".into()); + cfg.devices.push(crate::devices::ConfiguredDevice::new("ethernet", crate::devices::DeviceModel::Net(crate::config::NetDevice { mac: Some("08:00:69:21:43:65".into()), ..Default::default() }))); with_machine(cfg, |m| assert_eq!(m.l1s[0].station_mac(), [0x08, 0x00, 0x69, 0x21, 0x43, 0x65])); } /// The L1's reported revision and brick serial keep their defaults unless the config replaces them. diff --git a/src/ip35_machine.rs b/src/ip35_machine.rs index 5a4e613f7..f2f180350 100644 --- a/src/ip35_machine.rs +++ b/src/ip35_machine.rs @@ -204,6 +204,7 @@ pub(crate) fn slots(s: &mut Vec, onyx: bool) { crate::topology::pci_bus_slots(s, &format!("xio{HEAD_E}/pci0"), "I-brick XBridge head E", HEAD_E_SLOTS); crate::topology::pci_bus_slots(s, &format!("xio{HEAD_F}/pci0"), "I-brick XBridge head F", HEAD_F_SLOTS); crate::topology::loop_slots(s, &fibre_at()); + crate::topology::open_slot(s, &format!("xio{HEAD_F}/pci0/4/ethernet"), &[crate::topology::DeviceFamily::Net], &["ethernet"]); if onyx { graphics_slots(s); } diff --git a/src/ip53_machine.rs b/src/ip53_machine.rs index bb3a61b18..8b6cfc00f 100644 --- a/src/ip53_machine.rs +++ b/src/ip53_machine.rs @@ -104,6 +104,7 @@ pub(crate) fn slots(s: &mut Vec) { crate::topology::scsi_bus_slots(s, &format!("xio{IO9_WIDGET}/pci0/{SCSI_DEVICE}/c{c}"), "isp12160 channel", 15); } crate::topology::pci_bus_slots(s, &format!("xio{IO9_WIDGET}/pci1"), "Tezro IO9 PIC, bus 1", IO9_BUS1_SLOTS); + crate::topology::open_slot(s, &format!("xio{IO9_WIDGET}/pci0/{ETH_DEVICE}/ethernet"), &[crate::topology::DeviceFamily::Net], &["ethernet"]); let behind_ti = format!("xio{IO9_WIDGET}/pci0/{TI_BRIDGE_DEVICE}/pci0"); crate::topology::pci_bus_slots(s, &behind_ti, "TI PCI2050 secondary bus", &[(AUDIO_DEVICE, MachineSlotKind::PCI_SLOT, None)]); } diff --git a/src/main.rs b/src/main.rs index 6b849c80d..efc0d481c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,11 +27,9 @@ fn main() { // the backend then auto-picks. #[cfg(feature = "pcap")] { - if cfg.network.mode == iris::config::NetMode::Pcap - && cfg.network.pcap_interface.as_deref().map(str::trim).unwrap_or("").is_empty() - { + if cfg.network().mode == iris::config::NetMode::Pcap && cfg.network().pcap_interface.as_deref().is_none_or(|i| i.trim().is_empty()) { if let Some(name) = iris::net::net_pcap::prompt_for_interface() { - cfg.network.pcap_interface = Some(name); + cfg.set_net(iris::config::NetMode::Pcap, Some(&name)); } } } diff --git a/src/net/link.rs b/src/net/link.rs index 36f1869dd..d133c8bc5 100644 --- a/src/net/link.rs +++ b/src/net/link.rs @@ -121,7 +121,7 @@ pub struct Link { } impl Link { - /// `None` for `mode = "off"`: an adapter left unplugged. + /// `None` for an unplugged port. pub fn open(net: &NetworkConfig) -> Result, String> { Self::with_gateway(GatewayConfig::from_network(net)) } diff --git a/src/net/mod.rs b/src/net/mod.rs index af9b64cb0..826a43174 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -187,7 +187,7 @@ pub trait NetBackend: Send { /// opened. Deliberately **not** feature-gated — `NatControl` always carries the /// field and non-`pcap` builds / the GUI reference the type unconditionally; it /// only ever leaves `Inactive` when the `pcap` feature is built and the active -/// machine uses `[network] mode = "pcap"`. +/// machine's `net` entry has a `pcap` backend. #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] #[repr(u8)] pub enum PcapStatus { diff --git a/src/net/net_pcap.rs b/src/net/net_pcap.rs index 5e00b878c..ec0f72f5c 100644 --- a/src/net/net_pcap.rs +++ b/src/net/net_pcap.rs @@ -85,8 +85,8 @@ pub fn format_interfaces() -> String { } let mut out = String::new(); out.push_str("Available network interfaces for PCAP bridging:\n"); - out.push_str("(configure with `[network] pcap_interface = \"\"` in iris.toml;\n"); - out.push_str(" e.g. pcap_interface = \"1\" selects the first interface below)\n\n"); + out.push_str("(configure with `backend = \"pcap:\"` on the `net` [[devices]] entry;\n"); + out.push_str(" e.g. pcap:1 selects the first interface below)\n\n"); for (idx, i) in ifaces.iter().enumerate() { let mut tags = Vec::new(); if i.up { tags.push("up"); } @@ -114,7 +114,7 @@ pub fn format_interfaces() -> String { } } -/// Resolve `[network] pcap_interface` to a concrete device name. +/// Resolve the `pcap:` backend's interface to a concrete device name. /// /// The configured value may be: /// - a 1-based index into the `--list-net-interfaces` listing (e.g. "1"), @@ -145,7 +145,7 @@ fn select_interface(configured: &Option) -> Result { } /// Interactively prompt on stdin for a host interface to bridge onto, for use -/// when `[network] mode = "pcap"` is set but no `pcap_interface` is configured. +/// when the `net` entry's backend is `pcap` with no interface named. /// /// Returns the chosen device name, or `None` to defer to auto-pick (blank input, /// EOF, no interactive console, or enumeration failure). Must be called once at @@ -203,7 +203,7 @@ fn auto_pick(ifaces: &[NetInterface]) -> Result { .find(|i| i.up && i.running && !i.loopback && !i.addresses.is_empty()) .or_else(|| ifaces.iter().find(|i| i.up && !i.loopback)) .map(|i| i.name.clone()) - .ok_or_else(|| "no suitable non-loopback interface found; set [network] pcap_interface".to_string()) + .ok_or_else(|| "no suitable non-loopback interface found; name one as backend = \"pcap:IFACE\"".to_string()) } /// True when stdin is connected to an interactive terminal. @@ -238,7 +238,7 @@ fn prompt_interface(ifaces: &[NetInterface]) -> Option { return None; } eprintln!(); - eprintln!("PCAP networking: no [network] pcap_interface configured."); + eprintln!("PCAP networking: the net backend names no interface."); eprintln!("Select the host interface to bridge the guest onto:"); eprintln!(); for (idx, i) in ifaces.iter().enumerate() { @@ -353,7 +353,7 @@ impl NetBackend for PcapEngine { // vs. just report a bad/absent device. See `classify_open_error`. self.ctl.set_pcap_status(classify_open_error(&e)); eprintln!("iris: PCAP backend disabled: {}", e); - eprintln!("iris: the guest will have NO networking. Use `[network] mode = \"nat\"` for the software gateway."); + eprintln!("iris: the guest will have NO networking. Use backend = \"nat\" on the `net` entry for the software gateway."); // Drain TX so the guest's ring doesn't back up, but produce no RX. while self.running.load(Ordering::Relaxed) { { diff --git a/src/net/stream.rs b/src/net/stream.rs index 7e6df31dc..219549050 100644 --- a/src/net/stream.rs +++ b/src/net/stream.rs @@ -271,16 +271,16 @@ fn fill(r: &mut impl Read, buf: &mut [u8], keep_going: &dyn Fn() -> bool) -> io: } impl super::GatewayConfig { - /// The `[network] stream` peer, for a machine whose mode is + /// The `stream:` peer of the Ethernet's `net` entry, for a machine whose mode is /// [`NetMode::Stream`](crate::config::NetMode::Stream). `validate` has /// already parsed it; a missing or bad value here is a bug in the caller. pub fn stream_endpoint(&self) -> Result { - let s = self.stream.as_deref().ok_or("network.mode = \"stream\" needs [network] stream")?; + let s = self.stream.as_deref().ok_or("a stream backend needs a peer: stream:tcp:IP:PORT or stream:unix:PATH")?; StreamEndpoint::parse(s) } } -/// The backend for `[network] mode = "stream"`: connects to `endpoint` and +/// The backend for a `stream:` net backend: connects to `endpoint` and /// moves frames between it and the NIC's rings. Frames the guest sends /// arrive on `tx_cons` (with `tx_wake` notified), and frames from the peer go /// on `rx_prod` with `rx_wake` notified. diff --git a/src/slot_path.rs b/src/slot_path.rs index fe32f190f..6421668dd 100644 --- a/src/slot_path.rs +++ b/src/slot_path.rs @@ -21,6 +21,8 @@ const TAGS: &[(&str, bool)] = &[ ("loop", true), // Fibre Channel loop ID N ("usb", true), // USB port N ("serial", true), // serial port N, as numbered on the case + ("mace", false), + ("ethernet", false), // the Ethernet port of the part above it ]; const BARE: u8 = 3; diff --git a/src/sn/tests.rs b/src/sn/tests.rs index 2482932df..e579bc313 100644 --- a/src/sn/tests.rs +++ b/src/sn/tests.rs @@ -23,7 +23,7 @@ pub(crate) fn headless(dir: &std::path::Path, profile: crate::config::MachinePro cfg.prom = prom_path.to_string_lossy().into_owned(); cfg.nvram = dir.join("nvram.bin").to_string_lossy().into_owned(); cfg.headless = true; - cfg.network.mode = crate::config::NetMode::Off; + cfg.set_net(crate::config::NetMode::Off, None); cfg.monitor_port = Some(0); crate::dev::serial_host::tests::free_ports(&mut cfg); cfg diff --git a/src/topology.rs b/src/topology.rs index 0af5b748a..9ec486815 100644 --- a/src/topology.rs +++ b/src/topology.rs @@ -26,6 +26,8 @@ pub enum DeviceFamily { Virtio, /// A device on a serial port: a host serial port, a MIDI synth or a host MIDI port. Serial, + /// The host end of an Ethernet port. + Net, Empty, } @@ -40,6 +42,7 @@ impl DeviceFamily { DeviceFamily::Gfx => "a graphics board", DeviceFamily::Virtio => "virtio devices", DeviceFamily::Serial => "serial devices", + DeviceFamily::Net => "network backends", DeviceFamily::Empty => "nothing", } } @@ -422,6 +425,10 @@ impl DevicePlacement { let line = crate::dev::serial_dev::SerialDeviceConfig { kind: crate::dev::serial_dev::SerialKind::Line, backend: vec![format!("tcp:{tcp}")], ..Default::default() }; devices.push(ConfiguredDevice { default: true, ..ConfiguredDevice::new(&format!("serial{n}"), DeviceModel::Serial(line)) }); } + // So does an Ethernet port its host end. + for s in slots.iter().filter(|s| matches!(s.kind, MachineSlotKind::Open([DeviceFamily::Net]))) { + devices.push(ConfiguredDevice { default: true, ..ConfiguredDevice::new(&s.path.to_string(), DeviceModel::Net(Default::default())) }); + } let (slots, at) = layout(machine, slots, &devices); DevicePlacement { slots, machine, devices, at, pci: HashMap::new() } } @@ -444,6 +451,12 @@ impl DevicePlacement { Some(alias(at).or_else(|| Some(format!("{}/{step}", alias(&at.parent()?)?))).unwrap_or_else(|| at.to_string())) } + /// The device at port `at`, a machine alias or a path, and its index: an entry, else the port's default. + pub fn port(&self, at: &str) -> Option<(usize, &ConfiguredDevice)> { + let at = slot_alias(&self.slots, at).cloned().or_else(|| at.parse().ok())?; + (0..self.devices.len()).find(|&i| self.at(i) == Some(&at)).map(|i| (i, &self.devices[i])) + } + /// The devices that have a slot, with it, in config order. pub fn placed(&self) -> impl Iterator { self.devices.iter().zip(&self.at).filter_map(|(d, at)| Some((d, at.as_ref().ok()?))) @@ -621,6 +634,9 @@ fn layout(machine: &str, mut slots: Vec, devices: &[ConfiguredDevic }) } _ => match taken.get(&loc) { + // A board named at a `none` takes the slot, whichever came first. + Some(&j) if matches!(d.device, DeviceModel::Board(_)) && matches!(devices[j].device, DeviceModel::Empty) => Ok(loc), + Some(&j) if matches!(d.device, DeviceModel::Empty) && matches!(devices[j].device, DeviceModel::Board(_)) => Ok(loc), Some(&j) if matches!(d.device, DeviceModel::Board(_)) => { Err(format!("{loc} is the graphics board's port, taken by the {} there{}", devices[j].device.spec().name, why(&slots, d))) } @@ -645,8 +661,8 @@ fn layout(machine: &str, mut slots: Vec, devices: &[ConfiguredDevic if let Some(bring) = ty.slots { bring(&d.device, &loc, &mut slots); } - // `none` only keeps the slot's default board out; the slot stays free. - if !matches!(d.device, DeviceModel::Empty) { + // `none` at the graphics slot only keeps the default board out and leaves the slot free; elsewhere it holds the slot. + if !(matches!(d.device, DeviceModel::Empty) && (taken.contains_key(&loc) || names_main_slot(&slots, &loc.to_string(), None))) { taken.insert(loc.clone(), i); } out[i] = Some(Ok(loc)); @@ -772,8 +788,9 @@ mod tests { for p in MachineProfile::EVERY { let map = fill(p); let mut seen = std::collections::HashSet::new(); - for a in map.slots().iter().flat_map(|r| r.aliases.clone()) { - assert!(!MachineSlotPath::is_step(&a), "{p:?}: alias {a} looks like a hop"); + // A port may take the name of its own last step (`hpc3/ethernet` is `ethernet`). + for (s, a) in map.slots().iter().flat_map(|s| s.aliases.iter().map(move |a| (s, a))) { + assert!(!MachineSlotPath::is_step(a) || s.path.to_string().ends_with(&format!("/{a}")), "{p:?}: alias {a} looks like a hop"); assert!(seen.insert(a.clone()), "{p:?}: alias {a} twice"); } } @@ -1055,6 +1072,18 @@ mod tests { assert!(!refused("onyx2_ip27", wrong).contains("007-3454-005")); } + #[test] + fn a_none_at_gio0_leaves_the_slot_free() { + let at = place(&[card("none", Some("gio0")), card("ultra64", None)], &fill(MachineProfile::IndyIp24)).unwrap(); + assert_eq!(at[1].as_ref().map(|p| p.to_string()).as_deref(), Some("gio0")); + } + + #[test] + fn a_none_at_an_octane_xio_slot_holds_it() { + let at = place(&[card("none", Some("xio10")), card("pci_shoehorn", None)], &fill(MachineProfile::OctaneIp30)).unwrap(); + assert_eq!(at[1].as_ref().map(|p| p.to_string()).as_deref(), Some("xio12")); + } + #[test] fn gio_cards_clash_like_any_other_slot() { let map = fill(MachineProfile::IndyIp24); diff --git a/src/tree.rs b/src/tree.rs index 3173a5db6..1456c455d 100644 --- a/src/tree.rs +++ b/src/tree.rs @@ -148,6 +148,7 @@ mod tests { assert_eq!(rows, [ "SGI Indy (IP24)", "|-- hpc3 hpc3 built-in", + "| |-- ethernet (ethernet) net nat default", "| `-- c0 (scsi0) wd33c93a built-in", "| |-- t1 - takes: scsi devices", "| |-- t2 hdd irix.img config", diff --git a/tezro.toml.example b/tezro.toml.example index 41101cd67..327b9c230 100644 --- a/tezro.toml.example +++ b/tezro.toml.example @@ -32,9 +32,10 @@ l1_port = 18882 # type = "vpro" # model = "v12" -[network] -# Disconnected cable. For NAT, use mode = "nat". -mode = "off" +# Disconnected cable. For NAT, delete this entry. +[[devices]] +type = "none" +at = "ethernet" # Where each serial port is served: TCP on 127.0.0.1, in place of 8880 and up. [[devices]] diff --git a/tools/prom-boot-loop.py b/tools/prom-boot-loop.py index bcbb0f271..054a6b16c 100755 --- a/tools/prom-boot-loop.py +++ b/tools/prom-boot-loop.py @@ -24,13 +24,11 @@ headless = true no_audio = true monitor_port = 23010 - devices = [ { type = "serial", at = "serial1", backend = "tcp:23011" }, { type = "serial", at = "serial2", backend = "tcp:23012" } ] + devices = [ { type = "serial", at = "serial1", backend = "tcp:23011" }, { type = "serial", at = "serial2", backend = "tcp:23012" }, { type = "none", at = "ethernet" } ] serial_log = "serial.log" serial_log_overwrite = true [machine] profile = "o2_ip32" - [network] - mode = "off" [scsi] EOF tools/prom-boot-loop.py --iris target/release/iris --config o2.toml --count 100 diff --git a/tools/tests/netbsd-indy-keyboard.py b/tools/tests/netbsd-indy-keyboard.py index a30fdd798..1f8d48b57 100755 --- a/tools/tests/netbsd-indy-keyboard.py +++ b/tools/tests/netbsd-indy-keyboard.py @@ -105,7 +105,6 @@ def start(self): f'prom = "(embedded)"\nnvram = "nvram.bin"\nbanks = [128, 128, 0, 0]\n' f'headless = false\nno_audio = true\nmonitor_port = {b}\nci_socket = "{self.sock}"\n\n' f'[machine]\nprofile = "indy_ip24"\ncpu = "r4400_150"\n\n' - f'[network]\nmode = "nat"\n\n' f'[scsi.4]\npath = "{Path(self.args.iso).resolve()}"\ncdrom = true\n' f'kind = "cdrom"\noverlay = true\n') self.log = open(self.work / "iris.log", "w") From da525d2539d4dc2a02971804b9c69c923cb2610a Mon Sep 17 00:00:00 2001 From: James Braid Date: Sat, 28 Nov 2026 11:38:53 -0700 Subject: [PATCH 3/4] vino: attach the camera as a device at the Indy's video input VINO's video source came from a `[vino]` table, away from the other host ends. The camera is a device at a port like the rest: VINO is a slot `vino` on the Indy (the Indigo2 has the EISA bus there) with one input, `vino/video`, alias `video`, and a `camera` entry at it plugs a picture in. `backend` is webcam:N, test_pattern or black, and `standard` is ntsc or pal. The O2 models no video input, so it has no such slot. There is no model key: VINO takes the IndyCam and nothing else. With no entry VINO stays mapped with no source and no DMA thread, exactly what `source = "off"` did, so that value goes and the table's default needs no entry. iris-gui wrote a `[vino]` table into every machine it saved, so refusing it would have made every saved machine fail to load. The table is read with a warning and turned into the entry in memory, and the GUI saves the entry. A table at its defaults (`source = "off"`) says nothing and leaves no entry. Any other table beside an entry at the port is an error, as a serial port's tcp clash is; where the machine has no video input it is dropped with a warning. The GUI edits the entry through the machine's `vino()` view, which expects a valid backend: the file path checks it at parse and the GUI builds it from an enum. Production lines: +146 -54 ; Conflicts: ; src/config/legacy.rs ; src/machine.rs ; src/topology.rs --- CHANGELOG.md | 5 + FEATURES.md | 9 +- HELP.md | 9 +- clanker/irix/irix-install.md | 15 ++- .../rex3-processor-must-park-when-idle.md | 2 +- clanker/video/indycam-cdmc-register-map.md | 2 +- clanker/video/indycam-end-to-end-capture.md | 2 +- clanker/video/vino-verification-checklist.md | 2 +- installer/iris-gui.entitlements | 2 +- iris-gui/core/src/controller/camera.rs | 5 +- iris-gui/core/src/controller/settings.rs | 34 ++++-- iris-gui/core/src/model/machines.rs | 2 +- iris-gui/src/config_ui.rs | 25 ++-- iris-gui/src/main.rs | 2 +- iris-irix53.toml | 6 +- iris-irix65.toml | 6 +- iris.toml | 14 ++- src/config.rs | 111 ++++++++++++++---- src/config/legacy.rs | 31 +++++ src/devices.rs | 8 +- src/machine.rs | 9 +- src/slot_path.rs | 2 + src/topology.rs | 6 + src/tree.rs | 2 + 24 files changed, 223 insertions(+), 88 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4e1a331a..25b1e4ea5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -177,6 +177,11 @@ hashes are given where a change is easiest to understand by reading the commit. ### IndyCam +- The camera is a `camera` device at the Indy's `video` input: `backend` is + `webcam:N`, `test_pattern` or `black`, and `standard` is `ntsc` or `pal`. No + entry, no camera, as before. The `[vino]` table is read with a warning and + saved as the entry; beside an entry at the port it is an error. + - The host camera works with cameras that offer only MJPEG, NV12, RGB or gray at a usable size, such as high-resolution laptop webcams on Windows (techomancer/iris#70), and on Linux with cameras that have no YUYV mode. diff --git a/FEATURES.md b/FEATURES.md index da6652835..7edb4315e 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -417,6 +417,7 @@ takes; `--device [NAME:]TYPE[@SLOT][,KEY=VALUE]...` adds or replaces one from th | `daynaport` | a SCSI target | `mac` (`00:80:19:44:50:` when unset), `subnet` (`192.168.10.0/24` when unset, separate from ec0's). Refused on the machines with built-in Ethernet only (the O2, the Origin 200, Origin 2000 and Onyx2, the Fuel and the Tezro) and when the onboard Ethernet's backend is a `stream:` segment. | | `nvme` | a PCI slot | `path` (raw or CHD, at most 2 TiB), `overlay`, `write_cache` (as for `hdd`). An NVM Express controller with one namespace; any number per machine; see [docs/nvme.md](docs/nvme.md). | | `qla2200` | a PCI slot | A QLogic ISP2200 Fibre Channel adapter; its disks are `hdd` entries at `CARD/loopN`, N the loop ID 0 to 125. The Origin 3200 and Onyx 3000 have one fitted at `xio15/pci0/1`. See [docs/fibre-channel.md](docs/fibre-channel.md). | +| `camera` | the Indy's video input (`video`; `--list-slots` shows it) | `backend`: `webcam:N` (host camera N, `webcam:0` when unset), `test_pattern` or `black`; `standard`: `ntsc` (60 fields/s) or `pal` (50). With no entry VINO stays mapped but has no source and starts no DMA thread. | | `net` | an Ethernet port (`ethernet`: the machine's own; a card that has one brings `CARD/ethernet`) | `backend`: `nat` (the default: the built-in gateway), `pcap` or `pcap:IFACE` (a host interface; needs `--features pcap`), `stream:tcp:IP:PORT` or `stream:unix:PATH` (a private segment; not shared with a DaynaPort); `mac` (`08:00:69:12:34:56` when unset; injected only into blank PROM battery-backed MAC slots). A port with no entry is NAT, and `none` there unplugs it (the MAC goes with the entry). See [NETWORKING.md](NETWORKING.md). | | `serial` | a serial port (`serial1`, `serial2`, ...; `--list-slots` lists them) | `backend`: one string or a list of `tcp:PORT` (telnet on 127.0.0.1, 0 = any free port), `unix:PATH` (raw bytes) and `log:PATH` (a transcript). The device replaces the port's default (TCP 8880 and up; under `--ci` any free port on every port but the console); with no `backend` the port is unplugged. `hostserial`, `midi_synth` and `midi_raw` put a device on the port instead. See [HELP.md](HELP.md#serial-ports). | | `ice1724` | a PCI slot | The IC Ensemble ICE1724 audio card; plays as `[audio]` sets. | @@ -502,14 +503,6 @@ Omit `[nfs]` to disable the share; the default forward list is empty. | `port_forward[].guest_port` | `required` | Guest destination port. | | `port_forward[].bind` | `localhost` | localhost or any; any listens on all interfaces. | -### [vino] - -| Key | Default | Values and behavior | -|---|---|---| -| `vino.source` | `off` | off, test_pattern, camera, black. | -| `vino.standard` | `ntsc` | ntsc (60 fields/s) or pal (50 fields/s). | -| `vino.camera_index` | `0` | Host camera index; meaningful only for source=camera. | - ### [vnc] | Key | Default | Values and behavior | diff --git a/HELP.md b/HELP.md index 22de25a12..1aa8130e0 100644 --- a/HELP.md +++ b/HELP.md @@ -918,10 +918,11 @@ path = "cdrom4.iso" # ── Devices ────────────────────────────────────────────────────────────────── -[vino] # IndyCam video-in -source = "off" # "off" (default) | "test_pattern" | "black" | "camera" -standard = "ntsc" # or "pal" -camera_index = 0 # host camera, source = "camera" only +# [[devices]] # the Indy's IndyCam; no entry, no camera +# type = "camera" +# at = "video" +# backend = "webcam:0" # host camera N, or "test_pattern" or "black" +# standard = "ntsc" # or "pal" [audio] # host = "default" # or "pulse", "wasapi", "coreaudio", "null" (discard) diff --git a/clanker/irix/irix-install.md b/clanker/irix/irix-install.md index e067cd1ad..b0596dc69 100644 --- a/clanker/irix/irix-install.md +++ b/clanker/irix/irix-install.md @@ -97,8 +97,7 @@ Launch with `--config --ci --ci-display`. > iris-ci stays reachable while iris draws the Newport window > miniroot needs to see. -The disk goes at SCSI 1, CD (or CD changer) at SCSI 4. `[vino] -source = "camera"` is fine for the install. +The disk goes at SCSI 1, CD (or CD changer) at SCSI 4. A `camera` device is fine for the install. **6.5.22:** CD changer on SCSI 4 with Overlay 1 active and the rest in cycle order: @@ -128,8 +127,10 @@ discs = [ "irix/IRIX 6.5 Foundation 2.iso", ] -[vino] -source = "camera" +[[devices]] +type = "camera" +at = "video" +backend = "webcam:0" [[port_forward]] proto = "tcp"; host_port = 2323; guest_port = 23; bind = "localhost" @@ -176,8 +177,10 @@ discs = [ "irix53/Developers Toolbox 6.0 Disc 3.iso", ] -[vino] -source = "camera" +[[devices]] +type = "camera" +at = "video" +backend = "webcam:0" [[port_forward]] proto = "tcp"; host_port = 2323; guest_port = 23; bind = "localhost" diff --git a/clanker/perf/rex3-processor-must-park-when-idle.md b/clanker/perf/rex3-processor-must-park-when-idle.md index dfadca7bd..72373463e 100644 --- a/clanker/perf/rex3-processor-must-park-when-idle.md +++ b/clanker/perf/rex3-processor-must-park-when-idle.md @@ -53,5 +53,5 @@ Combined with the parking fix, idle graphical host CPU dropped ~130% → ~9%. Note a *live* VINO camera source genuinely keeps the guest busy (continuous video DMA → the guest blits each frame via REX3 → `fb_dirty` every frame), so "idle" -with `[vino] source = "camera"` is not truly idle and will render at full rate — +with a `camera` entry with `backend = "webcam:N"` is not truly idle and will render at full rate — that is correct. diff --git a/clanker/video/indycam-cdmc-register-map.md b/clanker/video/indycam-cdmc-register-map.md index 24c82bfb8..907bab686 100644 --- a/clanker/video/indycam-cdmc-register-map.md +++ b/clanker/video/indycam-cdmc-register-map.md @@ -7,7 +7,7 @@ register map, i2c 0x56 ## Symptom -Live camera capture (`[vino] source = "camera"`) produced a recognisable but +Live camera capture (a `camera` entry with `backend = "webcam:N"`) produced a recognisable but uniformly **green** image — luma and geometry correct, red and blue crushed to near zero. Reproduced on IRIX 6.5.22 with `vidtomem -f /tmp/cap -v 0`. diff --git a/clanker/video/indycam-end-to-end-capture.md b/clanker/video/indycam-end-to-end-capture.md index 1dd807888..e69f476de 100644 --- a/clanker/video/indycam-end-to-end-capture.md +++ b/clanker/video/indycam-end-to-end-capture.md @@ -13,7 +13,7 @@ One known visual artifact — see "Open issues" below. ```bash # host -cp iris.toml ... # ensure [vino] source = "camera" (or "test_pattern") +cp iris.toml ... # ensure a `camera` device at `video` with backend "webcam:0" (or "test_pattern") # ensure [scsi.2] scratch = true, size_mb = 16+ ./target/release/iris --ci ./target/release/iris-ci start diff --git a/clanker/video/vino-verification-checklist.md b/clanker/video/vino-verification-checklist.md index 3f67902d8..a3634083e 100644 --- a/clanker/video/vino-verification-checklist.md +++ b/clanker/video/vino-verification-checklist.md @@ -4,7 +4,7 @@ Consolidates guidance from `clanker/irix/vino-*.md`. ## Prerequisites -- `[vino]` configured in TOML; host camera support is built in (no `camera` feature) +- a `camera` device at `video` configured in TOML; host camera support is built in (no `camera` feature) - MC SYSID bit 4 set (`clanker/video/vino-attach-via-sysid-bit4.md`) - GIO alias `0x1F080000` → VINO (`clanker/video/vino-gio-alias-offset.md`) diff --git a/installer/iris-gui.entitlements b/installer/iris-gui.entitlements index d483cb557..3886eec2b 100644 --- a/installer/iris-gui.entitlements +++ b/installer/iris-gui.entitlements @@ -21,7 +21,7 @@ com.apple.security.device.camera diff --git a/iris-gui/core/src/controller/camera.rs b/iris-gui/core/src/controller/camera.rs index 8bb1b857b..4494ec38a 100644 --- a/iris-gui/core/src/controller/camera.rs +++ b/iris-gui/core/src/controller/camera.rs @@ -44,11 +44,12 @@ impl CameraTestController { // it is opened again (its Drop joins the capture thread). self.test = None; if action == CameraAction::Open { - let standard = match cfg.vino.standard { + let vino = cfg.vino(); + let standard = match vino.standard { VinoStandard::Ntsc => VideoStandard::Ntsc, VinoStandard::Pal => VideoStandard::Pal, }; - self.test = Some(CameraTest::start(standard, cfg.vino.camera_index)); + self.test = Some(CameraTest::start(standard, vino.camera_index)); } } } diff --git a/iris-gui/core/src/controller/settings.rs b/iris-gui/core/src/controller/settings.rs index fc1570045..0245b9c87 100644 --- a/iris-gui/core/src/controller/settings.rs +++ b/iris-gui/core/src/controller/settings.rs @@ -849,7 +849,8 @@ impl SettingsController { // Video in: the Indy's VINO input. if p == MachineProfile::IndyIp24 { - let src = VINO_SOURCES.iter().position(|v| *v == cfg.vino.source).unwrap_or(0); + let vino = cfg.vino(); + let src = VINO_SOURCES.iter().position(|v| *v == vino.source).unwrap_or(0); let mut f = vec![ Field { id: field::VINO_SOURCE, @@ -872,17 +873,17 @@ impl SettingsController { help: None, kind: FieldKind::Choice { options: vec![t!("config-vino-ntsc"), t!("config-vino-pal")], - selected: usize::from(cfg.vino.standard == VinoStandard::Pal), + selected: usize::from(vino.standard == VinoStandard::Pal), }, enabled: at_power_on(), }, ]; - if cfg.vino.source == VinoSource::Camera { + if vino.source == VinoSource::Camera { f.push(Field { id: field::VINO_CAMERA, label: t!("config-vino-camera"), help: None, - kind: FieldKind::Number { value: cfg.vino.camera_index as f64, min: 0.0, max: 15.0, step: 1.0, unit: String::new() }, + kind: FieldKind::Number { value: vino.camera_index as f64, min: 0.0, max: 15.0, step: 1.0, unit: String::new() }, enabled: at_power_on(), }); } @@ -1318,6 +1319,18 @@ fn set_num(slot: &mut T, v: T) -> bool { true } +/// Change the video input's source in place; whether it differs. +fn edit_vino(cfg: &mut MachineConfig, edit: impl FnOnce(&mut iris::config::VinoConfig)) -> bool { + let before = cfg.vino(); + let mut vino = before.clone(); + edit(&mut vino); + let changed = vino != before; + if changed { + cfg.set_vino(vino); + } + changed +} + fn set(cfg: &mut MachineConfig, field: &'static str, value: Value) -> bool { let p = cfg.machine.profile; // The guest clock's offset: one signed amount per unit, and a reset. @@ -1446,16 +1459,11 @@ fn set(cfg: &mut MachineConfig, field: &'static str, value: Value) -> bool { }, }, (field::VINO_SOURCE, Value::Index(i)) => match VINO_SOURCES.get(i) { - Some(v) => set_num(&mut cfg.vino.source, v.clone()), + Some(v) => edit_vino(cfg, |c| c.source = v.clone()), None => false, }, - (field::VINO_STANDARD, Value::Index(i)) => { - let v = if i == 1 { VinoStandard::Pal } else { VinoStandard::Ntsc }; - let changed = v != cfg.vino.standard; - cfg.vino.standard = v; - changed - } - (field::VINO_CAMERA, Value::Number(n)) => set_num(&mut cfg.vino.camera_index, n.round().clamp(0.0, 15.0) as _), + (field::VINO_STANDARD, Value::Index(i)) => edit_vino(cfg, |c| c.standard = if i == 1 { VinoStandard::Pal } else { VinoStandard::Ntsc }), + (field::VINO_CAMERA, Value::Number(n)) => edit_vino(cfg, |c| c.camera_index = n.round().clamp(0.0, 15.0) as _), (field::AFFINITY, Value::Bool(b)) => set_num(&mut cfg.perf.thread_affinity, b), // A core this host has: 0 to its count less one. (field::CPU_CORE, Value::Number(n)) => set_num(&mut cfg.perf.cpu_core, Some(n.round().clamp(0.0, host_cores() as f64 - 1.0) as u32)), @@ -1702,7 +1710,7 @@ mod tests { c.apply(action_for(id, v, &[], &[]).expect("an action"), cfg, None).0 }; assert!(set(&mut c, &mut cfg, field::VINO_SOURCE, Value::Index(2))); - assert_eq!(cfg.vino.source, VinoSource::Camera); + assert_eq!(cfg.vino().source, VinoSource::Camera); assert!(c.sections(&cfg, false).iter().flat_map(|s| &s.fields).any(|f| f.id == field::VINO_CAMERA)); assert!(set(&mut c, &mut cfg, field::AFFINITY, Value::Bool(true))); assert!(set(&mut c, &mut cfg, field::REX3_CORE, Value::Number(3.0))); diff --git a/iris-gui/core/src/model/machines.rs b/iris-gui/core/src/model/machines.rs index 632069486..091b81d91 100644 --- a/iris-gui/core/src/model/machines.rs +++ b/iris-gui/core/src/model/machines.rs @@ -165,7 +165,7 @@ pub fn visit_paths(cfg: &mut MachineConfig, mut visit: impl FnMut(&mut String)) } DeviceModel::VirtioSerial(v) => v.ports.iter_mut().filter_map(|p| p.socket.as_mut()).for_each(&mut visit), DeviceModel::Board(b) => b.flash.iter_mut().for_each(&mut visit), - DeviceModel::Net(_) | DeviceModel::XioBoard(_) | DeviceModel::PciBridge | DeviceModel::Ice1724 | DeviceModel::Qla2200 | DeviceModel::Ultra64 | DeviceModel::Empty => {} + DeviceModel::Net(_) | DeviceModel::Camera(_) | DeviceModel::XioBoard(_) | DeviceModel::PciBridge | DeviceModel::Ice1724 | DeviceModel::Qla2200 | DeviceModel::Ultra64 | DeviceModel::Empty => {} } } if let Some(nfs) = &mut cfg.nfs { diff --git a/iris-gui/src/config_ui.rs b/iris-gui/src/config_ui.rs index 542f3fdb9..8eb07ca99 100644 --- a/iris-gui/src/config_ui.rs +++ b/iris-gui/src/config_ui.rs @@ -155,7 +155,7 @@ pub enum ConfigAction { /// profile's built-in PROM loader in `iris::dev::prom::Prom`). RequestEmbeddedProm, /// User clicked "Test Camera" on the Video-In tab; the app should open the - /// host camera and show a live preview (using the current `[vino]` standard + /// host camera and show a live preview (using the current camera standard /// and camera index). TestCamera, /// User clicked "Refresh" on the Network tab's PCAP selector; the app should @@ -1770,37 +1770,42 @@ fn pcap_interface_picker( fn show_vino(ui: &mut Ui, cfg: &mut MachineConfig) -> ConfigAction { let mut action = ConfigAction::None; + let before = cfg.vino(); + let mut vino = before.clone(); ui.heading(t!("config-vino")); Grid::new("vino_grid").num_columns(2).striped(true).show(ui, |ui| { ui.label(t!("config-vino-source")); ComboBox::from_id_salt("vino_src") - .selected_text(match cfg.vino.source { + .selected_text(match vino.source { VinoSource::Camera => t!("config-vino-source-camera"), VinoSource::TestPattern => t!("config-vino-source-test"), VinoSource::Black => t!("config-vino-source-black"), VinoSource::Off => t!("config-vino-source-off"), }) .show_ui(ui, |ui| { - ui.selectable_value(&mut cfg.vino.source, VinoSource::Off, t!("config-vino-source-off")); - ui.selectable_value(&mut cfg.vino.source, VinoSource::TestPattern, t!("config-vino-source-test")); - ui.selectable_value(&mut cfg.vino.source, VinoSource::Camera, t!("config-vino-source-camera")); - ui.selectable_value(&mut cfg.vino.source, VinoSource::Black, t!("config-vino-source-black")); + ui.selectable_value(&mut vino.source, VinoSource::Off, t!("config-vino-source-off")); + ui.selectable_value(&mut vino.source, VinoSource::TestPattern, t!("config-vino-source-test")); + ui.selectable_value(&mut vino.source, VinoSource::Camera, t!("config-vino-source-camera")); + ui.selectable_value(&mut vino.source, VinoSource::Black, t!("config-vino-source-black")); }); ui.end_row(); ui.label(t!("config-vino-standard")); ComboBox::from_id_salt("vino_std") - .selected_text(match cfg.vino.standard { VinoStandard::Ntsc => t!("config-vino-ntsc"), VinoStandard::Pal => t!("config-vino-pal") }) + .selected_text(match vino.standard { VinoStandard::Ntsc => t!("config-vino-ntsc"), VinoStandard::Pal => t!("config-vino-pal") }) .show_ui(ui, |ui| { - ui.selectable_value(&mut cfg.vino.standard, VinoStandard::Ntsc, t!("config-vino-ntsc")); - ui.selectable_value(&mut cfg.vino.standard, VinoStandard::Pal, t!("config-vino-pal")); + ui.selectable_value(&mut vino.standard, VinoStandard::Ntsc, t!("config-vino-ntsc")); + ui.selectable_value(&mut vino.standard, VinoStandard::Pal, t!("config-vino-pal")); }); ui.end_row(); ui.label(t!("config-vino-camera")); - ui.add(DragValue::new(&mut cfg.vino.camera_index).range(0..=15)); + ui.add(DragValue::new(&mut vino.camera_index).range(0..=15)); ui.end_row(); }); + if vino != before { + cfg.set_vino(vino); + } // Live host-camera test: opens the selected camera directly (no IRIX boot // needed) so the user can confirm the capture path works — and, on macOS, diff --git a/iris-gui/src/main.rs b/iris-gui/src/main.rs index 4a171f54a..cf4fb64da 100644 --- a/iris-gui/src/main.rs +++ b/iris-gui/src/main.rs @@ -1857,7 +1857,7 @@ impl App { } /// Open (or restart) the live host-camera preview using the current - /// `[vino]` standard and camera index. Releases any previous test first. + /// camera standard and index. Releases any previous test first. fn open_camera_test(&mut self) { self.camera_test_tex = None; self.camera_test_seq = 0; diff --git a/iris-irix53.toml b/iris-irix53.toml index 1b34a8a8d..2576f1389 100644 --- a/iris-irix53.toml +++ b/iris-irix53.toml @@ -42,8 +42,10 @@ discs = [ "irix53/Developers Toolbox 6.0 Disc 3.iso", ] -[vino] -source = "camera" +[[devices]] +type = "camera" +at = "video" +backend = "webcam:0" [[port_forward]] proto = "tcp" diff --git a/iris-irix65.toml b/iris-irix65.toml index f1175eb3c..18bec8a30 100644 --- a/iris-irix65.toml +++ b/iris-irix65.toml @@ -33,8 +33,10 @@ discs = [ "irix/IRIX 6.5 Foundation 2.iso", ] -[vino] -source = "test_pattern" +[[devices]] +type = "camera" +at = "video" +backend = "test_pattern" [[port_forward]] proto = "tcp" diff --git a/iris.toml b/iris.toml index c27e63c38..2fb0e230f 100644 --- a/iris.toml +++ b/iris.toml @@ -159,13 +159,15 @@ bind = "localhost" #at = "scsi0/t4" #path = "cdrom4.iso" # optional — omit to start with an empty tray -# VINO video-in (IndyCam). Off by default. -# source: "off" | "test_pattern" | "black" | "camera" +# VINO video-in (IndyCam): a `camera` device at the Indy's `video` input. No +# entry, no camera. +# backend: "webcam:N" (host camera N) | "test_pattern" | "black" # standard: "ntsc" | "pal" -#[vino] -#source = "camera" -#standard = "ntsc" -#camera_index = 0 +#[[devices]] +#type = "camera" +#at = "video" +#backend = "webcam:0" +#standard = "ntsc" # ── Networking backend ──────────────────────────────────────────────────────── # backend = "nat" (default): built-in software NAT gateway (DHCP/DNS/ICMP/TCP/UDP diff --git a/src/config.rs b/src/config.rs index c86ff2fbc..6d32b964f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -519,10 +519,10 @@ impl NetDevice { } /// Where VINO's video-in capture should come from. -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum VinoSource { - /// Live host camera capture (built in; selected through `[vino] source`). + /// Live host camera capture (`webcam:N`). /// First run on macOS triggers the camera permission dialog. Camera, /// SMPTE-style colour bars + animated luma ramp. No host capture needed. @@ -530,16 +530,12 @@ pub enum VinoSource { /// Solid black field. Useful when you want IRIX video drivers to attach /// but don't want any host camera permission prompt or test pattern. Black, - /// Video-In disabled: VINO stays memory-mapped (IRIX can still probe it) - /// but no video source is installed and the DMA pump thread is never - /// started. Use this to skip Video-In entirely. + /// No `camera` entry: VINO stays memory-mapped (IRIX can still probe it) + /// but no video source is installed and the DMA pump thread is never started. Off, } impl Default for VinoSource { - // Off by default: most users don't need IndyCam, and this avoids a host - // camera permission prompt, the test-pattern source, and VINO's DMA pump - // thread. Set a source explicitly (`[vino] source = "..."`) to enable it. fn default() -> Self { VinoSource::Off } } @@ -557,6 +553,38 @@ impl Default for VinoStandard { fn default() -> Self { VinoStandard::Ntsc } } +/// A `camera` entry: the picture at a video input. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct CameraDevice { + /// `webcam:N` (host camera N), `test_pattern` or `black`. + #[serde(default = "webcam")] + pub backend: String, + /// Field rate (60 or 50 Hz) and field size. + #[serde(default)] + pub standard: VinoStandard, +} + +fn webcam() -> String { "webcam:0".into() } + +impl Default for CameraDevice { + fn default() -> Self { CameraDevice { backend: webcam(), standard: VinoStandard::default() } } +} + +impl CameraDevice { + /// The source `backend` names, and the host camera's number. + pub fn end(&self) -> Result<(VinoSource, u32), String> { + match self.backend.as_str() { + "test_pattern" => Ok((VinoSource::TestPattern, 0)), + "black" => Ok((VinoSource::Black, 0)), + b => match crate::backend::split(b)? { + ("webcam", n) => n.parse().map(|n| (VinoSource::Camera, n)).map_err(|_| format!("backend {b}: the camera number is not a number")), + (kind, _) => Err(format!("backend \"{b}\": no source {kind}; the sources are webcam:N, test_pattern and black")), + }, + } + } +} + /// One virtio-serial port and the host end it is connected to. /// /// With neither `tcp_port` nor `socket` the port is wired to nothing: output @@ -2123,18 +2151,13 @@ pub struct VncConfig { pub password_file: Option, } -/// VINO video-in configuration. -#[derive(Debug, Clone, Serialize, Deserialize, Default)] +/// VINO video-in as the machine reads it: the `camera` entry at its video input. Also the older `[vino]` table. +#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[serde(default)] pub struct VinoConfig { - /// Where the IndyCam feed comes from. - #[serde(default)] pub source: VinoSource, - /// Broadcast standard. Affects field rate (60 vs 50 Hz) and field size. - #[serde(default)] pub standard: VinoStandard, - /// Index of the host camera to open (0 = default). Only meaningful when - /// `source = "camera"`. - #[serde(default)] + /// The host camera to open, for `VinoSource::Camera`. pub camera_index: u32, } @@ -2283,7 +2306,7 @@ impl TezroSection { /// Field order matters for TOML export: the `toml` serializer requires every /// scalar/inline-value field to be emitted before any table or array-of-table /// field, so all scalars are declared first and the table-valued fields -/// (`scsi`, `nfs`, `port_forward`, `vino`) come last. +/// (`scsi`, `nfs`, `port_forward`) come last. /// /// `deny_unknown_fields` makes typos and misplaced keys a hard parse error /// instead of silently ignoring them. This catches a common footgun: writing @@ -2481,6 +2504,9 @@ pub struct MachineConfig { /// The older `[scsi.N]` tables, until `legacy` turns them into devices. #[serde(default, rename = "scsi", skip_serializing)] pub legacy_scsi: Option, + /// The older `[vino]` table, until `legacy` turns it into a `camera` entry. + #[serde(default, rename = "vino", skip_serializing)] + pub legacy_vino: Option, /// `--scsiN` and `--cdromN`, until `legacy` merges them into the devices. #[serde(skip)] pub legacy_shorthands: Vec, @@ -2514,10 +2540,6 @@ pub struct MachineConfig { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub port_forward: Vec, - /// VINO video-in configuration (IndyCam emulation source). - #[serde(default)] - pub vino: VinoConfig, - /// Built-in VNC server (`[vnc]` section). #[serde(default)] pub vnc: VncConfig, @@ -2753,6 +2775,7 @@ impl Default for MachineConfig { jitv2_threads_reason: String::new(), devices: default_disks(), legacy_scsi: None, + legacy_vino: None, legacy_shorthands: Vec::new(), machine_id: 0, old_keys: Vec::new(), @@ -2785,7 +2808,6 @@ impl Default for MachineConfig { serial_log: None, serial_log_overwrite: false, serial_log_timestamps: Default::default(), - vino: VinoConfig::default(), vnc: VncConfig::default(), network: NetworkSection::default(), mouse_scroll_pixels_per_line: default_scroll_pixels_per_line(), @@ -3735,6 +3757,28 @@ impl MachineConfig { } } + /// The `camera` entry at the video input, as VINO reads it: no entry, no source. + pub fn vino(&self) -> VinoConfig { + match self.port_device("video") { + Some(DeviceModel::Camera(c)) => { + let (source, camera_index) = c.end().expect("camera: parse and set_vino build a valid backend"); + VinoConfig { source, standard: c.standard, camera_index } + } + _ => VinoConfig::default(), + } + } + + /// Plug `vino`'s source into the video input; `Off` unplugs it. + pub fn set_vino(&mut self, vino: VinoConfig) { + let backend = match vino.source { + VinoSource::Camera => format!("webcam:{}", vino.camera_index), + VinoSource::TestPattern => "test_pattern".into(), + VinoSource::Black => "black".into(), + VinoSource::Off => return self.set_port_device("video", None), + }; + self.set_port_device("video", Some(DeviceModel::Camera(CameraDevice { backend, standard: vino.standard, ..Default::default() }))); + } + /// The `net` entry at the Ethernet port: the one a file places there, else the default. pub fn net_end(&self) -> NetDevice { match self.port_device("ethernet") { @@ -5322,6 +5366,27 @@ mod export_tests { assert!(MachineConfig::from_toml_str("[[devices]]\ntype = \"net\"\nbackend = \"tap:x\"\n").is_err()); } + /// The Indy's camera is a `camera` entry at its `video` input. + #[test] + fn the_indys_camera_is_a_camera_entry_at_its_video_input() { + let indy = MachineConfig::from_toml_str("[[devices]]\ntype = \"camera\"\nat = \"video\"\nbackend = \"webcam:2\"\nstandard = \"pal\"\n").unwrap(); + let v = indy.vino(); + assert_eq!((v.source, v.camera_index, v.standard), (VinoSource::Camera, 2, VinoStandard::Pal)); + assert_eq!(MachineConfig::default().vino().source, VinoSource::Off, "no entry, no camera"); + let mut cfg = MachineConfig::default(); + cfg.set_vino(VinoConfig { source: VinoSource::TestPattern, ..Default::default() }); + assert_eq!(cfg.vino().source, VinoSource::TestPattern); + cfg.set_vino(VinoConfig::default()); + assert!(cfg.devices.iter().all(|d| d.device.spec().name != "camera"), "Off removes the entry"); + let cli = Cli::parse_from(["iris", "--device", "camera@video,backend=black"]); + assert_eq!(cli.apply(MachineConfig::default()).vino().source, VinoSource::Black); + let at = |profile: &str, text: &str| MachineConfig::from_toml_str(&format!("[machine]\nprofile = \"{profile}\"\n{text}")).unwrap().resolved(); + let cam = "[[devices]]\ntype = \"camera\"\nat = \"video\"\n"; + assert!(at("o2_ip32", cam).unwrap_err().contains("has no slot video"), "the O2 models no video input"); + assert!(at("indigo2_ip22", cam).unwrap_err().contains("has no slot video"), "nor does the Indigo2"); + assert!(MachineConfig::from_toml_str("[[devices]]\ntype = \"camera\"\nbackend = \"webcam:x\"\n").is_err()); + } + /// Every old `[o2]` key lands on the shared key it stood for, and the /// section keeps only what is the O2's alone. #[test] diff --git a/src/config/legacy.rs b/src/config/legacy.rs index 1372b1e70..e7274beb4 100644 --- a/src/config/legacy.rs +++ b/src/config/legacy.rs @@ -116,6 +116,7 @@ pub(super) const OLD_KEYS: &[OldKey] = &[ fold("o2.forwards", When::Load, |c| took((!c.o2.forwards.is_empty()).then(|| std::mem::take(&mut c.o2.forwards)), |f| c.port_forward.extend(f))), group(&["graphics.board", "impact.gfx", "graphics.heads", "graphics.resolution", "graphics.flash"], When::Chosen, graphics), group(&["network.mode", "network.pcap_interface", "network.stream", "network.mac"], When::Chosen, network), + fold("vino", When::Chosen, vino), fold("o2.net", When::Chosen, o2_net), fold("octane.graphics", When::Load, |c| match c.octane.graphics.take() { Some(old) => Err(format!("octane.graphics has moved: write the board as a [[devices]] entry (was \"{}\")", old.trim())), @@ -398,6 +399,24 @@ pub(super) fn net_flags(cfg: &mut MachineConfig, mode: Option, iface: O } } +/// The older `[vino]` table as the `camera` entry at the Indy's video input. What iris-gui saved as defaults says nothing; a +/// source set where the machine has no video input is dropped, and one beside an entry there is refused. +fn vino(cfg: &mut MachineConfig) -> Result { + let Some(vino) = cfg.legacy_vino.take() else { return Ok(false) }; + if vino == VinoConfig::default() { + return Ok(false); + } + if !cfg.machine.profile.slots().iter().any(|s| s.aliases.iter().any(|a| a == "video")) { + eprintln!("iris: [vino] is ignored: this machine has no video input"); + return Ok(false); + } + if cfg.port_device("video").is_some() { + return Err("[vino] and the entry at video both set the camera; keep one".into()); + } + cfg.set_vino(vino); + Ok(true) +} + /// A bare drive id (`16 * controller + id`), the only way older versions /// named a drive to load or eject. pub(crate) fn drive_number(spec: &str) -> Option { @@ -893,6 +912,18 @@ mod tests { assert!(e.contains("octane.graphics has moved") && e.contains("[[devices]]") && e.contains("maximpact"), "{e}"); } + #[test] + fn the_older_vino_table_makes_the_camera_entry() { + let old = MachineConfig::from_toml_str("[vino]\nsource = \"camera\"\nstandard = \"pal\"\ncamera_index = 1\n").unwrap(); + assert_eq!(old.vino(), VinoConfig { source: VinoSource::Camera, standard: VinoStandard::Pal, camera_index: 1 }); + assert_eq!(old.old_keys, ["vino"]); + assert!(MachineConfig::from_toml_str("[vino]\nsource = \"off\"\n").unwrap().devices.iter().all(|d| d.device.spec().name != "camera")); + assert!(!toml::to_string_pretty(&old.for_writing()).unwrap().contains("[vino]"), "saved in the new form"); + assert!(MachineConfig::from_toml_str("[vino]\nsource = \"off\"\n").unwrap().old_keys.is_empty(), "a default table says nothing"); + let e = MachineConfig::from_toml_str("[vino]\nsource = \"black\"\n[[devices]]\ntype = \"camera\"\nat = \"video\"\nbackend = \"test_pattern\"\n").unwrap_err().to_string(); + assert!(e.contains("keep one"), "{e}"); + } + #[test] fn the_older_network_keys_and_flags_make_the_net_entry() { let text = "[network]\nmode = \"pcap\"\npcap_interface = \"eth0\"\nmac = \"08:00:69:aa:bb:cc\"\n"; diff --git a/src/devices.rs b/src/devices.rs index de02a269f..470d98eb8 100644 --- a/src/devices.rs +++ b/src/devices.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::sync::Arc; use crate::dev::serial_dev::{SerialDeviceConfig, SerialKind}; -use crate::config::{GraphicsBoard, MachineConfig, NetDevice, NvmeConfig, ScsiDeviceConfig, ScsiKind, Virtio9pConfig, VirtioSerialConfig}; +use crate::config::{CameraDevice, GraphicsBoard, MachineConfig, NetDevice, NvmeConfig, ScsiDeviceConfig, ScsiKind, Virtio9pConfig, VirtioSerialConfig}; use crate::dev::ng1::vc2_timings::NewportResolution; use crate::dev::ice1724::{Ice1724, Variant}; use crate::dev::isp2200::{card::Loop, Isp2200}; @@ -45,6 +45,8 @@ pub enum DeviceModel { Serial(SerialDeviceConfig), /// The host end of an Ethernet port. Net(NetDevice), + /// The picture at a video input. + Camera(CameraDevice), } /// What the test device's run-configuration register publishes and where its @@ -165,6 +167,7 @@ pub const DEVICE_TYPES: &[DeviceTypeSpec] = &[ slots: None, }, DeviceTypeSpec { name: "net", family: DeviceFamily::Net, keys: &["backend", "mac"], parse: |_, o| options(o).and_then(|n: NetDevice| n.check().map(|_| DeviceModel::Net(n))), slots: None }, + DeviceTypeSpec { name: "camera", family: DeviceFamily::Video, keys: &["backend", "standard"], parse: |_, o| options(o).and_then(|c: CameraDevice| c.end().map(|_| DeviceModel::Camera(c))), slots: None }, DeviceTypeSpec { name: "serial", family: DeviceFamily::Serial, keys: &["backend"], parse: serial_device, slots: None }, DeviceTypeSpec { name: "hostserial", family: DeviceFamily::Serial, keys: &["path"], parse: serial_device, slots: None }, DeviceTypeSpec { name: "midi_synth", family: DeviceFamily::Serial, keys: &["path", "gain"], parse: serial_device, slots: None }, @@ -235,6 +238,7 @@ impl DeviceModel { DeviceModel::Virtio9p(_) => "virtio_9p", DeviceModel::Serial(d) => d.kind.name(), DeviceModel::Net(_) => "net", + DeviceModel::Camera(_) => "camera", }; DEVICE_TYPES.iter().find(|t| t.name == name).expect("every variant has a type") } @@ -269,6 +273,7 @@ impl DeviceModel { DeviceModel::Serial(s) if !s.backend.is_empty() => format!("serial {}", s.backend.join(" ")), DeviceModel::Board(b) if b.model != GraphicsBoard::Newport => format!("{} {}", self.spec().name, b.model), DeviceModel::Net(n) => format!("net {}", n.backend), + DeviceModel::Camera(c) => format!("camera {}", c.backend), _ => self.spec().name.to_string(), } } @@ -290,6 +295,7 @@ impl DeviceModel { DeviceModel::Serial(d) => changed(d, keys), DeviceModel::Board(b) => changed(b, keys), DeviceModel::Net(d) => changed(d, keys), + DeviceModel::Camera(d) => changed(d, keys), DeviceModel::XioBoard(_) | DeviceModel::PciBridge | DeviceModel::Ice1724 | DeviceModel::Qla2200 | DeviceModel::Ultra64 | DeviceModel::Empty => toml::Table::new(), } } diff --git a/src/machine.rs b/src/machine.rs index 8d6ba24d0..1712fcbf0 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -657,7 +657,7 @@ impl Machine { hpc3.set_phys(phys.clone()); // Connect VINO to System Memory, install a video source, start DMA. - // Source kind + broadcast standard come from `[vino]` in iris.toml. + // Source kind + broadcast standard come from the `camera` entry at `video`. board.vino.set_phys(phys.clone()); if let Some(mgras) = &board.mgras { mgras.set_phys(phys.clone()); } if let Some(mgras) = &board.mgras_head1 { mgras.set_phys(phys.clone()); } @@ -670,14 +670,15 @@ impl Machine { if board.mgras_head1.is_some() { eprintln!("iris: host GL is not available on the IMPACT board in gio0"); } - let standard = match cfg.vino.standard { + let vino = cfg.vino(); + let standard = match vino.standard { crate::config::VinoStandard::Ntsc => crate::video_source::VideoStandard::Ntsc, crate::config::VinoStandard::Pal => crate::video_source::VideoStandard::Pal, }; - let source: Option> = match cfg.vino.source { + let source: Option> = match vino.source { crate::config::VinoSource::Camera => { { - let idx = cfg.vino.camera_index; + let idx = vino.camera_index; match crate::dev::camera::CameraSource::new_with_index(standard, idx) { Ok(c) => Some(Arc::new(c)), Err(e) => { diff --git a/src/slot_path.rs b/src/slot_path.rs index 6421668dd..6fccc1fe4 100644 --- a/src/slot_path.rs +++ b/src/slot_path.rs @@ -23,6 +23,8 @@ const TAGS: &[(&str, bool)] = &[ ("serial", true), // serial port N, as numbered on the case ("mace", false), ("ethernet", false), // the Ethernet port of the part above it + ("vino", false), + ("video", false), // the video input of the part above it ]; const BARE: u8 = 3; diff --git a/src/topology.rs b/src/topology.rs index 9ec486815..5ead635bb 100644 --- a/src/topology.rs +++ b/src/topology.rs @@ -28,6 +28,8 @@ pub enum DeviceFamily { Serial, /// The host end of an Ethernet port. Net, + /// The picture at a video input. + Video, Empty, } @@ -43,6 +45,7 @@ impl DeviceFamily { DeviceFamily::Virtio => "virtio devices", DeviceFamily::Serial => "serial devices", DeviceFamily::Net => "network backends", + DeviceFamily::Video => "cameras", DeviceFamily::Empty => "nothing", } } @@ -287,6 +290,9 @@ impl MachineProfile { boards(&mut s, "gio0", if self == P::IndyIp24 { &[GraphicsBoard::Newport] } else { GIO0_BOARDS }, None); if self == P::IndyIp24 { sole_board(&mut s, "gfx", "an IMPACT board is an Indigo2 option, and an Indy's GIO slots do not take one"); + // The Indy's VINO, with its one video input. + fixed_slot(&mut s, "vino", "vino", &[]); + open_slot(&mut s, "vino/video", &[DeviceFamily::Video], &["video"]); } } P::O2Ip32 => crate::ip32_machine::slots(&mut s), diff --git a/src/tree.rs b/src/tree.rs index 1456c455d..989841dc2 100644 --- a/src/tree.rs +++ b/src/tree.rs @@ -158,6 +158,8 @@ mod tests { "|-- gfx (graphics) newport default", "|-- gio1 - takes: virtio devices", "|-- gio0 - takes: gio cards, virtio devices, a graphics board (newport)", + "|-- vino vino built-in", + "| `-- video (video) - takes: cameras", "|-- serial1 serial tcp:8881 default", "`-- serial2 serial tcp:8880 default", ]); From c04bb2b85b2ebabb46e5dbc1335df6e7870cb6db Mon Sep 17 00:00:00 2001 From: James Braid Date: Sat, 28 Nov 2026 19:57:18 -0700 Subject: [PATCH 4/4] audio: place each sound chip's host output as a device at its port [audio] set the host output of every sound chip at once, and --audio-host overrode part of it, while a serial port or the Ethernet takes its host end as a device at the port. A sound chip's output is a port too: `audio` on the Indy's and Indigo2's HAL2, the O2's MACE and the Octane's and Onyx2's RAD1, and `CARD/audio` under an ice1724 card. An `audio` entry there names the host output: default, pulse, wasapi, coreaudio, null or file:PATH, with prebuf_ms, latency_ms and channels. A port with no entry plays to the host as before, and `none` at it keeps the chip and drops its sound. `no_audio` stays a run-mode flag. The machine reads the entry through `audio()` and the GUI writes it through `set_audio()`, as for the Ethernet and the camera; a card reads its own port where it is built. A serial `midi_synth` is not at that port, so it takes a `backend` of its own (the same values) instead of following the machine's entry: `none` at `audio` no longer mutes it, and a machine with no sound port can still send it to null or a file. A machine with no sound chip (the Fuel, the Origin machines) has no such port; the Tezro's channels setting moves to the entry at its card. iris-gui wrote an `[audio]` table into every machine it saved, so refusing it would have made every saved machine fail to load. The table is read with a warning and turned into the entry in memory, and the GUI saves the entry. A table at its defaults says nothing and leaves no entry, so the Fuel's saved `[audio]` stays quiet. Any other table beside an entry at the port is an error; where the machine has no sound port it is dropped with a warning. The --audio-host flag is a hidden option that sets the same entry after the file is read, so it beats the file's entry. Production lines: +204 -60 --- CHANGELOG.md | 13 ++ FEATURES.md | 26 +--- HELP.md | 17 ++- README.md | 2 +- TESTING.md | 4 +- clanker/devices/audio-test-suite.md | 2 +- clanker/devices/cpal-alsa-busy-poll.md | 4 +- clanker/devices/host-audio-is-iris-audio.md | 8 +- clanker/irix/midi-on-a-serial-port.md | 2 +- docs/dev/hal2.md | 6 +- docs/fuel-ip34.md | 2 +- docs/origin3200-ip35.md | 2 +- docs/tezro-ip53.md | 4 +- fuel.toml.example | 2 +- iris-gui/core/src/model/machines.rs | 33 ++++- iris-gui/src/config_ui.rs | 28 ++-- iris.toml | 14 +- irix-install/iris-indigo2-smoke-ci.toml | 3 - irix-install/iris-smoke-ci.toml | 3 - irix-install/iris-windows-384.toml | 4 +- irix-install/iris-windows-safe.toml | 4 +- irix-install/iris-windows.toml | 4 +- origin3200.toml.example | 2 +- src/chime_tests.rs | 4 +- src/config.rs | 155 +++++++++++++++----- src/config/legacy.rs | 47 ++++++ src/config/write.rs | 2 +- src/dev/hal2.rs | 4 +- src/dev/hpc3.rs | 1 + src/dev/ice1724.rs | 6 +- src/dev/mace_audio.rs | 2 +- src/dev/rad1.rs | 2 +- src/dev/serial_dev/midi.rs | 4 +- src/dev/serial_dev/mod.rs | 27 +++- src/devices.rs | 16 +- src/host_audio.rs | 16 +- src/ip27.rs | 4 + src/ip27_machine.rs | 2 +- src/ip30_machine.rs | 3 +- src/ip32_machine.rs | 3 +- src/iris_ci_boot.rs | 13 +- src/machine.rs | 2 +- src/slot_path.rs | 1 + src/topology.rs | 3 + src/tree.rs | 1 + test/audiotest/check.py | 2 +- test/audiotest/host.sh | 2 +- tezro.toml.example | 4 +- tools/netbsd-cd-boot.py | 5 +- wsl/README.md | 2 +- 50 files changed, 361 insertions(+), 161 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25b1e4ea5..b6265829d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -175,6 +175,19 @@ hashes are given where a change is easiest to understand by reading the commit. is not its default, beside an entry at the port, is an error. `tftp_dir`, `rsh_dir`, `rx_hold` and `nfs_pcap_ip` stay. +### Audio + +- A sound chip's host output is an `audio` device at its `audio` port (an + ICE1724 card's is `CARD/audio`): `backend` is `default`, `pulse`, `wasapi`, + `coreaudio`, `null` or `file:PATH`, with `prebuf_ms`, `latency_ms` and + `channels`. A port with no entry plays to the host; `type = "none"` keeps the + chip and drops its sound. The `[audio]` table is read with a warning and saved + as the entry (an error beside one at the port), as is `--audio-host`, which + replaces the file's entry. +- A serial `midi_synth` plays where its own `backend` says (the same values), + not where the machine's sound goes, so it works on machines with no sound + port. `[audio] host` and `file` no longer reach it. + ### IndyCam - The camera is a `camera` device at the Indy's `video` input: `backend` is diff --git a/FEATURES.md b/FEATURES.md index 7edb4315e..1b8d9dfa9 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -136,7 +136,7 @@ get (`scripts/dist/lib.sh`'s `DEFAULT_GUI_FEATURES`, plus `bundled`). Source: [iris-audio/Cargo.toml](iris-audio/Cargo.toml). The host audio output every sound device plays through (HAL2, MACE audio, RAD1, ICE1724), selected at -run time with `[audio] host`. It is a workspace of its own, built through the +run time by an `audio` device's `backend`. It is a workspace of its own, built through the core's path dependency, and the core takes its default features. | Feature | Purpose | Enables | @@ -344,7 +344,7 @@ Tezro-specific settings apply when `machine.profile = "tezro_ip53"`. | `flash` | unset | Persistent 16 MiB boot-flash file. Unset, the flash is volatile. | | `l1_port` | `8882` | Host TCP port for the L1 console. | | `l1_log` | unset | Optional serial log path for L1 output when it is not the console. | -| `audio` | `false` | Add the ICE1724 audio controller on the IO9's PCI bridge. Off, the bridge's bus is empty. On, it plays to the host as `[audio]` sets, or silently with `no_audio`. See the [Tezro guide](docs/tezro-ip53.md). | +| `audio` | `false` | Add the ICE1724 audio controller on the IO9's PCI bridge. Off, the bridge's bus is empty. On, it plays to the host as an `audio` entry at `CARD/audio` sets, or silently with `no_audio`. See the [Tezro guide](docs/tezro-ip53.md). | The machine runs the 700 MHz R16000 (`r16000_700`, the default), or the 800, 900 or 1000 MHz one (`r16000_800`, `r16000_900`, `r16000_1000`, with 4, 8 and 16 MiB @@ -419,18 +419,19 @@ takes; `--device [NAME:]TYPE[@SLOT][,KEY=VALUE]...` adds or replaces one from th | `qla2200` | a PCI slot | A QLogic ISP2200 Fibre Channel adapter; its disks are `hdd` entries at `CARD/loopN`, N the loop ID 0 to 125. The Origin 3200 and Onyx 3000 have one fitted at `xio15/pci0/1`. See [docs/fibre-channel.md](docs/fibre-channel.md). | | `camera` | the Indy's video input (`video`; `--list-slots` shows it) | `backend`: `webcam:N` (host camera N, `webcam:0` when unset), `test_pattern` or `black`; `standard`: `ntsc` (60 fields/s) or `pal` (50). With no entry VINO stays mapped but has no source and starts no DMA thread. | | `net` | an Ethernet port (`ethernet`: the machine's own; a card that has one brings `CARD/ethernet`) | `backend`: `nat` (the default: the built-in gateway), `pcap` or `pcap:IFACE` (a host interface; needs `--features pcap`), `stream:tcp:IP:PORT` or `stream:unix:PATH` (a private segment; not shared with a DaynaPort); `mac` (`08:00:69:12:34:56` when unset; injected only into blank PROM battery-backed MAC slots). A port with no entry is NAT, and `none` there unplugs it (the MAC goes with the entry). See [NETWORKING.md](NETWORKING.md). | +| `audio` | a sound port (`audio`: the Indy's, Indigo2's, O2's, Octane's and Onyx2's own chip; an ICE1724 card brings `CARD/audio`) | `backend`: `default` (CoreAudio on macOS, WASAPI on Windows, a PulseAudio server or PipeWire's pipewire-pulse on Linux and the other Unixes), `pulse`, `wasapi`, `coreaudio`, `null` (the device runs and its sound is discarded) or `file:PATH` (a 48 kHz 16-bit WAV file, written in real time as the host stream would play it, silence included; for headless runs and for checking what a guest played); `prebuf_ms` (`20`: how much sound a stream holds before it plays, the margin against a late guest and the latency iris adds); `latency_ms` (the host device's buffer; unset: its low-latency default); `channels` (`2`: speakers the Tezro's multichannel card plays to, 2, 4, 6 or 8; other sound devices are stereo). The stream follows a change of the host's default output device and keeps running with no device or server until one appears. A port with no entry plays to the host, and `none` there keeps the chip and discards its sound. | | `serial` | a serial port (`serial1`, `serial2`, ...; `--list-slots` lists them) | `backend`: one string or a list of `tcp:PORT` (telnet on 127.0.0.1, 0 = any free port), `unix:PATH` (raw bytes) and `log:PATH` (a transcript). The device replaces the port's default (TCP 8880 and up; under `--ci` any free port on every port but the console); with no `backend` the port is unplugged. `hostserial`, `midi_synth` and `midi_raw` put a device on the port instead. See [HELP.md](HELP.md#serial-ports). | -| `ice1724` | a PCI slot | The IC Ensemble ICE1724 audio card; plays as `[audio]` sets. | +| `ice1724` | a PCI slot | The IC Ensemble ICE1724 audio card; plays as the `audio` entry at `CARD/audio` sets. | | `pci_cage`, `pci_shoehorn` | an Octane XIO slot (`xio9` to `xio13`; the cage at `xio13`, alias `pci_module`) | The PCI module (slots 1 to 3) and the single-slot XIO-to-PCI adapter; see [docs/pci.md](docs/pci.md#option-boards-in-xio-slots). | | `pci_bridge` | a PCI slot | A PCI-to-PCI bridge, with one slot behind it at `BRIDGE/pci0/0`. | | `virtio_serial` | a spare slot (a GIO slot on the Indy and Indigo2) | `port` tables, `[[devices.port]]`, at most 31: `name`, `console`, and `tcp_port` (raw TCP on 127.0.0.1) or `socket` (a Unix socket, exclusive with `tcp_port`); one console on TCP 8890 when none. See [docs/dev/virtio-serial.md](docs/dev/virtio-serial.md). | | `virtio_9p` | a spare slot | `path` (required), `tag` (`"share"`), `readonly`, `owners` (`"squash"` or `"passthrough"`), `uid`, `gid`, `uid_map`, `gid_map`. Needs a Unix host; see [docs/dev/virtio-9p.md](docs/dev/virtio-9p.md). | | `ultra64`, `test_device` | `gio0` | The N64 development board (needs an external gopher64 peer), the bare-metal test device (`dump`, `run_config` as `time_pct=N,repeats=N,groups=MASK`; with `cheritest_dump_hook`) and the Indy's or Indigo2's second Newport head, and the Indigo2's second IMPACT. | | `hostserial` | a serial port, `serialN`, N the number on the machine's case (`serial1` and `serial2`; the Onyx2's MediaIO adds `serial3` and `serial4`); `at` is required | `path` (required): a host serial port such as `"/dev/ttyUSB0"`. Its rate, framing, DTR, RTS and break follow the guest; its CTS, DCD, DSR and RI are the guest's modem inputs. Linux and macOS. See the serial ports section of [HELP.md](HELP.md). | -| `midi_synth` | a serial port, as `hostserial` | `path` (required): a General MIDI SoundFont (`.sf2`), loaded at start. `gain` (`1.0`, 0 to 16): times the synth's own level, which leaves room for many voices; the host mix clips above full scale. Plays into the host's audio as a stream of its own (muted by `no_audio`); with `[audio] file`, into a file beside it (`out.wav` → `out-midi.wav`); `IRIS_MIDI_CAPTURE=file.wav` also records it. | +| `midi_synth` | a serial port, as `hostserial` | `path` (required): a General MIDI SoundFont (`.sf2`), loaded at start. `gain` (`1.0`, 0 to 16): times the synth's own level, which leaves room for many voices; the host mix clips above full scale. `backend` (the host's default): where it plays, as an `audio` entry's backend (`default`, `pulse`, `wasapi`, `coreaudio`, `null` or `file:PATH`), whatever the machine's own sound does. It plays as a stream of its own (muted by `no_audio`); with a `file:` backend, into a file beside it (`out.wav` → `out-midi.wav`); `IRIS_MIDI_CAPTURE=file.wav` also records it. | | `midi_raw` | a serial port, as `hostserial` | `path` (required): a host MIDI port. A raw MIDI device (Linux: `"/dev/snd/midiC1D0"` or `"/dev/midi1"`) passes the bytes as they are, both ways; a host serial port with a MIDI interface (`"/dev/ttyUSB0"`) is set up as `hostserial` does. | | `newport`, `express`, `impact`, `vpro`, `kona` | the graphics slot (alias `graphics`) | A graphics board; see [Graphics boards](#graphics-boards). | -| `none` | any slot; `at` is required | Leaves the slot empty, so the default for it is not placed. A graphics board slot stays free for another board; any other slot stays held. At a serial or Ethernet port it also drops the host end, as a `serial` with no `backend`; an Ethernet port's MAC goes too, and the machine's own is used. The Indy and Indigo2 always have their Ethernet. | +| `none` | any slot; `at` is required | Leaves the slot empty, so the default for it is not placed. A graphics board slot stays free for another board; any other slot stays held. At a serial, Ethernet or sound port it also drops the host end, as a `serial` with no `backend`; an Ethernet port's MAC goes too, and the machine's own is used, and a sound port's chip keeps running with its sound discarded. The Indy and Indigo2 always have their Ethernet. | @@ -511,16 +512,6 @@ Omit `[nfs]` to disable the share; the default forward list is empty. | `vnc.max_fps` | `30` | Most updates a second sent to a viewer (1–120). | | `vnc.password_file` | `unset` | File holding the VNC password (RFB VNC Authentication: first 8 bytes; a trailing newline is dropped). `--vnc-password-file` sets it. Unset: `IRIS_VNC_PASSWORD_FILE`, then `IRIS_VNC_PASSWORD` (the password itself) from the environment, then no password. Standalone `iris` only; see [HELP.md](HELP.md#vnc). | -### [audio] - -| Key | Default | Values and behavior | -|---|---|---| -| `audio.host` | `"default"` | Host audio system: `"default"` (CoreAudio on macOS, WASAPI on Windows, a PulseAudio server or PipeWire's pipewire-pulse on Linux and the other Unixes), `"pulse"`, `"wasapi"`, `"coreaudio"`, or `"null"` (the devices run and their sound is discarded). `"alsa"` and `"pulseaudio"` from older configurations mean `"default"` and `"pulse"`. The stream follows a change of the host's default output device, and keeps running with no device or server until one appears. `--audio-host` overrides. | -| `audio.prebuf_ms` | `20` | How much sound a stream holds before it plays and keeps queued afterwards: the margin against the emulated device running late, and the latency iris adds. Raise it if sound breaks up on a busy host. | -| `audio.latency_ms` | `unset` | How much the host's device should buffer. Unset: the host system's low-latency default. | -| `audio.channels` | `2` | Speakers the Tezro's multichannel card plays to: 2, 4 (quad), 6 (5.1) or 8 (7.1). The card folds its channels down to this many; any other value plays stereo. Other sound devices are stereo. | -| `audio.file` | `unset` | Play into this WAV file instead of a sound card: 48 kHz 16-bit, written in real time as the host stream would play it, silence included. For headless runs and for checking what a guest played. | - ### [jitv2] | Key | Default | Values and behavior | @@ -676,7 +667,6 @@ iris-gui does not parse this standalone option set; use its named-machine UI. | `--2x` | 2× window scaling for HiDPI/4K monitors | | `--headless` | Suppress the standalone window (platform-specific graphics/console behavior, as `headless`; audio unaffected) | | `--noaudio` | Disable host audio output, as `no_audio`; graphics is unaffected | -| `--audio-host ` | Host audio system: `default`, `pulse`, `wasapi`, `coreaudio` or `null` (overrides `[audio] host`) | | `--nfs-dir` | Enable NFS share: path to the directory to export (enables NFS) | | `--nat-subnet` | NAT subnet in CIDR notation (e.g. 192.168.5.0/24). Gateway gets .1, guest (IRIX) gets .2. Default: 192.168.0.0/24. | | `--validate` | Check the configuration (parse, settings, files, directories, ports) without starting the machine; exit 0 or 1. See [HELP.md](HELP.md#checking-a-configuration). | @@ -770,7 +760,7 @@ mistaken for GUI settings. | `GR2_JIT_DISASM` | Any presence prints each GR2 span shader's machine code as it compiles. | [src/dev/gr2/re3_jit/compiler.rs](src/dev/gr2/re3_jit/compiler.rs) | | `GR4_JIT_DISASM` | Any presence prints each IMPACT raster shader's machine code as it compiles. | [src/dev/mgras/rss_jit/compiler.rs](src/dev/mgras/rss_jit/compiler.rs) | | `IRIS_BAKE_HOOKS` | Any presence bakes callout hook addresses into JIT code (experimental). | [src/cpu/jitv2/codegen.rs](src/cpu/jitv2/codegen.rs) | -| `IRIS_AUDIO_DUMP` | File to record what every sound card plays (HAL2, MACE audio, RAD1, ICE1724) at the card's own rate, before conversion. RAD1 and ICE1724 record only with `[audio]` enabled. The layout is in the module. | [src/dev/audio_dump.rs](src/dev/audio_dump.rs) | +| `IRIS_AUDIO_DUMP` | File to record what every sound card plays (HAL2, MACE audio, RAD1, ICE1724) at the card's own rate, before conversion. RAD1 and ICE1724 record only with audio enabled. The layout is in the module. | [src/dev/audio_dump.rs](src/dev/audio_dump.rs) | | `IRIS_PPMEM_BACKEND` | `mach` backs guest RAM with Mach memory entries instead of POSIX shared memory (macOS), as the App Sandbox build does; for testing that path. | [src/ppmem/map_unix.rs](src/ppmem/map_unix.rs) | | `IRIS_CHD_DIFF_DIR` | Redirect CHD diff sidecars; GUI App Store sets a writable container directory. | [src/chd_disk.rs](src/chd_disk.rs) | | `IRIS_CRASH_DIAG` | off disables Windows crash handler installation. | [src/crash_diag.rs](src/crash_diag.rs) | @@ -853,7 +843,7 @@ tests, and subprocesses the tests start. A normal run never needs them. | `GR2_REPLAY` | Replay input path for opt-in GR2 tests. | [src/dev/gr2/hq2_tests.rs](src/dev/gr2/hq2_tests.rs) | | `GR2_REPLAY_OUT` | GR2 replay dump prefix (default gr2replay). | [src/dev/gr2/hq2_tests.rs](src/dev/gr2/hq2_tests.rs) | | `GR4_JIT_SWEEP`, `GR4_JIT_SEED` | Widen and reseed the IMPACT raster JIT's key sweep against the interpreter. | [src/dev/mgras/rss_jit_tests.rs](src/dev/mgras/rss_jit_tests.rs) | -| `IRIS_AUDIO_LOOPBACK` | Real-device audio tests: `:`, the `[audio] host` a card plays through (`default` or `pulse`) and the PulseAudio source that hears the default output (`default:iris_sink.monitor`). Linux; the tests skip when it is unset. | [src/host_audio.rs](src/host_audio.rs) | +| `IRIS_AUDIO_LOOPBACK` | Real-device audio tests: `:`, the `audio` backend a card plays through (`default` or `pulse`) and the PulseAudio source that hears the default output (`default:iris_sink.monitor`). Linux; the tests skip when it is unset. | [src/host_audio.rs](src/host_audio.rs) | | `IRIS_BENCH_ELF`, `IRIS_BENCH_RESULTS` | The benchmark-accuracy test: a rebuilt suite binary instead of `bench/prebuilt/irisbench.elf`, and a directory to collect the parsed results in. | [tests/bench_accuracy.rs](tests/bench_accuracy.rs) | | `IRIS_CONST_DUMP` | Presence prints selected disassembly lines in constant-dedup tests. | [src/cpu/jitv2/mod.rs](src/cpu/jitv2/mod.rs) | | `IRIS_CONST_MODE` | Select the opt-in constant-dedup codegen test shape. | [src/cpu/jitv2/mod.rs](src/cpu/jitv2/mod.rs) | diff --git a/HELP.md b/HELP.md index 1aa8130e0..61895d01d 100644 --- a/HELP.md +++ b/HELP.md @@ -598,14 +598,15 @@ type = "midi_synth" at = "serial1" # the Tezro's first DB9 path = "GeneralUser-GS.sf2" gain = 2.0 # optional +backend = "null" # optional: default, pulse, wasapi, coreaudio, null or file:PATH ``` `gain` sets how loud the synth plays (`gain = 2.0` is twice as loud). The default is the synth's own level, which leaves room for a whole General MIDI song: a single line of notes sounds quiet at it, and a loud song with a high gain clips. The synth plays as an output stream of its own, beside the -machine's sound; when `[audio] file` records the machine to a WAV, the synth -writes its own file beside it (`out.wav` and `out-midi.wav`). It plays +machine's sound, and its `backend` is its own: the machine's `audio` entry does not touch it. With a +`file:` backend it writes a WAV beside the name given (`out.wav` and `out-midi.wav`). It plays channel messages and resets on GM System On, GS Reset and System Reset; it sends nothing back. `no_audio` mutes it. @@ -924,12 +925,13 @@ path = "cdrom4.iso" # backend = "webcam:0" # host camera N, or "test_pattern" or "black" # standard = "ntsc" # or "pal" -[audio] -# host = "default" # or "pulse", "wasapi", "coreaudio", "null" (discard) -prebuf_ms = 20 # sound held before playing: the margin against a late guest, and the latency added +# [[devices]] # host sound; no entry plays to the host, type = "none" discards it +# type = "audio" +# at = "audio" # an ICE1724 card's is CARD/audio +# backend = "default" # or "pulse", "wasapi", "coreaudio", "null" (discard), "file:out.wav" +# prebuf_ms = 20 # sound held before playing: the margin against a late guest, and the latency added # latency_ms = 20 # what the host's device buffers; unset: its low-latency default -# channels = 2 # speakers for the Tezro's multichannel card: 2, 4, 6 or 8 -# file = "out.wav" # play into a WAV file instead of a sound card +# channels = 2 # speakers for the Tezro's multichannel card: 2, 4, 6 or 8 # Cards go in the same list. Left without `at`, a virtio device takes a spare slot the # board has for it, and a PCI card the first real slot. @@ -1114,7 +1116,6 @@ Display and audio --keyboard Host keyboard: ansi (default), iso or jis --headless No window; drops Newport (other boards stay fitted), O2 uses serial --noaudio Disable sound device output (graphics unaffected) - --audio-host HOST Host audio: default, pulse, wasapi, coreaudio or null Networking --nat-subnet NAT subnet, e.g. 192.168.5.0/24 diff --git a/README.md b/README.md index 3a2e448a3..205ad4f4b 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ boots to a usable system: shell, networking, X11, the works. binary); `prom` names a file to run instead - Sound on every machine that has it (HAL2, the O2's MACE audio, RAD, ICE1724) through the `iris-audio` crate: PulseAudio or PipeWire on Linux, WASAPI on - Windows, CoreAudio on macOS, or into a WAV file (`[audio] file`) + Windows, CoreAudio on macOS, or into a WAV file (an `audio` entry's `file:PATH`) - Cranelift JIT compiler for MIPS to host code (`jitv2`, optional, experimental) with persistent compiled-page cache, GPR register caching in loops, and faster FPU/inline paths; plus a REX3 draw pipeline of 400+ precompiled specialised draw functions and an diff --git a/TESTING.md b/TESTING.md index d9985e7a2..7655d194d 100644 --- a/TESTING.md +++ b/TESTING.md @@ -231,14 +231,14 @@ A sound card can break anywhere between guest memory and the host's speakers, and a CI runner has no speakers. Two backends hear what a card sends to the host: -- **`[audio] file`**: the card's host stream played into a WAV file in real +- **A `file:` audio backend**: the card's host stream played into a WAV file in real time, silent where the card was late. It needs no sound card. It goes through the stream's prebuffer and rate conversion (no clock following, so 48 kHz is copied exactly), but cannot see the host's audio system, its sound server or its mixer. - **The real device** (Linux): the card plays into the host's default output and the test records it back from a loopback. `IRIS_AUDIO_LOOPBACK` names - it as `:`: the `[audio] host` the card plays + it as `:`: the audio backend the card plays through (`default` or `pulse`) and the PulseAudio source that hears the default output, recorded with `parec`. With the variable unset these tests print `SKIPPED: IRIS_AUDIO_LOOPBACK not set` and pass. With it set, a diff --git a/clanker/devices/audio-test-suite.md b/clanker/devices/audio-test-suite.md index 327c4cb9e..f4c7ceff9 100644 --- a/clanker/devices/audio-test-suite.md +++ b/clanker/devices/audio-test-suite.md @@ -53,7 +53,7 @@ to a file: then the pairs, little-endian (`src/dev/audio_dump.rs`). It needs no host sound device, but RAD1 and the ICE1724 record nothing under `no_audio`. `check.py` measures each case at its records' rate. -- `[audio] file = "FILE"` writes a 48 kHz stereo 16-bit WAV of what the host +- An `audio` entry with `backend = "file:FILE"` writes a 48 kHz stereo 16-bit WAV of what the host stream plays; `check.py` reads the rate from its header. ```sh diff --git a/clanker/devices/cpal-alsa-busy-poll.md b/clanker/devices/cpal-alsa-busy-poll.md index eb0094b2f..422a9fe21 100644 --- a/clanker/devices/cpal-alsa-busy-poll.md +++ b/clanker/devices/cpal-alsa-busy-poll.md @@ -1,4 +1,4 @@ -# cpal's ALSA backend can spin a core: `[audio] host = "pulseaudio"` +# cpal's ALSA backend can spin a core: `backend = "pulse"` on the audio device avoids it **Status: history (2026-11-13).** cpal is gone: every sound device plays through the `iris-audio` crate, whose Linux backend is the PulseAudio @@ -19,7 +19,7 @@ loops, about five million times a second. Seen through PipeWire's ALSA plugin with the same period and buffer sizes sleeps normally, so it is cpal's loop, not the driver. Not reproduced yet on bare metal; it may need the VM's timing. -**Workaround.** `[audio] host = "pulseaudio"` (or `--audio-host pulseaudio`): +**Workaround.** an `audio` device with `backend = "pulse"` (or `--device audio@audio,backend=pulse`): cpal's own PulseAudio client (pure Rust, the `pulseaudio` feature) talks to a PulseAudio server or PipeWire's pipewire-pulse over the socket. The same stream used 0.01 s of CPU in 5 s. The default stays ALSA until the bug is diff --git a/clanker/devices/host-audio-is-iris-audio.md b/clanker/devices/host-audio-is-iris-audio.md index ffa294bf0..fe8746ceb 100644 --- a/clanker/devices/host-audio-is-iris-audio.md +++ b/clanker/devices/host-audio-is-iris-audio.md @@ -9,7 +9,7 @@ capture_var) -> Option`. A device then calls `out.set_rate()` when the guest reprograms its clock and `out.write(&[i16])` with whole frames. Everything else is the library's, on the far side of its ring: rate conversion, following the guest's clock (it bends the ratio by up -to 0.5%), the prebuffer (`[audio] prebuf_ms`), following the host's default +to 0.5%), the prebuffer (the `audio` entry's `prebuf_ms`), following the host's default device, and running with no device (`null_fallback` is always set, so an open never needs a retry). @@ -19,11 +19,11 @@ Rules that follow: prebuffer and the cards' once-a-second reopen were removed for this. - **What reaches a sound card or the null host is never sample-exact**, even at equal rates: the clock follower always runs the frames through the - rate converter. `[audio] file` turns the follower off (`max_adjust` 0), so + rate converter. A `file:` audio backend turns the follower off (`max_adjust` 0), so a card at 48 kHz is recorded exactly and others at a fixed ratio; a guest clock off the host's then underruns or skips instead. Tests that need the card's exact frames read a tap (`Sink::tap`, `PcmOut::tap`), a detached - stream (`host_audio::test_signal::detached`) or an `[audio] file`. + stream (`host_audio::test_signal::detached`) or an `audio` entry with a `file:` backend. - **Underruns are counted in times, not samples** (`Output::stats()`), and only while the device has not called `idle()`. Only HAL2 calls `idle()` (codec A disarmed). @@ -36,7 +36,7 @@ Rules that follow: prebuffer and clock follower, and a file or capture hears the mix. Voices are not sample-aligned with one another, which is why the ICE1724 still sums its analog and S/PDIF engines itself. -- **The ICE1724 folds to `[audio] channels`** (default 2) itself with its +- **The ICE1724 folds to the `audio` entry's `channels`** (default 2) itself with its BS.775 matrix. The library cannot report how many speakers the host has (the Pulse backend opens whatever width is asked and lets the server mix), and its own fold of 8 slots to stereo divides the level by four. diff --git a/clanker/irix/midi-on-a-serial-port.md b/clanker/irix/midi-on-a-serial-port.md index 28d3b72d2..b8b5917c3 100644 --- a/clanker/irix/midi-on-a-serial-port.md +++ b/clanker/irix/midi-on-a-serial-port.md @@ -13,6 +13,6 @@ Status: howto, 2026-11-26 (Tezro, IRIX 6.5). `mdOpenOutPort(name)`, `mdSetStampMode(p, MD_NOSTAMP)` to send at once, and `mdSend(p, &ev, 1)` with `ev.msg[0..2]` = status, data1, data2. - Check the host end with the monitor's `serial`: the `midi_synth` line counts - messages and notes. With `[audio] host = "null"`, `IRIS_MIDI_CAPTURE=x.wav` + messages and notes. With `backend = "null"` on the `midi_synth`, `IRIS_MIDI_CAPTURE=x.wav` still records the synth, so a test needs no speakers. - IRIX `grep` has no `\|`: use `egrep 'a|b'`. diff --git a/docs/dev/hal2.md b/docs/dev/hal2.md index 2d94250a0..b7ffc5f56 100644 --- a/docs/dev/hal2.md +++ b/docs/dev/hal2.md @@ -314,9 +314,9 @@ avoid advancing into descriptors the guest has not prepared. - Codec A keeps a host output stream open across enable/disable cycles and writes guest-rate stereo frames to it. The stream (the `iris-audio` crate) converts them to the host device's rate, follows the guest's clock - (except into an `[audio] file`, which is converted at the fixed ratio), - prebuffers `[audio] prebuf_ms` and follows the host's default output - device. `[audio] host` picks the host audio system. + (except into a `file:` backend, which is converted at the fixed ratio), + prebuffers `prebuf_ms` and follows the host's default output + device. The `audio` entry's `backend` picks the host audio system. - Mono is duplicated to L/R. Stereo consumes interleaved pairs. Single-stream quad consumes all four samples but discards the rear pair. - Codec B is an input DMA silence writer, not a second host output stream. diff --git a/docs/fuel-ip34.md b/docs/fuel-ip34.md index 8b4a50e70..0aab0c8c0 100644 --- a/docs/fuel-ip34.md +++ b/docs/fuel-ip34.md @@ -32,7 +32,7 @@ the DMediaPro DM8's converters, the same model as the [Tezro's](tezro-ip53.md). It takes the first free PCI slot (device 1 of head E) unless `at` names another, such as device 2 of head F beside the base I/O; which device a real Fuel's option slots are is not established, so the slot is the model's choice. IRIX 6.5.30 lists it as `Iris Audio Processor: version MAD -revision 1` and plays through it. It plays to the host as `[audio]` sets, or +revision 1` and plays through it. It plays to the host as the `audio` entry at `CARD/audio` sets, or silently with `no_audio`. `prom` overrides the built-in PROM; a file it names must load, and diff --git a/docs/origin3200-ip35.md b/docs/origin3200-ip35.md index fe7ee3423..c8a0a08f0 100644 --- a/docs/origin3200-ip35.md +++ b/docs/origin3200-ip35.md @@ -50,7 +50,7 @@ Ensemble ICE1724 with the DMediaPro DM8's converters, the same model as the devices the I-brick's option slots are is not established. On an Onyx 3000, IRIX 6.5.30 lists it as `Iris Audio Processor: version MAD revision 1` and plays through it; it has not been run in an Origin 3200 guest. It plays to the -host as `[audio]` sets, or silently with `no_audio`. +host as the `audio` entry at `CARD/audio` sets, or silently with `no_audio`. ## Nodes and the link diff --git a/docs/tezro-ip53.md b/docs/tezro-ip53.md index 65f53a13a..43adb043e 100644 --- a/docs/tezro-ip53.md +++ b/docs/tezro-ip53.md @@ -98,8 +98,8 @@ recipe. That is a stated model choice, not Tezro evidence. Its two I/O BARs need the bridge's I/O window, which firmware opens. The controller's interrupt is masked at reset; its INTA is rotated by the bridge to INTC of the bridge's slot, which the PIC wires to input 1 (a model choice; the board's -wiring is unknown). It plays to the host stream as `[audio]` sets, or silently -with `no_audio`; `[audio] channels` (2, 4, 6 or 8, default 2) is the number of +wiring is unknown). It plays to the host stream as the `audio` entry at `CARD/audio` sets, or silently +with `no_audio`; its `channels` (2, 4, 6 or 8, default 2) is the number of host speakers it folds its channels down to. Memory comes from `banks`: one 512 or 1024 MiB bank per locational bank, from diff --git a/fuel.toml.example b/fuel.toml.example index 291fda077..92779a58f 100644 --- a/fuel.toml.example +++ b/fuel.toml.example @@ -62,6 +62,6 @@ path = "ignore/fuel/irix.raw" overlay = true # Optional: the ICE1724 audio card in a PCI slot (`iris --list-slots` shows them). It plays as -# [audio] sets; unset no_audio for sound. +# its `audio` entry at CARD/audio sets; unset no_audio for sound. # [[devices]] # type = "ice1724" diff --git a/iris-gui/core/src/model/machines.rs b/iris-gui/core/src/model/machines.rs index 091b81d91..4ab687b0d 100644 --- a/iris-gui/core/src/model/machines.rs +++ b/iris-gui/core/src/model/machines.rs @@ -120,11 +120,6 @@ pub fn visit_paths(cfg: &mut MachineConfig, mut visit: impl FnMut(&mut String)) if let Some(path) = path { visit(path); } } visit(&mut cfg.virtio_9p.path); - if let Some(file) = &mut cfg.audio.file { - let mut path = file.to_string_lossy().into_owned(); - visit(&mut path); - *file = path.into(); - } for port in &mut cfg.virtio_serial.ports { if let Some(path) = &mut port.socket { visit(path); } } @@ -165,6 +160,13 @@ pub fn visit_paths(cfg: &mut MachineConfig, mut visit: impl FnMut(&mut String)) } DeviceModel::VirtioSerial(v) => v.ports.iter_mut().filter_map(|p| p.socket.as_mut()).for_each(&mut visit), DeviceModel::Board(b) => b.flash.iter_mut().for_each(&mut visit), + DeviceModel::Audio(a) => { + if let Some(path) = a.backend.strip_prefix("file:") { + let mut path = path.to_string(); + visit(&mut path); + a.backend = format!("file:{path}"); + } + } DeviceModel::Net(_) | DeviceModel::Camera(_) | DeviceModel::XioBoard(_) | DeviceModel::PciBridge | DeviceModel::Ice1724 | DeviceModel::Qla2200 | DeviceModel::Ultra64 | DeviceModel::Empty => {} } } @@ -634,15 +636,32 @@ pub(crate) mod tests { let dir = directory(&root.0, "octane").unwrap(); let mut cfg = MachineConfig::default(); cfg.virtio_9p.path = dir.join("share").to_string_lossy().into_owned(); - cfg.audio.file = Some(dir.join("out.wav")); + cfg.set_audio(iris::config::AudioConfig { file: Some(dir.join("out.wav")), ..Default::default() }); cfg.vnc.password_file = Some(dir.join("vnc.pass").to_string_lossy().into_owned()); save(&root.0, "octane", &mut cfg).unwrap(); let back = read(&config_path(&root.0, "octane").unwrap()).unwrap(); assert_eq!(back.virtio_9p.path, "share"); - assert_eq!(back.audio.file.as_deref(), Some(Path::new("out.wav"))); + assert_eq!(back.audio().file.as_deref(), Some(Path::new("out.wav"))); assert_eq!(back.vnc.password_file.as_deref(), Some("vnc.pass")); } + /// What an older iris-gui saved in every machine (`[vino]`, `[network] mode` and `[audio]` at their defaults) still loads, says + /// nothing, and is saved in the new form; set values become the entries at the ports. + #[test] + fn a_config_saved_by_the_older_gui_still_loads() { + let saved = "[vino]\nsource = \"off\"\nstandard = \"ntsc\"\ncamera_index = 0\n[network]\nmode = \"nat\"\n[audio]\nhost = \"default\"\nprebuf_ms = 20\n"; + let cfg = parse(saved).unwrap(); + assert!(cfg.devices.iter().all(|d| !matches!(d.device, DeviceModel::Net(_) | DeviceModel::Camera(_) | DeviceModel::Audio(_)))); + let text = cfg.to_toml(iris::config::Dump::Full).unwrap(); + assert!(!text.contains("[vino]") && !text.contains("[audio]") && !text.contains("mode ="), "{text}"); + + let set = parse(&format!("{saved}\n").replace("\"off\"", "\"camera\"").replace("\"nat\"\n", "\"pcap\"\npcap_interface = \"eth0\"\n").replace("\"default\"", "\"null\"")).unwrap(); + let back = parse(&set.to_toml(iris::config::Dump::Full).unwrap()).unwrap(); + assert_eq!(back.net_end().backend, "pcap:eth0"); + assert_eq!(back.vino().source, iris::config::VinoSource::Camera); + assert_eq!(back.audio().host, iris::config::AudioHost::Null); + } + /// `banks` a config left unset stays unset across a save, so a Tezro /// keeps its own memory; banks the user chose are kept. #[test] diff --git a/iris-gui/src/config_ui.rs b/iris-gui/src/config_ui.rs index 8eb07ca99..954e9a937 100644 --- a/iris-gui/src/config_ui.rs +++ b/iris-gui/src/config_ui.rs @@ -769,7 +769,8 @@ fn show_display(ui: &mut Ui, cfg: &mut MachineConfig, running: bool) { }); ui.end_row(); }); - if !cfg.no_audio { + if let Some(before) = cfg.audio_output().filter(|_| !cfg.no_audio) { + let mut audio = before.clone(); ui.separator(); ui.heading(t!("config-audio")); subtitle(ui, t!("config-audio-subtitle")); @@ -790,43 +791,46 @@ fn show_display(ui: &mut Ui, cfg: &mut MachineConfig, running: bool) { AudioHost::Pulse }; ComboBox::from_id_salt("audio_host") - .selected_text(label(cfg.audio.host)) + .selected_text(label(audio.host)) .show_ui(ui, |ui| { for h in [AudioHost::Default, native, AudioHost::Null] { - ui.selectable_value(&mut cfg.audio.host, h, label(h)); + ui.selectable_value(&mut audio.host, h, label(h)); } }); ui.end_row(); ui.label(t!("config-audio-prebuffer")); - ui.add(DragValue::new(&mut cfg.audio.prebuf_ms).range(5..=200)); + ui.add(DragValue::new(&mut audio.prebuf_ms).range(5..=200)); ui.end_row(); ui.label(t!("config-audio-host-buffer")); - let mut ms = cfg.audio.latency_ms.unwrap_or(0); + let mut ms = audio.latency_ms.unwrap_or(0); if ui.add(DragValue::new(&mut ms).range(0..=200)).changed() { - cfg.audio.latency_ms = if ms == 0 { None } else { Some(ms) }; + audio.latency_ms = if ms == 0 { None } else { Some(ms) }; } ui.end_row(); - // `[audio] channels`: only the Tezro's multichannel card reads it. + // Channels: only the Tezro's multichannel card reads them. if cfg.machine.profile == MachineProfile::TezroIp53 { ui.label(t!("config-audio-channels")) .tip(t!("config-audio-channels-tip")); ComboBox::from_id_salt("audio_channels") - .selected_text(cfg.audio.channels.to_string()) + .selected_text(audio.channels.to_string()) .show_ui(ui, |ui| { for n in [2usize, 4, 6, 8] { - ui.selectable_value(&mut cfg.audio.channels, n, n.to_string()); + ui.selectable_value(&mut audio.channels, n, n.to_string()); } }); ui.end_row(); } - // `[audio] file`: a WAV recording in place of the sound card. + // A WAV recording in place of the sound card. ui.label(t!("config-audio-file")) .tip(t!("config-audio-file-tip")); - let mut file = cfg.audio.file.as_ref().map(|p| p.to_string_lossy().into_owned()); + let mut file = audio.file.as_ref().map(|p| p.to_string_lossy().into_owned()); path_row_opt(ui, "audio_file", &mut file, Pick::SaveFile, &wav_filters()); - cfg.audio.file = file.map(std::path::PathBuf::from); + audio.file = file.map(std::path::PathBuf::from); ui.end_row(); }); + if audio != before { + cfg.set_audio(audio); + } subtitle(ui, t!("config-audio-rate-subtitle")); } } diff --git a/iris.toml b/iris.toml index 2fb0e230f..0c52db459 100644 --- a/iris.toml +++ b/iris.toml @@ -263,14 +263,18 @@ bind = "localhost" #minutes = -4 #seconds = -27 -# Host audio output, for every sound device (HAL2, the O2's, RAD, ICE1724). -#[audio] -#host = "default" # the platform's own: PulseAudio/PipeWire on Linux, WASAPI on Windows, -# # CoreAudio on macOS; or "pulse", "wasapi", "coreaudio", "null" (discard) +# Host audio output of a sound chip (HAL2, the O2's, RAD) or an ICE1724 card, an `audio` device at its +# `audio` port (an ICE1724 card's is CARD/audio). No entry plays to the host; `type = "none"` there +# keeps the chip and discards its sound. +#[[devices]] +#type = "audio" +#at = "audio" +#backend = "default" # the platform's own: PulseAudio/PipeWire on Linux, WASAPI on Windows, +# # CoreAudio on macOS; or "pulse", "wasapi", "coreaudio", "null" (discard), +# # or "file:out.wav" (a 48 kHz 16-bit WAV file instead of a sound card) #prebuf_ms = 20 # sound held before playing: the margin against a late guest, and the latency added #latency_ms = 20 # what the host's device buffers; unset: its low-latency default #channels = 2 # speakers for the Tezro's multichannel card: 2, 4, 6 or 8 -#file = "out.wav" # play into a 48 kHz 16-bit WAV file instead of a sound card # Built-in VNC server. Off unless listen is set (or --vnc is given). #[vnc] diff --git a/irix-install/iris-indigo2-smoke-ci.toml b/irix-install/iris-indigo2-smoke-ci.toml index 345c4f1eb..5f1b5cb93 100644 --- a/irix-install/iris-indigo2-smoke-ci.toml +++ b/irix-install/iris-indigo2-smoke-ci.toml @@ -20,9 +20,6 @@ heads = 1 [perf] thread_affinity = false -[audio] -prebuf_ms = 20 - [scsi.1] path = "irix-install/scsi1.raw" cdrom = false diff --git a/irix-install/iris-smoke-ci.toml b/irix-install/iris-smoke-ci.toml index 0ced8b72f..d6145ecc7 100644 --- a/irix-install/iris-smoke-ci.toml +++ b/irix-install/iris-smoke-ci.toml @@ -13,9 +13,6 @@ profile = "indy_ip24" [perf] thread_affinity = false -[audio] -prebuf_ms = 20 - [scsi.1] path = "irix-install/scsi1.raw" cdrom = false diff --git a/irix-install/iris-windows-384.toml b/irix-install/iris-windows-384.toml index 821759539..5444c264e 100644 --- a/irix-install/iris-windows-384.toml +++ b/irix-install/iris-windows-384.toml @@ -14,7 +14,9 @@ profile = "indy_ip24" [perf] thread_affinity = false -[audio] +[[devices]] +type = "audio" +at = "audio" prebuf_ms = 40 [scsi.1] diff --git a/irix-install/iris-windows-safe.toml b/irix-install/iris-windows-safe.toml index c9527aa5e..7febee137 100644 --- a/irix-install/iris-windows-safe.toml +++ b/irix-install/iris-windows-safe.toml @@ -13,7 +13,9 @@ profile = "indy_ip24" [perf] thread_affinity = false -[audio] +[[devices]] +type = "audio" +at = "audio" prebuf_ms = 40 [scsi.1] diff --git a/irix-install/iris-windows.toml b/irix-install/iris-windows.toml index 54339203a..34c396319 100644 --- a/irix-install/iris-windows.toml +++ b/irix-install/iris-windows.toml @@ -30,7 +30,9 @@ thread_affinity = false # ci_socket = "127.0.0.1:19851" # headless = true -[audio] +[[devices]] +type = "audio" +at = "audio" # Match IRIX BRES master (44100 Hz). Bump prebuf if you hear tail scratch on Windows. prebuf_ms = 40 # latency_ms = 20 diff --git a/origin3200.toml.example b/origin3200.toml.example index eb45059d8..03c606c3b 100644 --- a/origin3200.toml.example +++ b/origin3200.toml.example @@ -42,7 +42,7 @@ path = "ignore/origin3200/system.raw" overlay = true # Optional: the ICE1724 audio card in an I-brick PCI slot (bus1-slot2, bus1-slot3, bus2-slot1 or -# bus2-slot2). It plays as [audio] sets; unset no_audio for sound. +# bus2-slot2). It plays as its `audio` entry at CARD/audio sets; unset no_audio for sound. # [[devices]] # type = "ice1724" # at = "bus1-slot2" diff --git a/src/chime_tests.rs b/src/chime_tests.rs index 2144db5e3..1ab83b207 100644 --- a/src/chime_tests.rs +++ b/src/chime_tests.rs @@ -2,7 +2,7 @@ //! A chime is reduced to one `level:note` entry per 100 ms of sound and //! compared with a table recorded from our own run of each machine. -use crate::config::{AudioHost, GraphicsBoard, MachineConfig, MachineProfile}; +use crate::config::{AudioConfig, AudioHost, GraphicsBoard, MachineConfig, MachineProfile}; use crate::dev::audio_dump::tests::{dump, TAP}; use std::time::{Duration, Instant}; @@ -21,7 +21,7 @@ fn boot(profile: MachineProfile, cpu: &str, quiet: usize, edit: fn(&mut MachineC cfg.machine.profile = profile; cfg.machine.cpu = Some(cpu); cfg.no_audio = false; - cfg.audio.host = AudioHost::Null; + cfg.set_audio(AudioConfig { host: AudioHost::Null, ..Default::default() }); crate::test_temp::nvram_in(&mut cfg, &dir); let held = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); cfg.monitor_port = Some(held.local_addr().unwrap().port()); diff --git a/src/config.rs b/src/config.rs index 6d32b964f..be4454173 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,4 +1,4 @@ -use clap::{CommandFactory, FromArgMatches, Parser}; +use clap::{CommandFactory, FromArgMatches, Parser, ValueEnum}; use serde::{Deserialize, Serialize}; use std::net::Ipv4Addr; @@ -2098,8 +2098,8 @@ pub enum AudioHost { Null, } -/// Host audio output, for every sound device. -#[derive(Debug, Clone, Serialize, Deserialize)] +/// Host audio output of one sound device. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct AudioConfig { /// Host audio system to play through. Default: the platform's usual one. #[serde(default)] @@ -2123,6 +2123,56 @@ pub struct AudioConfig { pub file: Option, } +/// An `audio` entry: the host output of a sound chip. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct AudioDevice { + /// A host audio system (`default`, `pulse`, `wasapi`, `coreaudio` or `null`), or `file:PATH`: a 48 kHz 16-bit WAV file. + #[serde(default = "default_audio_backend")] + pub backend: String, + #[serde(default = "default_audio_prebuf_ms")] + pub prebuf_ms: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub latency_ms: Option, + #[serde(default = "default_audio_channels")] + pub channels: usize, +} + +fn default_audio_backend() -> String { "default".into() } + +impl Default for AudioDevice { + fn default() -> Self { AudioConfig::default().into() } +} + +impl From for AudioDevice { + fn from(a: AudioConfig) -> Self { + let backend = a.file.map_or_else(|| a.host.to_possible_value().map_or_else(default_audio_backend, |v| v.get_name().into()), |f| format!("file:{}", f.display())); + AudioDevice { backend, prebuf_ms: a.prebuf_ms, latency_ms: a.latency_ms, channels: a.channels } + } +} + +impl AudioDevice { + pub fn config(&self) -> Result { + let (host, file) = match self.backend.split_once(':') { + Some(("file", path)) if !path.is_empty() => (AudioHost::Default, Some(path.into())), + Some(_) => return Err(format!("backend \"{}\" is not a host audio system or file:PATH", self.backend)), + None => (AudioHost::from_str(&self.backend, true).map_err(|_| format!("backend \"{}\" is not default, pulse, wasapi, coreaudio, null or file:PATH", self.backend))?, None), + }; + Ok(AudioConfig { host, file, prebuf_ms: self.prebuf_ms, latency_ms: self.latency_ms, channels: self.channels }) + } +} + +impl AudioConfig { + /// What the entry at a sound port asks for: no entry plays to the host, `none` keeps the chip and discards its sound. + pub fn at_port(entry: Option<&DeviceModel>) -> AudioConfig { + match entry { + Some(DeviceModel::Audio(a)) => a.config().expect("audio backend: validate() should have caught this"), + Some(DeviceModel::Empty) => AudioConfig { host: AudioHost::Null, ..Default::default() }, + _ => AudioConfig::default(), + } + } +} + fn default_audio_prebuf_ms() -> u64 { 20 } fn default_audio_channels() -> usize { 2 } fn is_default_audio_channels(n: &usize) -> bool { *n == 2 } @@ -2507,6 +2557,9 @@ pub struct MachineConfig { /// The older `[vino]` table, until `legacy` turns it into a `camera` entry. #[serde(default, rename = "vino", skip_serializing)] pub legacy_vino: Option, + /// The older `[audio]` table, until `legacy` turns it into an `audio` entry. + #[serde(default, rename = "audio", skip_serializing)] + pub legacy_audio: Option, /// `--scsiN` and `--cdromN`, until `legacy` merges them into the devices. #[serde(skip)] pub legacy_shorthands: Vec, @@ -2553,10 +2606,6 @@ pub struct MachineConfig { #[serde(default = "default_scsi_deferred_int")] pub scsi_deferred_int: bool, - /// Host audio output tuning (`[audio]` section). - #[serde(default)] - pub audio: AudioConfig, - /// Machine platform profile (`[machine]` section). #[serde(default)] pub machine: MachineSection, @@ -2776,6 +2825,7 @@ impl Default for MachineConfig { devices: default_disks(), legacy_scsi: None, legacy_vino: None, + legacy_audio: None, legacy_shorthands: Vec::new(), machine_id: 0, old_keys: Vec::new(), @@ -2815,7 +2865,6 @@ impl Default for MachineConfig { renderer: UiRenderer::default(), vsync: false, scsi_deferred_int: default_scsi_deferred_int(), - audio: AudioConfig::default(), machine: MachineSection::default(), graphics: GraphicsSection::default(), debug: DebugConfig::default(), @@ -3459,6 +3508,7 @@ impl MachineConfig { DeviceModel::VirtioSerial(v) => v.check()?, DeviceModel::Virtio9p(v) => v.check()?, DeviceModel::Net(n) => n.check().map_err(|e| format!("[[devices]] net: {e}"))?, + DeviceModel::Audio(a) => drop(a.config().map_err(|e| format!("[[devices]] audio: {e}"))?), _ => {} } } @@ -3779,6 +3829,36 @@ impl MachineConfig { self.set_port_device("video", Some(DeviceModel::Camera(CameraDevice { backend, standard: vino.standard, ..Default::default() }))); } + /// The sound port the machine's host output is set at: its sound chip's `audio`, else its first ICE1724 card's. + fn audio_port(&self) -> Option { + Self::audio_port_in(&DevicePlacement::lenient(self, &self.devices)) + } + + fn audio_port_in(p: &DevicePlacement) -> Option { + let card = || p.placed().find(|(d, _)| matches!(d.device, DeviceModel::Ice1724)).map(|(_, at)| format!("{at}/audio")); + p.slots.iter().any(|s| s.aliases.iter().any(|a| a == "audio")).then(|| "audio".into()).or_else(card) + } + + /// The host output the entry at the machine's sound port asks for; none where the machine has no sound port. + pub fn audio_output(&self) -> Option { + let p = DevicePlacement::lenient(self, &self.devices); + let at = Self::audio_port_in(&p)?; + Some(AudioConfig::at_port(p.port(&at).filter(|(_, d)| !d.default).map(|(_, d)| &d.device))) + } + + /// [`Self::audio_output`], the default where there is no sound port. + pub fn audio(&self) -> AudioConfig { + self.audio_output().unwrap_or_default() + } + + /// Put `audio` on the machine's sound port; the default is an entry that says nothing. + pub fn set_audio(&mut self, audio: AudioConfig) { + let audio = AudioDevice::from(audio); + if let Some(at) = self.audio_port() { + self.set_port_device(&at, (audio != AudioDevice::default()).then_some(DeviceModel::Audio(audio))); + } + } + /// The `net` entry at the Ethernet port: the one a file places there, else the default. pub fn net_end(&self) -> NetDevice { match self.port_device("ethernet") { @@ -3943,10 +4023,6 @@ pub struct Cli { #[arg(long = "noaudio", default_value_t = false)] pub no_audio: bool, - /// Host audio system: default, pulse, wasapi, coreaudio or null (overrides `[audio] host`) - #[arg(long = "audio-host", value_enum, value_name = "HOST")] - pub audio_host: Option, - /// Enable NFS share: path to the directory to export (enables NFS) #[arg(long = "nfs-dir", value_name = "DIR")] pub nfs_dir: Option, @@ -4043,11 +4119,13 @@ pub struct Cli { #[arg(long = "serial-log-b", value_name = "FILE", hide = true)] pub serial_log_b: Option, - /// The older network options, which become the `net` entry at the Ethernet port (see `legacy`). + /// The older network and audio options, which become the `net` entry at the Ethernet port (see `legacy`). #[arg(long = "net-mode", value_name = "MODE", hide = true)] pub net_mode: Option, #[arg(long = "pcap-interface", value_name = "IFACE", hide = true)] pub pcap_interface: Option, + #[arg(long = "audio-host", value_enum, value_name = "HOST", hide = true)] + pub audio_host: Option, /// Physical host keyboard: `ansi` (default), `iso` or `jis`. Use `jis` /// for a Japanese keyboard with the PROM's `keybd` set to JP. @@ -4202,6 +4280,7 @@ impl Cli { } // A flag beats the file, whether the file wrote an older key or an entry at the port. legacy::net_flags(&mut cfg, self.net_mode, self.pcap_interface.as_deref()); + legacy::audio_flag(&mut cfg, self.audio_host); if self.no_write_cache { for dev in cfg.devices.iter_mut().filter_map(|d| d.device.scsi_mut()).filter(|d| d.kind() == ScsiKind::Disk) { @@ -4219,7 +4298,6 @@ impl Cli { if self.scale2x { cfg.scale = 2; } if self.headless { cfg.headless = true; } if self.no_audio { cfg.no_audio = true; } - if let Some(h) = self.audio_host { cfg.audio.host = h; } if self.no_scsi_deferred_int { cfg.scsi_deferred_int = false; } if self.ci { cfg.ci = true; } @@ -4550,29 +4628,6 @@ mod export_tests { assert_eq!(cfg.graphics_board(), Some(GraphicsBoard::Ir3)); } - #[test] - fn audio_host_parses_and_defaults() { - let cfg: MachineConfig = toml::from_str("").expect("parse"); - assert_eq!(cfg.audio.host, AudioHost::Default); - let cfg: MachineConfig = toml::from_str(r#" - [audio] - host = "pulseaudio" - latency_ms = 15 - cpal_buffer_frames = 256 - "#).expect("an older configuration still parses"); - assert_eq!(cfg.audio.host, AudioHost::Pulse); - assert_eq!(cfg.audio.latency_ms, Some(15)); - assert_eq!(cfg.audio.channels, 2); - let old: MachineConfig = toml::from_str("[audio]\nhost = \"alsa\"").expect("parse"); - assert_eq!(old.audio.host, AudioHost::Default); - let back: MachineConfig = toml::from_str(&toml::to_string_pretty(&cfg).expect("serialize")).expect("deserialize"); - assert_eq!(back.audio.host, AudioHost::Pulse); - assert!(toml::from_str::("[audio]\nhost = \"oss\"").is_err()); - assert_eq!(cfg.audio.file, None); - let cfg: MachineConfig = toml::from_str("[audio]\nfile = \"out.wav\"").expect("parse"); - assert_eq!(cfg.audio.file.as_deref(), Some(std::path::Path::new("out.wav"))); - } - #[test] fn write_cache_defaults_on_and_round_trips() { let cfg = MachineConfig::from_toml_str(r#" @@ -5387,6 +5442,32 @@ mod export_tests { assert!(MachineConfig::from_toml_str("[[devices]]\ntype = \"camera\"\nbackend = \"webcam:x\"\n").is_err()); } + /// A sound chip's host output is an `audio` entry at its `audio` port; an ICE1724 card brings a port of its own. + #[test] + fn a_sound_chips_host_output_is_an_audio_entry_at_its_port() { + let text = "[[devices]]\ntype = \"audio\"\nat = \"audio\"\nbackend = \"file:out.wav\"\nchannels = 4\nlatency_ms = 15\n"; + for profile in ["indy_ip24", "indigo2_ip22", "o2_ip32", "octane_ip30", "onyx2_ip27"] { + let cfg = MachineConfig::from_toml_str(&format!("[machine]\nprofile = \"{profile}\"\n{text}")).unwrap(); + let a = cfg.audio(); + assert_eq!((a.file.as_deref(), a.channels, a.latency_ms), (Some(std::path::Path::new("out.wav")), 4, Some(15)), "{profile}"); + } + assert!(MachineConfig::from_toml_str(&format!("[machine]\nprofile = \"fuel_ip34\"\n{text}")).unwrap().resolved().unwrap_err().contains("has no slot audio")); + let host = |b: &str| MachineConfig::from_toml_str(&format!("[[devices]]\ntype = \"audio\"\nbackend = \"{b}\"\n")).map(|c| c.audio().host); + assert_eq!(host("pulseaudio").unwrap(), AudioHost::Pulse); + assert!(host("oss").is_err() && host("tcp:1").is_err()); + let mut cfg = MachineConfig::default(); + assert_eq!(cfg.audio().host, AudioHost::Default); + cfg.set_audio(AudioConfig { host: AudioHost::Pulse, ..Default::default() }); + assert_eq!(MachineConfig::from_toml_str(&toml::to_string_pretty(&cfg).unwrap()).unwrap().audio().host, AudioHost::Pulse); + cfg.set_audio(AudioConfig::default()); + assert!(!toml::to_string_pretty(&cfg).unwrap().contains("\"audio\""), "the default says nothing"); + let none = MachineConfig::from_toml_str("[[devices]]\ntype = \"none\"\nat = \"audio\"\n").unwrap(); + assert_eq!(none.audio().host, AudioHost::Null, "an empty port keeps the chip and drops its sound"); + let card = "[machine]\nprofile = \"tezro_ip53\"\n[[devices]]\ntype = \"ice1724\"\nname = \"snd\"\nat = \"xio15/pci0/2/pci0/2\"\n"; + let card = MachineConfig::from_toml_str(&format!("{card}[[devices]]\ntype = \"audio\"\nat = \"snd/audio\"\nbackend = \"null\"\n")).unwrap(); + assert_eq!(card.audio().host, AudioHost::Null, "the card's own port takes an audio entry: {:?}", card.clone().resolved().err()); + } + /// Every old `[o2]` key lands on the shared key it stood for, and the /// section keeps only what is the O2's alone. #[test] diff --git a/src/config/legacy.rs b/src/config/legacy.rs index e7274beb4..5bad0ba50 100644 --- a/src/config/legacy.rs +++ b/src/config/legacy.rs @@ -117,6 +117,7 @@ pub(super) const OLD_KEYS: &[OldKey] = &[ group(&["graphics.board", "impact.gfx", "graphics.heads", "graphics.resolution", "graphics.flash"], When::Chosen, graphics), group(&["network.mode", "network.pcap_interface", "network.stream", "network.mac"], When::Chosen, network), fold("vino", When::Chosen, vino), + fold("audio", When::Chosen, audio), fold("o2.net", When::Chosen, o2_net), fold("octane.graphics", When::Load, |c| match c.octane.graphics.take() { Some(old) => Err(format!("octane.graphics has moved: write the board as a [[devices]] entry (was \"{}\")", old.trim())), @@ -417,6 +418,34 @@ fn vino(cfg: &mut MachineConfig) -> Result { Ok(true) } +/// The older `[audio]` table as the `audio` entry at the sound port. What iris-gui saved as defaults says nothing; a table +/// where the machine has no sound port is dropped, and one beside an entry there is refused. +fn audio(cfg: &mut MachineConfig) -> Result { + let Some(audio) = cfg.legacy_audio.take() else { return Ok(false) }; + if audio == AudioConfig::default() { + return Ok(false); + } + let Some(at) = cfg.audio_port() else { + eprintln!("iris: [audio] is ignored: this machine has no sound port"); + return Ok(false); + }; + if cfg.port_device(&at).is_some() { + return Err("[audio] and the entry at the sound port both set the host output; keep one".into()); + } + cfg.set_audio(audio); + Ok(true) +} + +/// `--audio-host` sets the sound port's host over whatever the file set there. +pub(super) fn audio_flag(cfg: &mut MachineConfig, host: Option) { + if let Some(host) = host.filter(|_| cfg.audio_port().is_some()) { + cfg.set_audio(AudioConfig { host, ..cfg.audio() }); + if !cfg.old_keys.contains(&"--audio-host") { + cfg.old_keys.push("--audio-host"); + } + } +} + /// A bare drive id (`16 * controller + id`), the only way older versions /// named a drive to load or eject. pub(crate) fn drive_number(spec: &str) -> Option { @@ -924,6 +953,24 @@ mod tests { assert!(e.contains("keep one"), "{e}"); } + #[test] + fn the_older_audio_table_and_flag_make_the_audio_entry() { + let old = MachineConfig::from_toml_str("[audio]\nhost = \"pulse\"\nlatency_ms = 15\n").unwrap(); + assert_eq!((old.audio().host, old.audio().latency_ms), (AudioHost::Pulse, Some(15))); + assert_eq!(old.old_keys, ["audio"]); + assert!(!toml::to_string_pretty(&old.for_writing()).unwrap().contains("[audio]"), "saved in the new form"); + let default = MachineConfig::from_toml_str("[audio]\nhost = \"default\"\nprebuf_ms = 20\n").unwrap(); + assert!(default.devices.iter().all(|d| d.device.spec().name != "audio"), "the default says nothing"); + let cli = Cli::parse_from(["iris", "--audio-host", "null"]); + assert_eq!(cli.apply(MachineConfig::default()).audio().host, AudioHost::Null); + let entry = "[[devices]]\ntype = \"audio\"\nat = \"audio\"\nbackend = \"pulse\"\n"; + let file = MachineConfig::from_toml_str(entry).unwrap(); + assert_eq!(Cli::parse_from(["iris", "--audio-host", "null"]).apply(file).audio().host, AudioHost::Null); + let e = MachineConfig::from_toml_str(&format!("[audio]\nhost = \"null\"\n{entry}")).unwrap_err().to_string(); + assert!(e.contains("keep one"), "{e}"); + assert!(MachineConfig::from_toml_str(&format!("[audio]\nhost = \"default\"\n{entry}")).unwrap().old_keys.is_empty()); + } + #[test] fn the_older_network_keys_and_flags_make_the_net_entry() { let text = "[network]\nmode = \"pcap\"\npcap_interface = \"eth0\"\nmac = \"08:00:69:aa:bb:cc\"\n"; diff --git a/src/config/write.rs b/src/config/write.rs index 648fc8025..83cf6c806 100644 --- a/src/config/write.rs +++ b/src/config/write.rs @@ -186,7 +186,7 @@ path = "/dev/ttyUSB0" let cfg = load("[machine]\nprofile = \"indy_ip24\"\n"); let text = cfg.to_toml(Dump::Full).unwrap(); let table: toml::Table = toml::from_str(&text).unwrap(); - assert!(text.contains("[audio]") && text.contains("path = \"scsi1.raw\"") && !text.contains("banks") && table["jitv2"].get("threads").is_none(), "{text}"); + assert!(text.contains("[network]") && text.contains("path = \"scsi1.raw\"") && !text.contains("banks") && table["jitv2"].get("threads").is_none(), "{text}"); assert_eq!(load(&text).to_toml(Dump::Full).unwrap(), text); } } diff --git a/src/dev/hal2.rs b/src/dev/hal2.rs index cd5832a7f..27101ef55 100644 --- a/src/dev/hal2.rs +++ b/src/dev/hal2.rs @@ -378,7 +378,7 @@ pub struct Hal2 { ar_state: Arc>, /// Each engine's pacing timer while armed. timers: Mutex<[Option; 4]>, - // [audio]: which host to play through, and its buffer size. + // the `audio` entry: which host to play through, and its buffer size. audio: AudioConfig, /// What codec A moved and skipped (`audio status`); codec B is not counted. meter: Arc, @@ -397,7 +397,7 @@ impl Hal2 { Self::with_audio(tm, dma_clients, AudioConfig::default()) } - /// HAL2 playing through the host and buffer `[audio]` asks for. + /// HAL2 playing through the host and buffer the `audio` entry asks for. pub fn with_audio(tm: &Arc, dma_clients: Vec>, audio: AudioConfig) -> Self { Self { state: Arc::new(Mutex::new(Hal2State { diff --git a/src/dev/hpc3.rs b/src/dev/hpc3.rs index 360231ba1..c7c0102ad 100644 --- a/src/dev/hpc3.rs +++ b/src/dev/hpc3.rs @@ -1288,6 +1288,7 @@ impl Hpc3 { pub fn slots(s: &mut Vec, guinness: bool) { crate::topology::fixed_slot(s, "hpc3", "hpc3", &[]); crate::topology::open_slot(s, "hpc3/ethernet", &[crate::topology::DeviceFamily::Net], &["ethernet"]); + crate::topology::open_slot(s, "hpc3/audio", &[crate::topology::DeviceFamily::Audio], &["audio"]); for c in 0..Self::scsi_channels(guinness) { crate::topology::scsi_bus_slots(s, &Self::scsi_at(c).to_string(), "wd33c93a", 7); } diff --git a/src/dev/ice1724.rs b/src/dev/ice1724.rs index 8ea5ac124..dedb2f244 100644 --- a/src/dev/ice1724.rs +++ b/src/dev/ice1724.rs @@ -118,7 +118,7 @@ //! * `dropped_frames` counts frames played into a host ring left with no //! room. //! * The interleaved engine's slots, and the S/PDIF engine, play through one -//! host stream as wide as `[audio] channels` asks (8, 6, 4 or 2, the +//! host stream as wide as the `audio` entry's `channels` asks (8, 6, 4 or 2, the //! default; any other value is taken as 2). Which speaker a slot drives is //! not established; the //! model takes the usual host orders: 2 slots front left and right; 4 @@ -734,7 +734,7 @@ pub struct Inner { clock: CardClock, /// Brings the engines up to date; counts machine time. timer: Timer, - /// `[audio]` settings once host output is enabled. + /// `audio` entry's settings once host output is enabled. audio_cfg: Mutex>, sink: Mutex>, /// The frames the engines skipped; what they moved is `State::stats`. @@ -912,7 +912,7 @@ impl Inner { // ---- host audio ---- /// Open the host stream, once, when output is enabled. It is as wide as - /// `[audio] channels` asks; the card folds its slots down to that. + /// the `audio` entry's `channels` asks; the card folds its slots down to that. fn open_sink(&self) { let Some(cfg) = self.audio_cfg.lock().clone() else { return }; // Read before the sink lock: engines take the state lock, then the diff --git a/src/dev/mace_audio.rs b/src/dev/mace_audio.rs index da979ffcc..e9f50937c 100644 --- a/src/dev/mace_audio.rs +++ b/src/dev/mace_audio.rs @@ -1129,7 +1129,7 @@ mod tests { /// service pass hands them over, in real time: a 440 Hz tone on the /// left from the first at 48 kHz and an 880 Hz tone on the right from /// the second at 22.05 kHz. They are one stream on the host, so the - /// `[audio] file` holds both, each at its own pitch on its own side. + /// `file:` audio backend holds both, each at its own pitch on its own side. #[test] fn both_outputs_play_at_their_own_rates_into_one_stream() { use crate::host_audio::test_signal::*; diff --git a/src/dev/rad1.rs b/src/dev/rad1.rs index e090896f5..0f09f5364 100644 --- a/src/dev/rad1.rs +++ b/src/dev/rad1.rs @@ -643,7 +643,7 @@ pub struct Inner { status: Timer, /// The next output pump tick, in machine nanoseconds. pump: Timer, - /// `[audio]` settings once host output is enabled; `None` (tests, + /// The `audio` settings once host output is enabled; `None` (tests, /// `no_audio`) keeps the output channel running silently. audio_cfg: Mutex>, sink: Mutex>, diff --git a/src/dev/serial_dev/midi.rs b/src/dev/serial_dev/midi.rs index 322368098..9006134e4 100644 --- a/src/dev/serial_dev/midi.rs +++ b/src/dev/serial_dev/midi.rs @@ -165,8 +165,8 @@ pub struct MidiSynth { impl MidiSynth { /// Load `soundfont` and start playing, at `gain` times rustysynth's own /// level, into a host stream that `audio` describes; with `mute` (the - /// machine's `no_audio`) the synth parses and renders nothing. When the - /// machine's audio goes to a file, the synth's goes to one beside it + /// machine's `no_audio`) the synth parses and renders nothing. When `audio` + /// goes to a file, the synth's goes to one beside it /// (`out.wav` → `out-midi.wav`): each stream writes a file of its own. pub fn open(soundfont: &str, gain: f32, audio: &crate::config::AudioConfig, mute: bool) -> Result { let font = { diff --git a/src/dev/serial_dev/mod.rs b/src/dev/serial_dev/mod.rs index bfebc987b..71eae35a8 100644 --- a/src/dev/serial_dev/mod.rs +++ b/src/dev/serial_dev/mod.rs @@ -60,6 +60,7 @@ pub struct SerialDeviceConfig { #[serde(default)] pub path: String, /// `serial`: the host ends, one string or a list: `tcp:PORT`, `unix:PATH` or `log:PATH`. None leaves the port unplugged. + /// `midi_synth`: the host audio it plays to, as an `audio` entry's `backend`; none is the host's default. #[serde(default, deserialize_with = "crate::backend::list", skip_serializing_if = "Vec::is_empty")] pub backend: Vec, /// `midi_synth`: how loud it plays, times the synth's own level (1.0), @@ -91,6 +92,15 @@ impl SerialDeviceConfig { self.backend.extend(port.map(|p| format!("tcp:{p}"))); } + /// The host output a `midi_synth` plays to. + pub fn synth_output(&self) -> Result { + match self.backend.as_slice() { + [] => Ok(Default::default()), + [b] => crate::config::AudioDevice { backend: b.clone(), ..Default::default() }.config(), + _ => Err("midi_synth takes one backend".into()), + } + } + pub fn check(&self) -> Result<(), String> { let needs = match self.kind { SerialKind::Line => return ends(&self.backend).map(drop), @@ -104,6 +114,9 @@ impl SerialDeviceConfig { if self.gain.is_some_and(|g| !(0.0..=16.0).contains(&g)) { return Err("gain is from 0 to 16".into()); } + if self.kind == SerialKind::MidiSynth { + self.synth_output()?; + } Ok(()) } } @@ -221,7 +234,7 @@ fn open(n: u8, d: &SerialDeviceConfig, cfg: &MachineConfig) -> Result midi::MidiSynth::open(path, d.gain.unwrap_or(1.0), &cfg.audio, cfg.no_audio) + SerialKind::MidiSynth => d.synth_output().and_then(|out| midi::MidiSynth::open(path, d.gain.unwrap_or(1.0), &out, cfg.no_audio)) .map(|m| { log::info!("serial{n}: midi_synth plays on the SoundFont synth, {path}"); Arc::new(m) as Arc @@ -303,6 +316,18 @@ mod tests { assert!(cfg(indy, &synth.replace("2.0", "20.0")).unwrap_err().contains("gain")); let raw_gain = "[[devices]]\ntype = \"midi_raw\"\nat = \"serial2\"\npath = \"/dev/midi3\"\ngain = 2.0\n"; assert!(cfg(indy, raw_gain).unwrap_err().contains("no key gain")); + let out = |b: &str| cfg(indy, &format!("{synth}backend = {b}\n")).map(|c| placed(&c)[0].1.synth_output()); + assert_eq!(out("\"null\"").unwrap().unwrap().host, crate::config::AudioHost::Null); + assert_eq!(out("\"file:m.wav\"").unwrap().unwrap().file.as_deref(), Some(std::path::Path::new("m.wav"))); + assert!(out("\"tape\"").unwrap_err().contains("backend")); + assert!(out("[\"null\", \"default\"]").unwrap_err().contains("one backend")); + } + + /// `none` at a port unplugs it: the default listener goes, and the other port keeps its own. + #[test] + fn none_at_a_port_unplugs_it() { + let c = cfg(MachineProfile::IndyIp24, "[[devices]]\ntype = \"none\"\nat = \"serial2\"\n").unwrap(); + assert_eq!(placed(&c).iter().map(|(n, ..)| *n).collect::>(), [1]); } /// A port with no entry listens on its default TCP port, which an entry for the port replaces. The Indy's console, diff --git a/src/devices.rs b/src/devices.rs index 470d98eb8..215ac5b23 100644 --- a/src/devices.rs +++ b/src/devices.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::sync::Arc; use crate::dev::serial_dev::{SerialDeviceConfig, SerialKind}; -use crate::config::{CameraDevice, GraphicsBoard, MachineConfig, NetDevice, NvmeConfig, ScsiDeviceConfig, ScsiKind, Virtio9pConfig, VirtioSerialConfig}; +use crate::config::{AudioConfig, AudioDevice, CameraDevice, GraphicsBoard, MachineConfig, NetDevice, NvmeConfig, ScsiDeviceConfig, ScsiKind, Virtio9pConfig, VirtioSerialConfig}; use crate::dev::ng1::vc2_timings::NewportResolution; use crate::dev::ice1724::{Ice1724, Variant}; use crate::dev::isp2200::{card::Loop, Isp2200}; @@ -17,7 +17,7 @@ use crate::dev::xio_pci::{Kind, CAGE_SLOTS, SHOEHORN_SLOTS}; use crate::slot_path::MachineSlotPath; use crate::dev::virtio::pci::VirtioPci; use crate::pci::{DevFn, PciToPciBridge, PCI_INTA}; -use crate::topology::{loop_slots, pci_bus_slots, DeviceFamily, DevicePlacement, MachineSlot, MachineSlotKind}; +use crate::topology::{loop_slots, open_slot, pci_bus_slots, DeviceFamily, DevicePlacement, MachineSlot, MachineSlotKind}; /// What a device is, with its options. A family step adds a variant here and /// its rows to [`DEVICE_TYPES`]. @@ -47,6 +47,8 @@ pub enum DeviceModel { Net(NetDevice), /// The picture at a video input. Camera(CameraDevice), + /// The host output of a sound chip. + Audio(AudioDevice), } /// What the test device's run-configuration register publishes and where its @@ -133,7 +135,7 @@ pub const DEVICE_TYPES: &[DeviceTypeSpec] = &[ DeviceTypeSpec { name: "pci_shoehorn", family: DeviceFamily::Xio, keys: &[], parse: |_, _| Ok(DeviceModel::XioBoard(Kind::Shoehorn)), slots: Some(|_, at, s| pci_bus_slots(s, &at.pci(0).to_string(), "PCI shoehorn", SHOEHORN_SLOTS)) }, // One slot behind it, device 0, where iris has always put a card. DeviceTypeSpec { name: "pci_bridge", family: DeviceFamily::Pci, keys: &[], parse: |_, _| Ok(DeviceModel::PciBridge), slots: Some(|_, at, s| pci_bus_slots(s, &at.pci(0).to_string(), "pci bridge", &[(0, MachineSlotKind::PCI_SLOT, None)])) }, - DeviceTypeSpec { name: "ice1724", family: DeviceFamily::Pci, keys: &[], parse: |_, _| Ok(DeviceModel::Ice1724), slots: None }, + DeviceTypeSpec { name: "ice1724", family: DeviceFamily::Pci, keys: &[], parse: |_, _| Ok(DeviceModel::Ice1724), slots: Some(|_, at, s| open_slot(s, &format!("{at}/audio"), &[DeviceFamily::Audio], &[])) }, DeviceTypeSpec { name: "qla2200", family: DeviceFamily::Pci, keys: &[], parse: |_, _| Ok(DeviceModel::Qla2200), slots: Some(|_, at, s| loop_slots(s, at)) }, DeviceTypeSpec { name: "nvme", family: DeviceFamily::Pci, keys: &["path", "overlay", "write_cache"], parse: nvme, slots: None }, DeviceTypeSpec { name: "ultra64", family: DeviceFamily::Gio, keys: &[], parse: |_, _| Ok(DeviceModel::Ultra64), slots: None }, @@ -168,9 +170,10 @@ pub const DEVICE_TYPES: &[DeviceTypeSpec] = &[ }, DeviceTypeSpec { name: "net", family: DeviceFamily::Net, keys: &["backend", "mac"], parse: |_, o| options(o).and_then(|n: NetDevice| n.check().map(|_| DeviceModel::Net(n))), slots: None }, DeviceTypeSpec { name: "camera", family: DeviceFamily::Video, keys: &["backend", "standard"], parse: |_, o| options(o).and_then(|c: CameraDevice| c.end().map(|_| DeviceModel::Camera(c))), slots: None }, + DeviceTypeSpec { name: "audio", family: DeviceFamily::Audio, keys: &["backend", "prebuf_ms", "latency_ms", "channels"], parse: |_, o| options(o).and_then(|a: AudioDevice| a.config().map(|_| DeviceModel::Audio(a))), slots: None }, DeviceTypeSpec { name: "serial", family: DeviceFamily::Serial, keys: &["backend"], parse: serial_device, slots: None }, DeviceTypeSpec { name: "hostserial", family: DeviceFamily::Serial, keys: &["path"], parse: serial_device, slots: None }, - DeviceTypeSpec { name: "midi_synth", family: DeviceFamily::Serial, keys: &["path", "gain"], parse: serial_device, slots: None }, + DeviceTypeSpec { name: "midi_synth", family: DeviceFamily::Serial, keys: &["path", "gain", "backend"], parse: serial_device, slots: None }, DeviceTypeSpec { name: "midi_raw", family: DeviceFamily::Serial, keys: &["path"], parse: serial_device, slots: None }, ]; @@ -239,6 +242,7 @@ impl DeviceModel { DeviceModel::Serial(d) => d.kind.name(), DeviceModel::Net(_) => "net", DeviceModel::Camera(_) => "camera", + DeviceModel::Audio(_) => "audio", }; DEVICE_TYPES.iter().find(|t| t.name == name).expect("every variant has a type") } @@ -274,6 +278,7 @@ impl DeviceModel { DeviceModel::Board(b) if b.model != GraphicsBoard::Newport => format!("{} {}", self.spec().name, b.model), DeviceModel::Net(n) => format!("net {}", n.backend), DeviceModel::Camera(c) => format!("camera {}", c.backend), + DeviceModel::Audio(a) => format!("audio {}", a.backend), _ => self.spec().name.to_string(), } } @@ -296,6 +301,7 @@ impl DeviceModel { DeviceModel::Board(b) => changed(b, keys), DeviceModel::Net(d) => changed(d, keys), DeviceModel::Camera(d) => changed(d, keys), + DeviceModel::Audio(d) => changed(d, keys), DeviceModel::XioBoard(_) | DeviceModel::PciBridge | DeviceModel::Ice1724 | DeviceModel::Qla2200 | DeviceModel::Ultra64 | DeviceModel::Empty => toml::Table::new(), } } @@ -530,7 +536,7 @@ pub fn build_cards(&mut self, cfg: &MachineConfig, timers: &Arc) - if cfg.no_audio { eprintln!("iris: {AUDIO_WITH_NO_AUDIO}"); } else { - card.enable_output(cfg.audio.clone()); + card.enable_output(AudioConfig::at_port(self.port(&format!("{at}/audio")).map(|p| &p.1.device))); } bus.attach(slot, card.clone()); card.register_locks(); diff --git a/src/host_audio.rs b/src/host_audio.rs index 6a29fb161..3b9a4bc3c 100644 --- a/src/host_audio.rs +++ b/src/host_audio.rs @@ -6,7 +6,7 @@ //! them; rate conversion, following the guest's clock, prebuffering, //! following the host's default device and surviving its absence all //! happen on the other side of the stream. This module only turns the -//! `[audio]` section into a stream. +//! `audio` entry into a stream. use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; @@ -17,7 +17,7 @@ pub use iris_audio::Output; use crate::config::{AudioConfig, AudioHost}; -/// The rate of an `[audio] file`. +/// The rate of a `file:` audio backend. pub const FILE_RATE: u32 = 48000; /// The highest rate a device may set on its stream. const MAX_RATE: u32 = 96000; @@ -27,7 +27,7 @@ const MAX_LATENCY: Duration = Duration::from_millis(100); /// Open and start a host output stream for the device `who`, playing /// `channels`-wide frames at `rate` Hz (which [`Output::set_rate`] changes -/// later) as `[audio]` asks. The stream opens even when the host has no +/// later) as the `audio` entry asks. The stream opens even when the host has no /// sound device or server just now, and moves to one when it appears, so a /// device opens once and never retries. `None`, with a message, only when /// the configuration cannot work: an unwritable `file`, a host this @@ -177,7 +177,7 @@ pub(crate) mod test_signal { } } - /// `[audio]` settings that play into a WAV file of the test's own, and + /// `audio` settings that play into a WAV file of the test's own, and /// the file. pub(crate) fn file_config(name: &str) -> (AudioConfig, TempWav) { let path = std::env::temp_dir().join(format!("iris-{name}-{}.wav", std::process::id())); @@ -185,7 +185,7 @@ pub(crate) mod test_signal { } /// The variable naming the loopback a real-device test records from: - /// `:`. The host is the `[audio] host` the + /// `:`. The host is the `audio` backend the /// card plays through (`default` or `pulse`); the source is the /// PulseAudio source that hears the default output, such as a null /// sink's monitor: `default:iris_sink.monitor`. Linux only: recording @@ -194,7 +194,7 @@ pub(crate) mod test_signal { /// Where a test hears what a card sent to the host. pub(crate) enum Backend { - /// An `[audio] file` of the test's own. Needs no sound card. + /// A `file:` audio backend of the test's own. Needs no sound card. File, /// The host's real default output, recorded back through the /// loopback [`LOOPBACK_VAR`] names: the host backend, the sound @@ -209,7 +209,7 @@ pub(crate) mod test_signal { pub(crate) pcm: Vec, } - /// The `[audio]` settings a card under test plays with, and what records + /// The `audio` settings a card under test plays with, and what records /// it. A real-device listener holds a lock while it lives: two cards on /// one default output would mix. pub(crate) struct Listener { @@ -634,7 +634,7 @@ mod tests { } /// Play stereo `pcm` at `rate` into a detached stream whose device runs - /// at the file's rate with no rate adjustment, as an `[audio] file` does; + /// at the file's rate with no rate adjustment, as a `file:` audio backend does; /// return what the device took, from its first sound. The test is the /// device, so a busy host cannot starve it into an underrun. fn played_through_a_stream(rate: u32, pcm: &[i16]) -> Vec { diff --git a/src/ip27.rs b/src/ip27.rs index 4d3ed5462..d8b403550 100644 --- a/src/ip27.rs +++ b/src/ip27.rs @@ -382,6 +382,10 @@ pub(crate) fn slots(s: &mut Vec, profile: MachineP crate::topology::scsi_bus_slots(s, &format!("xio{widget}/pci0/{d}"), "isp1040", 15); } crate::topology::open_slot(s, &format!("xio{widget}/pci0/2/ethernet"), &[DeviceFamily::Net], &["ethernet"]); + // The Onyx2's MediaIO RAD1. + if profile == MachineProfile::Onyx2Ip27 { + crate::topology::open_slot(s, &format!("xio{widget}/pci0/7/audio"), &[DeviceFamily::Audio], &["audio"]); + } } /// The PCI devices both IP27 I/O boards carry behind their Bridge: two ISP1040s and an IOC3. diff --git a/src/ip27_machine.rs b/src/ip27_machine.rs index ad0c67d30..8464ebfd0 100644 --- a/src/ip27_machine.rs +++ b/src/ip27_machine.rs @@ -221,7 +221,7 @@ fn attach_mediaio(timers: &Arc, cfg: &MachineConfig, bridge: &Brid io.monitor.push(mio.ps2()); let rad = Arc::new(Rad1::mediaio(timers)); if !cfg.no_audio { - rad.enable_output(cfg.audio.clone()); + rad.enable_output(cfg.audio()); } pci.attach(DevFn { device: MEDIAIO_RAD1_DEVICE, function: 0 }, rad.clone()); rad.register_locks(); diff --git a/src/ip30_machine.rs b/src/ip30_machine.rs index 616b95a09..018131c9b 100644 --- a/src/ip30_machine.rs +++ b/src/ip30_machine.rs @@ -82,6 +82,7 @@ pub(crate) fn slots(s: &mut Vec) { const OCTANE_BOARDS: &[GraphicsBoard] = &[B::SolidImpact, B::HighImpact, B::MaxImpact, B::V6, B::V8, B::V10, B::V12]; crate::topology::pci_bus_slots(s, &format!("xio{}/pci0", crate::ip30::WIDGET_BRIDGE), "Octane system board", SYSTEM_SLOTS); crate::topology::open_slot(s, &format!("xio{}/pci0/2/ethernet", crate::ip30::WIDGET_BRIDGE), &[DeviceFamily::Net], &["ethernet"]); + crate::topology::open_slot(s, &format!("xio{}/pci0/3/audio", crate::ip30::WIDGET_BRIDGE), &[DeviceFamily::Audio], &["audio"]); for (w, aliases) in XIO_SLOTS { crate::topology::open_slot(s, &format!("xio{w}"), &[DeviceFamily::Xio, DeviceFamily::Gfx], aliases); } @@ -462,7 +463,7 @@ impl OctaneMachine { })); let rad = Arc::new(Rad1::new(&timer_manager)); if !cfg.no_audio { - rad.enable_output(cfg.audio.clone()); + rad.enable_output(cfg.audio()); } pci.attach(slot(3), rad.clone()); // The status bar's activity bits and the CPU's Compare matches, diff --git a/src/ip32_machine.rs b/src/ip32_machine.rs index dc1166cc8..04fa261e3 100644 --- a/src/ip32_machine.rs +++ b/src/ip32_machine.rs @@ -157,6 +157,7 @@ pub(crate) fn slots(s: &mut Vec) { crate::topology::fixed_slot(s, "gbe", "CRIME/GBE", &["graphics"]); crate::topology::fixed_slot(s, "mace", "mace", &[]); crate::topology::open_slot(s, "mace/ethernet", &[crate::topology::DeviceFamily::Net], &["ethernet"]); + crate::topology::open_slot(s, "mace/audio", &[crate::topology::DeviceFamily::Audio], &["audio"]); } @@ -204,7 +205,7 @@ impl O2Machine { let bus = Ip32Bus::with_options(mem, prom, opts, &timer_manager); // MACE audio plays through the host unless audio is off. if !cfg.no_audio { - bus.mace.audio.enable_output(cfg.audio.clone()); + bus.mace.audio.enable_output(cfg.audio()); } if let Some(d) = attached.daynaports.first() { return Err(format!("{}: kind = \"daynaport\" is not available on the O2", crate::config::scsi_label(d.controller, d.id))); diff --git a/src/iris_ci_boot.rs b/src/iris_ci_boot.rs index dfeb7ad16..8b28ba8a6 100644 --- a/src/iris_ci_boot.rs +++ b/src/iris_ci_boot.rs @@ -208,15 +208,16 @@ fn config(disk: &Path, socket: &str, machine: &str) -> String { let mut t = toml::Table::new(); t.insert("machine".into(), m.into()); // Not no_audio: it removes HAL2 on an Indy, and the installed kernel then reconfigures. - let mut audio = toml::Table::new(); - audio.insert("host".into(), "null".into()); - t.insert("audio".into(), audio.into()); + let mut devices = vec![toml::Value::from(hdd)]; + if iris::config::MachineProfile::from_name(machine).is_ok_and(|p| p.slots().iter().any(|s| s.aliases.iter().any(|a| a == "audio"))) { + devices.push(toml::Table::from_iter([("type".into(), "audio".into()), ("at".into(), "audio".into()), ("backend".into(), "null".into())]).into()); + } t.insert("nvram".into(), "nvram.bin".into()); t.insert("serial_log".into(), "serial.log".into()); t.insert("serial_log_overwrite".into(), true.into()); t.insert("ci".into(), true.into()); t.insert("ci_socket".into(), socket.into()); - t.insert("devices".into(), vec![toml::Value::from(hdd)].into()); + t.insert("devices".into(), devices.into()); format!("# Written by iris-ci boot-test.\n{}", toml::to_string(&t).expect("a table of plain values")) } @@ -745,9 +746,9 @@ mod tests { #[test] fn the_config_silences_the_host_and_keeps_hal2() { use iris::config::{AudioHost, MachineConfig}; - let cfg: MachineConfig = toml::from_str(&config(Path::new("d.chd"), "s", "indy_ip24")).unwrap(); + let cfg = MachineConfig::from_toml_str(&config(Path::new("d.chd"), "s", "indy_ip24")).unwrap(); assert!(!cfg.no_audio); - assert_eq!(cfg.audio.host, AudioHost::Null); + assert_eq!(cfg.audio().host, AudioHost::Null); } #[test] diff --git a/src/machine.rs b/src/machine.rs index 1712fcbf0..248cc1660 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -356,7 +356,7 @@ impl Machine { std::process::exit(1); } }; - let hpc3 = Hpc3::with_net(eeprom_hpc3.clone(), ioc.clone(), guinness, heartbeat.clone(), cfg.network(), cfg.no_audio, cfg.audio.clone(), cfg.nvram.clone(), cfg.rtc_offset, cfg.scsi_deferred_int, scsi_buses, &timer_manager); + let hpc3 = Hpc3::with_net(eeprom_hpc3.clone(), ioc.clone(), guinness, heartbeat.clone(), cfg.network(), cfg.no_audio, cfg.audio(), cfg.nvram.clone(), cfg.rtc_offset, cfg.scsi_deferred_int, scsi_buses, &timer_manager); // Backdoor-inject the configured (or default) Ethernet station // address before the CPU ever runs, since real hardware always has diff --git a/src/slot_path.rs b/src/slot_path.rs index 6fccc1fe4..c82d9946a 100644 --- a/src/slot_path.rs +++ b/src/slot_path.rs @@ -25,6 +25,7 @@ const TAGS: &[(&str, bool)] = &[ ("ethernet", false), // the Ethernet port of the part above it ("vino", false), ("video", false), // the video input of the part above it + ("audio", false), // the audio output of the part above it ]; const BARE: u8 = 3; diff --git a/src/topology.rs b/src/topology.rs index 5ead635bb..1f2bc90bc 100644 --- a/src/topology.rs +++ b/src/topology.rs @@ -30,6 +30,8 @@ pub enum DeviceFamily { Net, /// The picture at a video input. Video, + /// The host output of a sound chip. + Audio, Empty, } @@ -46,6 +48,7 @@ impl DeviceFamily { DeviceFamily::Serial => "serial devices", DeviceFamily::Net => "network backends", DeviceFamily::Video => "cameras", + DeviceFamily::Audio => "audio backends", DeviceFamily::Empty => "nothing", } } diff --git a/src/tree.rs b/src/tree.rs index 989841dc2..2182070c3 100644 --- a/src/tree.rs +++ b/src/tree.rs @@ -149,6 +149,7 @@ mod tests { "SGI Indy (IP24)", "|-- hpc3 hpc3 built-in", "| |-- ethernet (ethernet) net nat default", + "| |-- audio (audio) - takes: audio backends", "| `-- c0 (scsi0) wd33c93a built-in", "| |-- t1 - takes: scsi devices", "| |-- t2 hdd irix.img config", diff --git a/test/audiotest/check.py b/test/audiotest/check.py index cf6de9de8..d69aff0df 100755 --- a/test/audiotest/check.py +++ b/test/audiotest/check.py @@ -4,7 +4,7 @@ CAPTURE is the card's capture, in either of two forms (told apart by the first four bytes): - WAV a stereo 16-bit WAV (an [audio] file, 48 kHz). The rate comes from + WAV a stereo 16-bit WAV (an audio `file:` backend, 48 kHz). The rate comes from its header. MARKS holds byte offsets into its data chunk. dump what the card played at its own rate (IRIS_AUDIO_DUMP; the layout is in src/dev/audio_dump.rs): records of out:u8, rate:u32, diff --git a/test/audiotest/host.sh b/test/audiotest/host.sh index 4c3462c81..1be3ef035 100755 --- a/test/audiotest/host.sh +++ b/test/audiotest/host.sh @@ -4,7 +4,7 @@ # The guest is an Octane or an O2 with a MIPSpro compiler, logged in or # loginable, with iris started with the control socket SOCKET and the capture # file in its environment: IRIS_AUDIO_DUMP=CAPTURE (or, on the Octane, -# [audio] file = "CAPTURE" in its config, a 48 kHz WAV). This copies the test +# an `audio` entry with `backend = "file:CAPTURE"` in its config, a 48 kHz WAV). This copies the test # in, builds it, plays each case from sweep.sh (only those matching the egrep # PATTERN, if given), and writes OUT/marks.txt. Then run check.py CAPTURE # OUT/marks.txt. diff --git a/tezro.toml.example b/tezro.toml.example index 327b9c230..8642282e4 100644 --- a/tezro.toml.example +++ b/tezro.toml.example @@ -57,8 +57,8 @@ overlay = true # write_cache = false # default true. false stores every write before it completes, like SGI's drives (slower); true can lose ~5 s of writes in a host crash. See STORAGE.md # Optional: the ICE1724 audio controller behind the IO9's PCI bridge. It plays -# as [audio] sets (unset no_audio for sound); [audio] channels = 2, 4, 6 or 8 is -# how many speakers its channels fold down to. +# as its `audio` entry at CARD/audio sets (unset no_audio for sound); channels = 2, 4, 6 or 8 +# there is how many speakers its channels fold down to. # [[devices]] # type = "ice1724" # at = "xio15/pci0/2/pci0/2" diff --git a/tools/netbsd-cd-boot.py b/tools/netbsd-cd-boot.py index 3e7e24c61..18fb1e43f 100755 --- a/tools/netbsd-cd-boot.py +++ b/tools/netbsd-cd-boot.py @@ -53,16 +53,13 @@ def config(iso: Path, cpu: str, sock: str, port: int) -> str: return f"""# Written by tools/netbsd-cd-boot.py. headless = true monitor_port = {port} -devices = [ {{ type = "serial", at = "serial2", backend = "tcp:{port + 1}" }}, {{ type = "serial", at = "serial1", backend = "tcp:{port + 2}" }} ] +devices = [ {{ type = "serial", at = "serial2", backend = "tcp:{port + 1}" }}, {{ type = "serial", at = "serial1", backend = "tcp:{port + 2}" }}, {{ type = "audio", at = "audio", backend = "null" }} ] nvram = "nvram.bin" serial_log = "serial.log" serial_log_overwrite = true ci = true ci_socket = {json.dumps(sock)} -[audio] -host = "null" - [machine] profile = "indy_ip24" cpu = {json.dumps(cpu)} diff --git a/wsl/README.md b/wsl/README.md index d9fc04de7..e6cfa2523 100644 --- a/wsl/README.md +++ b/wsl/README.md @@ -36,7 +36,7 @@ These settings are part of this repository and share the core configuration sche | **Premiere GUI** | `cargo build -p iris-gui --features premiere` — embedded `lightning` + `idle-pause`; `run-iris-gui-premiere.bat` | | **GUI prefs** | Debug tab settings (`gui_gl_capture`, `no_idle`, `log`) persisted in the machine's own TOML; **File → Prepare for premiere…** flushes it to disk and reports the path to run the CLI `--config` against, from that machine's folder | | **Idle refresh** | Status-bar-only heartbeat skips full compositor + partial egui upload — [clanker/perf/gui-idle-refresh.md](../clanker/perf/gui-idle-refresh.md) | -| **Audio** | Every sound device plays through the `iris-audio` crate (WASAPI on Windows); the GUI's audio settings write `[audio]`: host, prebuffer, host buffer (`latency_ms`), channels and a WAV file to play into | +| **Audio** | Every sound device plays through the `iris-audio` crate (WASAPI on Windows); the GUI's audio settings write an `audio` device: host, prebuffer, host buffer (`latency_ms`), channels and a WAV file to play into | | **jitv2 (experimental)** | `--features jitv2` — whole-page compiler, on at runtime once compiled in (no env-var toggle); use `jitv2_lockstep` for diagnostics or `jitv2_opcodefusion` separately (they conflict); `[jitv2] threads` sets the compile pool (unset: one thread per guest CPU, at most 4, capped by the host's usable CPUs) | See [HELP.md](../HELP.md) for monitor commands, serial ports, NVRAM, etc.