[domistream] WIP: rustfmt, doc link, clippy fixes (one collapsible-if left in rtsp/mod.rs), PROTOCOL.md status

Paused at Mark's request.
This commit is contained in:
2026-11-25 14:32:37 +01:00
parent 30a7b90034
commit bd91a1007e
14 changed files with 68 additions and 57 deletions
+14 -4
View File
@@ -200,7 +200,14 @@ impl AudioDepacketizer {
AudioFec::Disabled => None, AudioFec::Disabled => None,
AudioFec::ParityMatrix(m) => Some(ReedSolomon::with_parity_matrix(DATA_SHARDS, PARITY_SHARDS, &m)?), AudioFec::ParityMatrix(m) => Some(ReedSolomon::with_parity_matrix(DATA_SHARDS, PARITY_SHARDS, &m)?),
}; };
Ok(Self { config, code, next: None, blocks: HashMap::new(), events: VecDeque::new(), stats: AudioStats::default() }) Ok(Self {
config,
code,
next: None,
blocks: HashMap::new(),
events: VecDeque::new(),
stats: AudioStats::default(),
})
} }
fn drop_packet(&mut self) -> Result<()> { fn drop_packet(&mut self) -> Result<()> {
@@ -277,7 +284,7 @@ impl AudioDepacketizer {
return false; return false;
} }
let ahead = first.wrapping_sub(next); let ahead = first.wrapping_sub(next);
if ahead < 0x8000 && ahead >= MAX_PACKETS_AHEAD { if (MAX_PACKETS_AHEAD..0x8000).contains(&ahead) {
return false; return false;
} }
let window = (MAX_BLOCKS_IN_FLIGHT * DATA_SHARDS) as u16; let window = (MAX_BLOCKS_IN_FLIGHT * DATA_SHARDS) as u16;
@@ -371,7 +378,9 @@ impl AudioDepacketizer {
.blocks .blocks
.iter() .iter()
.filter(|(b, _)| b.wrapping_sub(base) != 0 && b.wrapping_sub(n) < 0x8000) .filter(|(b, _)| b.wrapping_sub(base) != 0 && b.wrapping_sub(n) < 0x8000)
.filter_map(|(_, blk)| blk.data.iter().flatten().map(|d| d.arrived).chain(blk.parity.iter().flatten().map(|p| p.arrived)).min()) .filter_map(|(_, blk)| {
blk.data.iter().flatten().map(|d| d.arrived).chain(blk.parity.iter().flatten().map(|p| p.arrived)).min()
})
.min(); .min();
match (own, later) { match (own, later) {
(Some(a), Some(b)) => Some(a.min(b)), (Some(a), Some(b)) => Some(a.min(b)),
@@ -411,7 +420,8 @@ impl AudioDepacketizer {
.next() .next()
.or_else(|| { .or_else(|| {
block.data.iter().enumerate().find_map(|(i, d)| { block.data.iter().enumerate().find_map(|(i, d)| {
d.as_ref().map(|d| d.timestamp_ms.wrapping_sub(i as u32 * u32::from(self.config.packet_duration_ms))) d.as_ref()
.map(|d| d.timestamp_ms.wrapping_sub(i as u32 * u32::from(self.config.packet_duration_ms)))
}) })
}) })
.unwrap_or(0); .unwrap_or(0);
+1 -1
View File
@@ -8,8 +8,8 @@
use core::fmt; use core::fmt;
use aes_gcm::aead::{AeadInOut, KeyInit};
use aes_gcm::Aes128Gcm; use aes_gcm::Aes128Gcm;
use aes_gcm::aead::{AeadInOut, KeyInit};
use crate::util::{array, cap, malformed, u16_le, u32_le}; use crate::util::{array, cap, malformed, u16_le, u32_le};
use crate::{Error, Result}; use crate::{Error, Result};
+4 -1
View File
@@ -304,7 +304,10 @@ pub fn encode_client_message(message: &ClientMessage) -> Result<Vec<u8>> {
Ok(m) Ok(m)
} }
ClientMessage::Input(e) => crate::input::encode_input(e), ClientMessage::Input(e) => crate::input::encode_input(e),
ClientMessage::StartA | ClientMessage::StartB | ClientMessage::PeriodicPing | ClientMessage::RequestIdrFrame => { ClientMessage::StartA
| ClientMessage::StartB
| ClientMessage::PeriodicPing
| ClientMessage::RequestIdrFrame => {
Err(crate::Error::Unsupported { what: "a control message whose body is still UNKNOWN (U10)" }) Err(crate::Error::Unsupported { what: "a control message whose body is still UNKNOWN (U10)" })
} }
} }
+17 -14
View File
@@ -367,14 +367,16 @@ impl EnetClient {
check check
} }
CommandBody::SendUnreliable { unreliable_sequence, data } => { CommandBody::SendUnreliable { unreliable_sequence, data } => {
if self.state == EnetState::Connected && channel < self.channel_count { if self.state == EnetState::Connected
if let Some(ch) = self.channels.get_mut(usize::from(channel)) { && channel < self.channel_count
let newer = && let Some(ch) = self.channels.get_mut(usize::from(channel))
ch.in_unreliable.is_none_or(|last| (1..0x8000).contains(&unreliable_sequence.wrapping_sub(last))); {
if newer { let newer = ch
ch.in_unreliable = Some(unreliable_sequence); .in_unreliable
self.events.push_back(EnetEvent::Received { channel, data }); .is_none_or(|last| (1..0x8000).contains(&unreliable_sequence.wrapping_sub(last)));
} if newer {
ch.in_unreliable = Some(unreliable_sequence);
self.events.push_back(EnetEvent::Received { channel, data });
} }
} }
Ok(()) Ok(())
@@ -574,7 +576,10 @@ impl EnetClient {
acknowledge: false, acknowledge: false,
channel_id: channel, channel_id: channel,
reliable_sequence: 0, reliable_sequence: 0,
body: CommandBody::SendUnsequenced { unsequenced_group: self.unsequenced_group, data: data.to_vec() }, body: CommandBody::SendUnsequenced {
unsequenced_group: self.unsequenced_group,
data: data.to_vec(),
},
}); });
} }
} }
@@ -625,11 +630,9 @@ impl EnetClient {
} }
size += protocol::command_size(c); size += protocol::command_size(c);
if let Some(c) = self.resend.pop_front() { if let Some(c) = self.resend.pop_front() {
if let Some(f) = self if let Some(f) = self.in_flight.iter_mut().find(|f| {
.in_flight f.command.channel_id == c.channel_id && f.command.reliable_sequence == c.reliable_sequence
.iter_mut() }) {
.find(|f| f.command.channel_id == c.channel_id && f.command.reliable_sequence == c.reliable_sequence)
{
f.sent_at = now; f.sent_at = now;
} }
commands.push(c); commands.push(c);
+10 -3
View File
@@ -157,7 +157,9 @@ fn is_mds(p: &[u8], data: usize, parity: usize) -> bool {
if p.contains(&0) { if p.contains(&0) {
return false; return false;
} }
let total: u64 = (2..=data.min(parity)).map(|s| choose(data, s).saturating_mul(choose(parity, s))).fold(0u64, u64::saturating_add); let total: u64 = (2..=data.min(parity))
.map(|s| choose(data, s).saturating_mul(choose(parity, s)))
.fold(0u64, u64::saturating_add);
let max_size = if total <= MDS_EXHAUSTIVE_BUDGET { let max_size = if total <= MDS_EXHAUSTIVE_BUDGET {
data.min(parity) data.min(parity)
} else if choose(data, 2).saturating_mul(choose(parity, 2)) <= MDS_PAIRS_BUDGET { } else if choose(data, 2).saturating_mul(choose(parity, 2)) <= MDS_PAIRS_BUDGET {
@@ -335,7 +337,11 @@ impl ReedSolomon {
.take(missing.len()) .take(missing.len())
.collect(); .collect();
let e = missing.len(); let e = missing.len();
let a: Vec<u8> = rows.iter().flat_map(|&r| missing.iter().map(move |&c| (r, c))).map(|(r, c)| self.coefficient(r, c)).collect(); let a: Vec<u8> = rows
.iter()
.flat_map(|&r| missing.iter().map(move |&c| (r, c)))
.map(|(r, c)| self.coefficient(r, c))
.collect();
let a_inv = invert(a, e).ok_or(malformed("fec system is singular (matrix not MDS)"))?; let a_inv = invert(a, e).ok_or(malformed("fec system is singular (matrix not MDS)"))?;
// rhs_r = parity_r - sum over present data of P[r][i] * d_i // rhs_r = parity_r - sum over present data of P[r][i] * d_i
let mut rhs: Vec<Vec<u8>> = Vec::with_capacity(e); let mut rhs: Vec<Vec<u8>> = Vec::with_capacity(e);
@@ -362,7 +368,8 @@ impl ReedSolomon {
(0..self.parity_shards).filter(|&j| shards.get(k + j).is_some_and(Option::is_none)).collect(); (0..self.parity_shards).filter(|&j| shards.get(k + j).is_some_and(Option::is_none)).collect();
if !parity_missing.is_empty() { if !parity_missing.is_empty() {
let data: Vec<&[u8]> = shards.iter().take(k).flatten().map(Vec::as_slice).collect(); let data: Vec<&[u8]> = shards.iter().take(k).flatten().map(Vec::as_slice).collect();
let rebuilt: Vec<(usize, Vec<u8>)> = parity_missing.iter().map(|&j| (j, self.parity_row(j, &data, len))).collect(); let rebuilt: Vec<(usize, Vec<u8>)> =
parity_missing.iter().map(|&j| (j, self.parity_row(j, &data, len))).collect();
for (j, p) in rebuilt { for (j, p) in rebuilt {
if let Some(s) = shards.get_mut(k + j) { if let Some(s) = shards.get_mut(k + j) {
*s = Some(p); *s = Some(p);
+1 -1
View File
@@ -32,7 +32,7 @@ impl AudioLayout {
} }
/// The speaker mask (WAVE channel-mask bits: FL FR, + FC LFE BL BR, + SL SR). Stereo's `0x3` matches the /// The speaker mask (WAVE channel-mask bits: FL FR, + FC LFE BL BR, + SL SR). Stereo's `0x3` matches the
/// documented default `surroundAudioInfo` 0x30002 [M]; the surround masks are the standard layouts (U4). /// documented default `surroundAudioInfo` 0x30002 (source M); the surround masks are the standard layouts (U4).
#[must_use] #[must_use]
pub const fn channel_mask(self) -> u32 { pub const fn channel_mask(self) -> u32 {
match self { match self {
+5 -3
View File
@@ -95,13 +95,15 @@ pub fn parse_server_info(body: &[u8]) -> Result<ServerInfo> {
} }
let hostname = non_empty(r, "hostname")?.ok_or(malformed("serverinfo: no hostname"))?.to_owned(); let hostname = non_empty(r, "hostname")?.ok_or(malformed("serverinfo: no hostname"))?.to_owned();
let unique_id = non_empty(r, "uniqueid")?.ok_or(malformed("serverinfo: no uniqueid"))?.to_owned(); let unique_id = non_empty(r, "uniqueid")?.ok_or(malformed("serverinfo: no uniqueid"))?.to_owned();
let https_port = parse_u16("serverinfo HttpsPort", field(r, "HttpsPort")?.ok_or(malformed("serverinfo: no HttpsPort"))?)?; let https_port =
parse_u16("serverinfo HttpsPort", field(r, "HttpsPort")?.ok_or(malformed("serverinfo: no HttpsPort"))?)?;
let http_port = non_empty(r, "ExternalPort")?.map(|p| parse_u16("serverinfo ExternalPort", p)).transpose()?; let http_port = non_empty(r, "ExternalPort")?.map(|p| parse_u16("serverinfo ExternalPort", p)).transpose()?;
let mac = non_empty(r, "mac")?.map(parse_mac).transpose()?; let mac = non_empty(r, "mac")?.map(parse_mac).transpose()?;
let max_luma_pixels_hevc = let max_luma_pixels_hevc =
non_empty(r, "MaxLumaPixelsHEVC")?.map(|v| parse_dec("serverinfo MaxLumaPixelsHEVC", v)).transpose()?; non_empty(r, "MaxLumaPixelsHEVC")?.map(|v| parse_dec("serverinfo MaxLumaPixelsHEVC", v)).transpose()?;
let codec_mode_support = let codec_mode_support = non_empty(r, "ServerCodecModeSupport")?
non_empty(r, "ServerCodecModeSupport")?.map(|v| parse_u32("serverinfo ServerCodecModeSupport", v)).transpose()?; .map(|v| parse_u32("serverinfo ServerCodecModeSupport", v))
.transpose()?;
let paired = match non_empty(r, "PairStatus")? { let paired = match non_empty(r, "PairStatus")? {
None | Some("0") => false, None | Some("0") => false,
Some("1") => true, Some("1") => true,
+3 -4
View File
@@ -201,10 +201,9 @@ pub fn encode_input(event: &InputEvent) -> crate::Result<Vec<u8>> {
InputType::MouseMoveAbs, InputType::MouseMoveAbs,
&[x.to_be_bytes(), y.to_be_bytes(), [0, 0], width.to_be_bytes(), height.to_be_bytes()].concat(), &[x.to_be_bytes(), y.to_be_bytes(), [0, 0], width.to_be_bytes(), height.to_be_bytes()].concat(),
), ),
InputEvent::MouseButton { pressed, button } => frame( InputEvent::MouseButton { pressed, button } => {
if pressed { InputType::MouseButtonDown } else { InputType::MouseButtonUp }, frame(if pressed { InputType::MouseButtonDown } else { InputType::MouseButtonUp }, &[button as u8])
&[button as u8], }
),
InputEvent::Key { pressed, flags, key_code, modifiers } => { InputEvent::Key { pressed, flags, key_code, modifiers } => {
let [lo, hi] = key_code.to_le_bytes(); let [lo, hi] = key_code.to_le_bytes();
frame(if pressed { InputType::KeyDown } else { InputType::KeyUp }, &[flags, lo, hi, modifiers, 0, 0]) frame(if pressed { InputType::KeyDown } else { InputType::KeyUp }, &[flags, lo, hi, modifiers, 0, 0])
+2 -2
View File
@@ -32,8 +32,8 @@ fn ecb(key: &PairingKey, data: &[u8], encrypt: bool) -> Result<Vec<u8>> {
} }
let cipher = Aes128::new(key.into()); let cipher = Aes128::new(key.into());
let mut out = data.to_vec(); let mut out = data.to_vec();
for chunk in out.chunks_exact_mut(16) { for chunk in out.as_chunks_mut::<16>().0 {
let block: &mut aes::Block = chunk.try_into().map_err(|_| malformed("aes block"))?; let block: &mut aes::Block = chunk.into();
if encrypt { if encrypt {
cipher.encrypt_block(block); cipher.encrypt_block(block);
} else { } else {
+2 -4
View File
@@ -271,10 +271,8 @@ impl ServerCert {
const END: &[u8] = b"-----END CERTIFICATE-----"; const END: &[u8] = b"-----END CERTIFICATE-----";
cap("host certificate PEM", MAX_CERT_PEM_BYTES, pem.len())?; cap("host certificate PEM", MAX_CERT_PEM_BYTES, pem.len())?;
let trimmed = pem.trim_ascii(); let trimmed = pem.trim_ascii();
let body = trimmed let body =
.strip_prefix(BEGIN) trimmed.strip_prefix(BEGIN).and_then(|b| b.strip_suffix(END)).ok_or(malformed("host certificate PEM"))?;
.and_then(|b| b.strip_suffix(END))
.ok_or(malformed("host certificate PEM"))?;
if body.windows(5).any(|w| w == b"-----") { if body.windows(5).any(|w| w == b"-----") {
return Err(malformed("host certificate PEM holds more than one block")); return Err(malformed("host certificate PEM holds more than one block"));
} }
+1 -7
View File
@@ -170,13 +170,7 @@ impl RtspClient {
Ok(c) Ok(c)
} }
fn queue( fn queue(&mut self, method: Method, target: &str, mut extra: Vec<(String, String)>, body: Vec<u8>) -> Result<()> {
&mut self,
method: Method,
target: &str,
mut extra: Vec<(String, String)>,
body: Vec<u8>,
) -> Result<()> {
self.cseq = self.cseq.wrapping_add(1); self.cseq = self.cseq.wrapping_add(1);
let mut headers = vec![("CSeq".to_owned(), self.cseq.to_string())]; let mut headers = vec![("CSeq".to_owned(), self.cseq.to_string())];
headers.push(("X-GS-ClientVersion".to_owned(), CLIENT_VERSION.to_owned())); headers.push(("X-GS-ClientVersion".to_owned(), CLIENT_VERSION.to_owned()));
+2 -6
View File
@@ -111,12 +111,8 @@ pub(crate) fn hex_decode(what: &'static str, s: &str) -> Result<Vec<u8>> {
return Err(malformed(what)); return Err(malformed(what));
} }
let mut out = Vec::with_capacity(b.len() / 2); let mut out = Vec::with_capacity(b.len() / 2);
for pair in b.chunks_exact(2) { for [h, l] in b.as_chunks::<2>().0 {
let (hi, lo) = match pair { match (hex_digit(*h), hex_digit(*l)) {
[h, l] => (hex_digit(*h), hex_digit(*l)),
_ => (None, None),
};
match (hi, lo) {
(Some(h), Some(l)) => out.push((h << 4) | l), (Some(h), Some(l)) => out.push((h << 4) | l),
_ => return Err(malformed(what)), _ => return Err(malformed(what)),
} }
+1 -4
View File
@@ -286,10 +286,7 @@ impl VideoDepacketizer {
} }
block.shards.insert(fec.shard_index, p.payload.to_vec()); block.shards.insert(fec.shard_index, p.payload.to_vec());
let complete = (0..=usize::from(f.last_block)).all(|b| { let complete = (0..=usize::from(f.last_block)).all(|b| {
f.blocks f.blocks.get(b).and_then(Option::as_ref).is_some_and(|blk| blk.shards.len() >= usize::from(blk.data_shards))
.get(b)
.and_then(Option::as_ref)
.is_some_and(|blk| blk.shards.len() >= usize::from(blk.data_shards))
}); });
if complete { if complete {
match assemble(f, frame, payload_len, now) { match assemble(f, frame, payload_len, now) {
+5 -3
View File
@@ -2,8 +2,9 @@
The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf
protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is
marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, Phase A (docs + API, no logic yet). U9 narrowed and U14 settled from the approved sources the same marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, implemented as stream-v0.1.0 per these docs and the approved sources; interop with a real host
day (sections 3.1, 5.3); the rest waits for the lab capture ([LAB_CAPTURE.md](LAB_CAPTURE.md)). is unverified (the lab capture was not run, [LAB_CAPTURE.md](LAB_CAPTURE.md)). U9 narrowed and U14 settled from the
approved sources (sections 3.1, 5.3); where an UNKNOWN remains, the code follows the Wolf-documented behaviour.
**Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)): **Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)):
@@ -510,7 +511,8 @@ Every 4 data packets are followed by 2 parity packets [W6]. A block is the 4 dat
start at a multiple of 4 [M]; the base sequence and timestamp in the FEC header are the first data packet's [M]. start at a multiple of 4 [M]; the base sequence and timestamp in the FEC header are the first data packet's [M].
Shards are the encrypted payloads (all 4 the same length, constant-bitrate Opus) [M]. A lost data packet is rebuilt Shards are the encrypted payloads (all 4 the same length, constant-bitrate Opus) [M]. A lost data packet is rebuilt
from any 4 of the 6 packets; its RTP header comes from the base values (sequence = base + index, timestamp = base + from any 4 of the 6 packets; its RTP header comes from the base values (sequence = base + index, timestamp = base +
index × duration) [M]. index × duration) [M]. DomiStream waits for the jitter budget (`loss_timeout`) before rebuilding a missing packet,
so a packet that arrives late is played as sent rather than as a rebuilt copy.
UNKNOWN U16 (blocks audio FEC): the parity matrix. It is a fixed 2 × 4 matrix over GF(2^8), **not** the default UNKNOWN U16 (blocks audio FEC): the parity matrix. It is a fixed 2 × 4 matrix over GF(2^8), **not** the default
construction of the RS library Moonshine uses [M]. The only value we have seen carries GPL provenance and is not construction of the RS library Moonshine uses [M]. The only value we have seen carries GPL provenance and is not