forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

wire.rs467 lines, 15.0 KiBHistoryRawDownload
1//! The PulseAudio native protocol's wire format: packet framing and the tagged
2//! structs every command, reply and event is written in.
3//!
4//! Everything is big-endian. A packet is a 20-byte header (payload length,
5//! channel, offset, flags) and the payload. Control packets travel on channel
6//! `u32::MAX`; a playback stream's samples go out as memblock packets on the
7//! channel the server named in its CREATE reply. Values are tagged: `L` is a
8//! u32, `r` an i64, `1`/`0` a bool, `t` a NUL-terminated string, `x` a
9//! length-prefixed blob, and so on. The layouts here were read off a capture of
10//! libpulse talking to pipewire-pulse at protocol version 35.
11
12#![forbid(unsafe_code)]
13
14/// Channel number of every control packet.
15pub const CONTROL_CHANNEL: u32 = u32::MAX;
16/// Bytes in a packet header.
17pub const HEADER_LEN: usize = 20;
18/// The protocol version this client speaks. Its CREATE_PLAYBACK_STREAM layout
19/// is the one written by [`create_playback_stream_args`].
20pub const PROTOCOL_VERSION: u32 = 35;
21/// `PA_SAMPLE_FLOAT32LE`.
22pub const SAMPLE_FORMAT_FLOAT32LE: u8 = 5;
23/// `PA_VOLUME_NORM`: the stream's own volume, left at unity.
24pub const VOLUME_NORM: u32 = 0x10000;
25/// `PA_INVALID_INDEX`, and the "server's choice" value of the buffer attributes.
26pub const DEFAULT: u32 = u32::MAX;
27
28/// Command numbers (PulseAudio's `PA_COMMAND_*`), the ones this client uses.
29pub mod command {
30 pub const ERROR: u32 = 0;
31 pub const REPLY: u32 = 2;
32 pub const CREATE_PLAYBACK_STREAM: u32 = 3;
33 pub const DELETE_PLAYBACK_STREAM: u32 = 4;
34 pub const AUTH: u32 = 8;
35 pub const SET_CLIENT_NAME: u32 = 9;
36 pub const GET_PLAYBACK_LATENCY: u32 = 14;
37 pub const CORK_PLAYBACK_STREAM: u32 = 41;
38 pub const FLUSH_PLAYBACK_STREAM: u32 = 42;
39 pub const CREATE_RECORD_STREAM: u32 = 5;
40 pub const DELETE_RECORD_STREAM: u32 = 6;
41 pub const GET_SOURCE_INFO_LIST: u32 = 24;
42 pub const CORK_RECORD_STREAM: u32 = 58;
43 /// Server to client: the stream has room for `length` more bytes.
44 pub const REQUEST: u32 = 61;
45 /// Server to client: the stream ran dry while it was playing.
46 pub const UNDERFLOW: u32 = 63;
47 /// Server to client: the server removed the stream.
48 pub const PLAYBACK_STREAM_KILLED: u32 = 64;
49 /// Server to client: the server removed the recording stream.
50 pub const RECORD_STREAM_KILLED: u32 = 65;
51}
52
53/// The fixed fields of a packet header, as [`header`] writes them.
54pub fn header(len: u32, channel: u32, offset: i64, flags: u32) -> [u8; HEADER_LEN] {
55 let mut out = [0u8; HEADER_LEN];
56 out[0..4].copy_from_slice(&len.to_be_bytes());
57 out[4..8].copy_from_slice(&channel.to_be_bytes());
58 out[8..16].copy_from_slice(&offset.to_be_bytes());
59 out[16..20].copy_from_slice(&flags.to_be_bytes());
60 out
61}
62
63/// Splits a header into `(payload length, channel, offset, flags)`.
64pub fn parse_header(bytes: &[u8; HEADER_LEN]) -> (u32, u32, i64, u32) {
65 let be32 = |at: usize| u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap());
66 let offset = i64::from_be_bytes(bytes[8..16].try_into().unwrap());
67 (be32(0), be32(4), offset, be32(16))
68}
69
70/// A whole control packet: header, then the command and tag, then `args`.
71pub fn control(command: u32, tag: u32, args: Tags) -> Vec<u8> {
72 let payload = Tags::new().u32(command).u32(tag).extend(args).into_bytes();
73 let mut packet = header(payload.len() as u32, CONTROL_CHANNEL, 0, 0).to_vec();
74 packet.extend_from_slice(&payload);
75 packet
76}
77
78/// Builds a tagged struct, one value at a time.
79#[derive(Default, Clone, Debug, PartialEq)]
80pub struct Tags(Vec<u8>);
81
82impl Tags {
83 pub fn new() -> Self {
84 Self::default()
85 }
86
87 pub fn into_bytes(self) -> Vec<u8> {
88 self.0
89 }
90
91 /// Appends another struct's values after these.
92 pub fn extend(mut self, other: Tags) -> Self {
93 self.0.extend(other.0);
94 self
95 }
96
97 pub fn u32(mut self, value: u32) -> Self {
98 self.0.push(b'L');
99 self.0.extend_from_slice(&value.to_be_bytes());
100 self
101 }
102
103 /// A usec: the `U` tag, a u64.
104 pub fn usec(mut self, value: u64) -> Self {
105 self.0.push(b'U');
106 self.0.extend_from_slice(&value.to_be_bytes());
107 self
108 }
109
110 /// A plain u64, the `R` tag.
111 pub fn u64(mut self, value: u64) -> Self {
112 self.0.push(b'R');
113 self.0.extend_from_slice(&value.to_be_bytes());
114 self
115 }
116
117 pub fn i64(mut self, value: i64) -> Self {
118 self.0.push(b'r');
119 self.0.extend_from_slice(&value.to_be_bytes());
120 self
121 }
122
123 pub fn u8(mut self, value: u8) -> Self {
124 self.0.push(b'B');
125 self.0.push(value);
126 self
127 }
128
129 pub fn bool(mut self, value: bool) -> Self {
130 self.0.push(if value { b'1' } else { b'0' });
131 self
132 }
133
134 /// A string, NUL-terminated on the wire.
135 pub fn string(mut self, value: &str) -> Self {
136 self.0.push(b't');
137 self.0.extend_from_slice(value.as_bytes());
138 self.0.push(0);
139 self
140 }
141
142 /// The null string: "no name", the server's default.
143 pub fn null(mut self) -> Self {
144 self.0.push(b'N');
145 self
146 }
147
148 /// A length-prefixed blob, such as the authentication cookie.
149 pub fn arbitrary(mut self, value: &[u8]) -> Self {
150 self.0.push(b'x');
151 self.0.extend_from_slice(&(value.len() as u32).to_be_bytes());
152 self.0.extend_from_slice(value);
153 self
154 }
155
156 pub fn sample_spec(mut self, format: u8, channels: u8, rate: u32) -> Self {
157 self.0.push(b'a');
158 self.0.push(format);
159 self.0.push(channels);
160 self.0.extend_from_slice(&rate.to_be_bytes());
161 self
162 }
163
164 pub fn channel_map(mut self, positions: &[u8]) -> Self {
165 self.0.push(b'm');
166 self.0.push(positions.len() as u8);
167 self.0.extend_from_slice(positions);
168 self
169 }
170
171 /// A channel volume: one u32 per channel.
172 pub fn cvolume(mut self, volumes: &[u32]) -> Self {
173 self.0.push(b'v');
174 self.0.push(volumes.len() as u8);
175 for volume in volumes {
176 self.0.extend_from_slice(&volume.to_be_bytes());
177 }
178 self
179 }
180
181 /// A timeval: seconds and microseconds, two u32s.
182 pub fn timeval(mut self, sec: u32, usec: u32) -> Self {
183 self.0.push(b'T');
184 self.0.extend_from_slice(&sec.to_be_bytes());
185 self.0.extend_from_slice(&usec.to_be_bytes());
186 self
187 }
188
189 /// A property list: each key with its value (NUL included in the length),
190 /// closed by the null string.
191 pub fn proplist(mut self, props: &[(&str, &str)]) -> Self {
192 self.0.push(b'P');
193 for (key, value) in props {
194 self = self.string(key);
195 let len = value.len() as u32 + 1;
196 self = self.u32(len);
197 self.0.push(b'x');
198 self.0.extend_from_slice(&len.to_be_bytes());
199 self.0.extend_from_slice(value.as_bytes());
200 self.0.push(0);
201 }
202 self.0.push(b'N');
203 self
204 }
205}
206
207/// Reads a tagged struct back, value by value. Each reader returns `None` when
208/// the next value is not the kind asked for, or the payload runs out.
209pub struct Reader<'a> {
210 buf: &'a [u8],
211}
212
213impl<'a> Reader<'a> {
214 pub fn new(buf: &'a [u8]) -> Self {
215 Self { buf }
216 }
217
218 /// The bytes not read yet.
219 pub fn rest(&self) -> &'a [u8] {
220 self.buf
221 }
222
223 fn take(&mut self, tag: u8, len: usize) -> Option<&'a [u8]> {
224 let (&first, rest) = self.buf.split_first()?;
225 if first != tag || rest.len() < len {
226 return None;
227 }
228 let (value, after) = rest.split_at(len);
229 self.buf = after;
230 Some(value)
231 }
232
233 pub fn u32(&mut self) -> Option<u32> {
234 let value = self.take(b'L', 4)?;
235 Some(u32::from_be_bytes(value.try_into().ok()?))
236 }
237
238 pub fn u64(&mut self) -> Option<u64> {
239 let value = self.take(b'U', 8)?;
240 Some(u64::from_be_bytes(value.try_into().ok()?))
241 }
242
243 pub fn i64(&mut self) -> Option<i64> {
244 let value = self.take(b'r', 8)?;
245 Some(i64::from_be_bytes(value.try_into().ok()?))
246 }
247
248 pub fn bool(&mut self) -> Option<bool> {
249 match self.buf.first()? {
250 b'1' => self.take(b'1', 0).map(|_| true),
251 b'0' => self.take(b'0', 0).map(|_| false),
252 _ => None,
253 }
254 }
255
256 pub fn timeval(&mut self) -> Option<()> {
257 self.take(b'T', 8).map(|_| ())
258 }
259
260 pub fn string(&mut self) -> Option<String> {
261 let (&first, rest) = self.buf.split_first()?;
262 if first != b't' {
263 return None;
264 }
265 let end = rest.iter().position(|&b| b == 0)?;
266 let text = String::from_utf8(rest[..end].to_vec()).ok()?;
267 self.buf = &rest[end + 1..];
268 Some(text)
269 }
270
271 /// A length-prefixed blob: the tag, a raw big-endian length, then the bytes.
272 pub fn arbitrary(&mut self) -> Option<&'a [u8]> {
273 let len = self.take(b'x', 4)?;
274 let len = u32::from_be_bytes(len.try_into().ok()?) as usize;
275 if self.buf.len() < len {
276 return None;
277 }
278 let (value, after) = self.buf.split_at(len);
279 self.buf = after;
280 Some(value)
281 }
282
283 pub fn u8(&mut self) -> Option<u8> {
284 self.take(b'B', 1).map(|v| v[0])
285 }
286
287 /// A string that may be the null string (`N`), which reads as `None`.
288 pub fn string_or_null(&mut self) -> Option<Option<String>> {
289 match self.buf.first()? {
290 b'N' => self.take(b'N', 0).map(|_| None),
291 _ => self.string().map(Some),
292 }
293 }
294
295 /// A sample spec: the tag, format, channels and rate. Skipped by the source list.
296 pub fn sample_spec(&mut self) -> Option<()> {
297 let (&first, rest) = self.buf.split_first()?;
298 if first != b'a' || rest.len() < 6 {
299 return None;
300 }
301 self.buf = &rest[6..];
302 Some(())
303 }
304
305 /// A channel map: the tag, a count, then one position byte per channel.
306 pub fn channel_map(&mut self) -> Option<()> {
307 let n = self.take(b'm', 1)?[0] as usize;
308 self.take_raw(n).map(|_| ())
309 }
310
311 /// A channel volume: the tag, a count, then one u32 per channel.
312 pub fn cvolume(&mut self) -> Option<()> {
313 let n = self.take(b'v', 1)?[0] as usize;
314 self.take_raw(n * 4).map(|_| ())
315 }
316
317 /// A volume, the `V` tag and a u32.
318 pub fn volume(&mut self) -> Option<u32> {
319 let value = self.take(b'V', 4)?;
320 Some(u32::from_be_bytes(value.try_into().ok()?))
321 }
322
323 /// A property list, read and dropped: its keys and values in turn, closed by
324 /// the null string.
325 pub fn skip_proplist(&mut self) -> Option<()> {
326 self.take(b'P', 0)?;
327 while self.string_or_null()?.is_some() {
328 self.u32()?;
329 self.arbitrary()?;
330 }
331 Some(())
332 }
333
334 /// A format info: the `f` tag, an encoding byte and a property list. Skipped
335 /// by the source list.
336 pub fn format_info(&mut self) -> Option<()> {
337 self.take(b'f', 0)?;
338 self.u8()?;
339 self.skip_proplist()
340 }
341
342 /// Bytes with no tag of their own, of exactly `len`.
343 fn take_raw(&mut self, len: usize) -> Option<&'a [u8]> {
344 if self.buf.len() < len {
345 return None;
346 }
347 let (value, after) = self.buf.split_at(len);
348 self.buf = after;
349 Some(value)
350 }
351}
352
353/// Arguments of CREATE_RECORD_STREAM at protocol version 35, in the order the
354/// server reads them (`command_create_record_stream` in protocol-native.c). The
355/// server's default source is used, and the stream starts running.
356pub fn create_record_stream_args(rate: u32, channels: u8, source: Option<&str>, fragsize: u32) -> Tags {
357 let positions: Vec<u8> = match channels {
358 1 => vec![0],
359 2 => vec![1, 2],
360 n => (0..n).map(|i| 12 + i).collect(),
361 };
362 let source = match source {
363 Some(name) => Tags::new().string(name),
364 None => Tags::new().null(),
365 };
366 let mut tags = Tags::new()
367 .sample_spec(SAMPLE_FORMAT_FLOAT32LE, channels, rate)
368 .channel_map(&positions)
369 .u32(DEFAULT)
370 .extend(source)
371 .u32(DEFAULT)
372 .bool(false)
373 .u32(fragsize);
374 // no_remap, no_remix, fix_format, fix_rate, fix_channels, no_move, variable_rate
375 for _ in 0..7 {
376 tags = tags.bool(false);
377 }
378 // peak_detect, adjust_latency, then the proplist, then direct_on_input.
379 tags = tags.bool(false).bool(false).proplist(&[
380 ("application.name", crate::pulse::APP_NAME),
381 ("media.name", "edith voice-over"),
382 ]);
383 tags = tags.u32(DEFAULT).bool(false).bool(false).bool(false);
384 // No formats, then the volume (unset), muted, volume_set, muted_set,
385 // relative_volume and passthrough.
386 tags = tags.u8(0).cvolume(&vec![VOLUME_NORM; channels as usize]);
387 for _ in 0..5 {
388 tags = tags.bool(false);
389 }
390 tags
391}
392
393/// Arguments of CREATE_PLAYBACK_STREAM at protocol version 35, in the order the
394/// server reads them. Flags are all off, as libpulse sends them by default, and
395/// the stream starts running, as the old plugin's did: the caller pauses it.
396pub fn create_playback_stream_args(
397 rate: u32,
398 channels: u8,
399 tlength: u32,
400 minreq: u32,
401 volume: u32,
402) -> Tags {
403 let positions: Vec<u8> = match channels {
404 1 => vec![0],
405 2 => vec![1, 2],
406 n => (0..n).map(|i| 12 + i).collect(),
407 };
408 let mut tags = Tags::new()
409 .sample_spec(SAMPLE_FORMAT_FLOAT32LE, channels, rate)
410 .channel_map(&positions)
411 .u32(DEFAULT)
412 .null()
413 .u32(DEFAULT)
414 .bool(false)
415 .u32(tlength)
416 .u32(tlength)
417 .u32(minreq)
418 .u32(0)
419 .cvolume(&vec![volume; channels as usize]);
420 for _ in 0..9 {
421 tags = tags.bool(false);
422 }
423 tags = tags.proplist(&[
424 ("application.name", crate::pulse::APP_NAME),
425 ("media.name", "edith playback"),
426 ]);
427 for _ in 0..7 {
428 tags = tags.bool(false);
429 }
430 tags.u8(0)
431}
432
433#[cfg(test)]
434mod tests {
435 use super::*;
436
437 #[test]
438 fn wire_round_trips_and_matches_the_capture() {
439 let bytes = header(0x0102, 7, -3, 9);
440 assert_eq!(&bytes[0..4], &[0, 0, 1, 2]);
441 assert_eq!(parse_header(&bytes), (0x0102, 7, -3, 9));
442
443 let bytes = Tags::new()
444 .u32(7)
445 .string("edith")
446 .bool(true)
447 .i64(-5)
448 .arbitrary(&[1, 2, 3])
449 .timeval(1, 2)
450 .into_bytes();
451 let mut r = Reader::new(&bytes);
452 assert_eq!(r.u32(), Some(7));
453 assert_eq!(r.string().as_deref(), Some("edith"));
454 assert_eq!(r.bool(), Some(true));
455 assert_eq!(r.i64(), Some(-5));
456 assert_eq!(r.arbitrary(), Some(&[1u8, 2, 3][..]));
457 assert_eq!(r.timeval(), Some(()));
458 assert_eq!(r.u32(), None, "a wrong tag is refused");
459
460 // The create arguments match the layout captured from libpulse.
461 let args = create_playback_stream_args(48_000, 2, 38_400, 1_920, VOLUME_NORM).into_bytes();
462 assert_eq!(&args[..7], &[b'a', 5, 2, 0, 0, 0xbb, 0x80]);
463 assert_eq!(&args[7..11], &[b'm', 2, 1, 2]);
464 assert_eq!(args[22], b'0');
465 assert_eq!(args.last(), Some(&0));
466 }
467}