alpha2-host-core 0.10.0

FFmpeg-free native host logic for alpha2: the policies, audio timelines, cursor rules, providers, plugin runtime, protocol frames and request parsing native hosts share, and the decode, export and still pipeline the mobile hosts run.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! A file's fingerprint and media facts, read from its container and parameter sets alone.

use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::Path;
use std::time::UNIX_EPOCH;

use alpha2_assets::{AudioStreamFacts, FrameRateEvidence};
use alpha2_container::{
    AudioCodec, ContainerReader, DemuxError, TrackInfo, TrackKind, VideoCodec, VideoTrack,
};
use alpha2_media::{CancelToken, ColorMetadata, SampleAspectRatio};
use alpha2_model::{AudioStreamShape, MediaFingerprint, StreamTopology, VideoStreamShape};
use alpha2_time::FrameRate;
use serde::Serialize;
use sha2::{Digest, Sha256};

use crate::parameter_sets::{ParameterSetCodec, SequenceFacts, sequence_facts};
use crate::stills::{probe_still, still_format};
use crate::video_stream::to_media_time;

/// What a probe found in one file.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaProbe {
    /// The evidence a project records of the file.
    pub fingerprint: MediaFingerprint,
    /// What the file holds.
    pub kind: ProbedKind,
    /// Whether the fingerprint has an audio stream.
    pub has_audio: bool,
    /// Every track in container order; a still has one video track.
    pub tracks: Vec<TrackFacts>,
    /// The audio tracks in container order, as an asset catalog lists them.
    pub audio_streams: Vec<AudioStreamFacts>,
}

/// What a probed file holds, by the project's media kinds.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProbedKind {
    /// A video track, with or without sound.
    Video,
    /// Sound only.
    Audio,
    /// A still picture.
    Image,
}

/// What a track's container entry and parameter sets state.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrackFacts {
    /// What the track carries.
    pub kind: TrackFactsKind,
    /// The codec, by the name the desktop host's catalog gives it.
    pub codec: String,
    /// The track's own presentation duration, when the container states one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_ticks: Option<i64>,
    /// The language tag, when tagged.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// The track's name, when tagged.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Whether the container flags it as a default track.
    pub default: bool,
    /// The picture facts of a video track.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub video: Option<VideoFacts>,
    /// The sound facts of an audio track.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio: Option<AudioFacts>,
}

/// What a track carries.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TrackFactsKind {
    /// Pictures.
    Video,
    /// Sound.
    Audio,
    /// Anything else (subtitles, timecode, metadata).
    Other,
}

/// A video track's picture facts.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VideoFacts {
    /// Coded width in pixels.
    pub coded_width: u32,
    /// Coded height in pixels.
    pub coded_height: u32,
    /// Clockwise rotation in degrees (0, 90, 180 or 270), applied after the mirror.
    pub rotation: u32,
    /// Whether the stored picture is mirrored left to right before it turns.
    pub mirror: bool,
    /// The pixel aspect ratio the container declares, else the bitstream's.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sample_aspect_ratio: Option<Ratio>,
    /// Luma bits per sample, where the parameter sets state it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bit_depth: Option<u32>,
    /// The color the container declares, else the bitstream's.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub color: Option<ColorMetadata>,
    /// The frame rate the container states, absent for variable-rate media.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nominal_frame_rate: Option<FrameRate>,
    /// Whether the track carries alpha.
    pub alpha: bool,
}

/// An audio track's sound facts.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AudioFacts {
    /// Samples per second.
    pub sample_rate: u32,
    /// Channel count.
    pub channels: u32,
    /// Bits per decoded sample, when stated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bits_per_sample: Option<u16>,
}

/// A ratio of two positive integers.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub struct Ratio {
    /// Numerator.
    pub num: u32,
    /// Denominator.
    pub den: u32,
}

/// Why a file could not be probed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProbeError {
    /// Nothing is at the path.
    Missing,
    /// The file could not be read, or its data breaks its format's rules.
    Unreadable(String),
    /// A format this layer does not read, with the reason.
    Unsupported(String),
    /// The cancel token was set.
    Cancelled,
}

impl std::fmt::Display for ProbeError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Missing => write!(formatter, "the file is missing"),
            Self::Unreadable(reason) | Self::Unsupported(reason) => write!(formatter, "{reason}"),
            Self::Cancelled => write!(formatter, "the probe was cancelled"),
        }
    }
}

impl std::error::Error for ProbeError {}

impl From<DemuxError> for ProbeError {
    fn from(error: DemuxError) -> Self {
        match error {
            DemuxError::Unsupported(reason) => Self::Unsupported(reason),
            error => Self::Unreadable(error.to_string()),
        }
    }
}

const HASH_BLOCK_BYTES: usize = 1 << 20;
const SNIFF_BYTES: u64 = 4096;

/// Probes the file at `path`: its fingerprint by the rules every host records, with a SHA-256
/// of every byte when `hash`, and what its container and parameter sets state.
///
/// # Errors
/// [`ProbeError::Missing`] when nothing is at `path`, [`ProbeError::Unsupported`] for a format
/// this layer does not read, [`ProbeError::Unreadable`] for read failures and damaged data, and
/// [`ProbeError::Cancelled`] once `cancel` is set.
pub fn probe_file(path: &Path, hash: bool, cancel: &CancelToken) -> Result<MediaProbe, ProbeError> {
    let metadata = match std::fs::metadata(path) {
        Ok(metadata) if metadata.is_file() => metadata,
        Ok(_) => return Err(ProbeError::Unreadable("the path is not a file".into())),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Err(ProbeError::Missing);
        }
        Err(error) => return Err(unreadable(&error)),
    };
    let mut file = File::open(path).map_err(|error| unreadable(&error))?;
    let mut head = Vec::new();
    (&mut file)
        .take(SNIFF_BYTES)
        .read_to_end(&mut head)
        .map_err(|error| unreadable(&error))?;
    file.seek(SeekFrom::Start(0))
        .map_err(|error| unreadable(&error))?;
    let mut probe = if still_format(&head).is_some() {
        probe_image(&mut file)?
    } else {
        let mut reader = alpha2_container::open_source(Box::new(file))?;
        probe_container(reader.as_mut(), cancel)?
    };
    probe.fingerprint.byte_length = Some(metadata.len());
    probe.fingerprint.modified_ms = metadata
        .modified()
        .ok()
        .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
        .and_then(|since| i64::try_from(since.as_millis()).ok());
    if hash {
        probe.fingerprint.content_sha256 = Some(sha256(path, cancel)?);
    }
    Ok(probe)
}

/// The SHA-256 of every byte of the file at `path`, as 64 lowercase hexadecimal digits.
///
/// # Errors
/// [`ProbeError::Unreadable`] for a read failure, [`ProbeError::Cancelled`] once `cancel` is set.
pub fn sha256(path: &Path, cancel: &CancelToken) -> Result<String, ProbeError> {
    let mut file = File::open(path).map_err(|error| match error.kind() {
        std::io::ErrorKind::NotFound => ProbeError::Missing,
        _ => unreadable(&error),
    })?;
    let mut hasher = Sha256::new();
    let mut block = vec![0; HASH_BLOCK_BYTES];
    loop {
        if cancel.is_cancelled() {
            return Err(ProbeError::Cancelled);
        }
        let read = match file.read(&mut block) {
            Ok(0) => break,
            Ok(read) => read,
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(error) => return Err(unreadable(&error)),
        };
        hasher.update(&block[..read]);
    }
    Ok(hasher
        .finalize()
        .iter()
        .fold(String::with_capacity(64), |mut hex, byte| {
            use std::fmt::Write;
            let _ = write!(hex, "{byte:02x}");
            hex
        }))
}

fn unreadable(error: &std::io::Error) -> ProbeError {
    ProbeError::Unreadable(format!("cannot read the file: {error}"))
}

fn probe_image(file: &mut File) -> Result<MediaProbe, ProbeError> {
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes)
        .map_err(|error| unreadable(&error))?;
    let info = probe_still(&bytes).map_err(|error| ProbeError::Unreadable(error.to_string()))?;
    let (width, height) = info.orientation.displayed_size(info.width, info.height);
    Ok(MediaProbe {
        fingerprint: MediaFingerprint {
            streams: Some(StreamTopology {
                video: Some(VideoStreamShape::new(width, height, None)),
                audio: None,
            }),
            ..MediaFingerprint::default()
        },
        kind: ProbedKind::Image,
        has_audio: false,
        tracks: vec![TrackFacts {
            kind: TrackFactsKind::Video,
            codec: info.format.as_str().to_ascii_lowercase(),
            duration_ticks: None,
            language: None,
            title: None,
            default: true,
            video: Some(VideoFacts {
                coded_width: info.width,
                coded_height: info.height,
                rotation: info.orientation.rotation.quarter_turns() * 90,
                mirror: info.orientation.mirror,
                sample_aspect_ratio: None,
                bit_depth: None,
                color: None,
                nominal_frame_rate: None,
                alpha: false,
            }),
            audio: None,
        }],
        audio_streams: Vec::new(),
    })
}

#[derive(Clone, Copy, Debug)]
struct Span {
    start: i64,
    end: Option<i64>,
}

fn probe_container(
    reader: &mut dyn ContainerReader,
    cancel: &CancelToken,
) -> Result<MediaProbe, ProbeError> {
    let tracks = reader.tracks().to_vec();
    let video_index = reader.default_video();
    let audio_index = reader
        .default_audio()
        .filter(|&index| tracks[index].audio.as_ref().is_some_and(decodable));
    let mut spans = Vec::new();
    let mut video_shape = None;
    let mut color = None;
    for (index, track) in tracks.iter().enumerate() {
        match track.kind {
            TrackKind::Video if Some(index) == video_index => {
                let (span, rate) = video_presentation(reader, track, cancel)?;
                spans.extend(span);
                if let Some(video) = &track.video {
                    let sequence = sequence_of(video);
                    let (width, height) = visible_size(video, sequence.as_ref());
                    let aspect = sample_aspect_ratio(video, sequence.as_ref()).unwrap_or_default();
                    let (width, height) = aspect.square_pixel_size(width, height);
                    let (width, height) = video.orientation.displayed_size(width, height);
                    video_shape = Some(VideoStreamShape::new(width, height, rate));
                    color = declared_color(video, sequence.as_ref());
                }
            }
            TrackKind::Video => spans.extend(first_video_presentation(reader, track, cancel)?),
            TrackKind::Audio => spans.extend(audio_presentation(reader, track, cancel)?),
            TrackKind::Other => {}
        }
    }
    let audio_shape = audio_index
        .and_then(|index| tracks[index].audio.as_ref())
        .filter(|audio| audio.channels > 0 && audio.sample_rate > 0)
        .map(|audio| AudioStreamShape::new(audio.channels, audio.sample_rate));
    let has_audio = audio_shape.is_some();
    let kind = if video_shape.is_some() {
        ProbedKind::Video
    } else if has_audio {
        ProbedKind::Audio
    } else {
        return Err(ProbeError::Unsupported(
            "the file has no video or audio track".into(),
        ));
    };
    let fingerprint = MediaFingerprint {
        streams: Some(StreamTopology {
            video: video_shape,
            audio: audio_shape,
        }),
        duration_ticks: presentation_end(
            &spans,
            reader.file_duration().map(alpha2_time::MediaTime::ticks),
        ),
        color,
        ..MediaFingerprint::default()
    };
    let audio_ordinal = audio_index.map(|index| {
        tracks[..index]
            .iter()
            .filter(|track| track.kind == TrackKind::Audio)
            .count()
    });
    let audio_streams = tracks
        .iter()
        .filter(|track| track.kind == TrackKind::Audio)
        .enumerate()
        .map(|(ordinal, track)| {
            let mut facts = AudioStreamFacts::new(
                track.audio.as_ref().map_or(0, |audio| audio.channels),
                Some(ordinal) == audio_ordinal,
            );
            facts.codec = Some(track_codec(track));
            facts.language.clone_from(&track.language);
            facts.title.clone_from(&track.title);
            facts
        })
        .collect();
    Ok(MediaProbe {
        fingerprint,
        kind,
        has_audio,
        tracks: tracks.iter().map(track_facts).collect(),
        audio_streams,
    })
}

/// `FFmpeg` adds a file's own duration (a Matroska segment's) to the earliest track start.
fn presentation_end(spans: &[Span], file_duration: Option<i64>) -> Option<i64> {
    let start = spans.iter().map(|span| span.start).min()?;
    let end = match file_duration {
        Some(duration) => Some(start.saturating_add(duration)),
        None => spans.iter().filter_map(|span| span.end).max(),
    }?;
    Some(end.max(0))
}

fn video_presentation(
    reader: &mut dyn ContainerReader,
    track: &TrackInfo,
    cancel: &CancelToken,
) -> Result<(Option<Span>, Option<FrameRate>), ProbeError> {
    reader.seek(track.id, i64::MIN)?;
    let timescale = f64::from(track.timescale.max(1));
    let mut evidence = FrameRateEvidence::new();
    let mut first = None::<i64>;
    while let Some(packet) = reader.next_packet(track.id)? {
        if cancel.is_cancelled() {
            return Err(ProbeError::Cancelled);
        }
        first = Some(first.map_or(packet.pts, |first| first.min(packet.pts)));
        #[expect(
            clippy::cast_precision_loss,
            reason = "seconds need far fewer than 52 bits"
        )]
        let seconds = packet.pts as f64 / timescale;
        if !evidence.push(seconds) {
            break;
        }
    }
    let span = first.map(|first| span_of(track, first));
    Ok((span, evidence.rate()))
}

fn first_video_presentation(
    reader: &mut dyn ContainerReader,
    track: &TrackInfo,
    cancel: &CancelToken,
) -> Result<Option<Span>, ProbeError> {
    if cancel.is_cancelled() {
        return Err(ProbeError::Cancelled);
    }
    reader.seek(track.id, i64::MIN)?;
    let first = crate::video_stream::first_timestamps(reader, track)
        .map_err(|error| ProbeError::Unreadable(error.to_string()))?
        .into_iter()
        .min();
    Ok(first.map(|first| span_of(track, first)))
}

const fn decodable(audio: &alpha2_container::AudioTrack) -> bool {
    !matches!(audio.codec, AudioCodec::Other(_))
}

fn audio_presentation(
    reader: &mut dyn ContainerReader,
    track: &TrackInfo,
    cancel: &CancelToken,
) -> Result<Option<Span>, ProbeError> {
    if cancel.is_cancelled() {
        return Err(ProbeError::Cancelled);
    }
    reader.seek(track.id, i64::MIN)?;
    let Some(packet) = reader.next_packet(track.id)? else {
        return Ok(None);
    };
    let priming = track.audio.as_ref().map_or(0, |audio| {
        rescale(
            i64::from(audio.priming),
            i64::from(track.timescale.max(1)),
            i64::from(audio.sample_rate.max(1)),
        )
    });
    Ok(Some(span_of(track, packet.pts.saturating_add(priming))))
}

fn span_of(track: &TrackInfo, first: i64) -> Span {
    Span {
        start: to_media_time(first, track.timescale).ticks(),
        end: track
            .duration
            .map(|duration| to_media_time(first.saturating_add(duration), track.timescale).ticks()),
    }
}

fn rescale(value: i64, numerator: i64, denominator: i64) -> i64 {
    let scaled = i128::from(value) * i128::from(numerator) / i128::from(denominator.max(1));
    i64::try_from(scaled).unwrap_or(i64::MAX)
}

fn sequence_of(video: &VideoTrack) -> Option<SequenceFacts> {
    match video.codec {
        VideoCodec::H264 => sequence_facts(ParameterSetCodec::H264, &video.codec_private),
        VideoCodec::Hevc => sequence_facts(ParameterSetCodec::Hevc, &video.codec_private),
        _ => None,
    }
}

fn visible_size(video: &VideoTrack, sequence: Option<&SequenceFacts>) -> (u32, u32) {
    sequence
        .and_then(|facts| facts.crop.visible())
        .map_or((video.width, video.height), |rect| {
            (rect.width, rect.height)
        })
}

fn sample_aspect_ratio(
    video: &VideoTrack,
    sequence: Option<&SequenceFacts>,
) -> Option<SampleAspectRatio> {
    video
        .sample_aspect_ratio
        .or_else(|| sequence.and_then(|facts| facts.vui.sample_aspect_ratio))
}

fn declared_color(video: &VideoTrack, sequence: Option<&SequenceFacts>) -> Option<ColorMetadata> {
    video
        .color
        .or_else(|| sequence.and_then(|facts| facts.vui.color))
}

/// `vpcC` keeps the bit depth in its seventh byte's high nibble, `av1C` in its third byte.
fn bit_depth(video: &VideoTrack, sequence: Option<&SequenceFacts>) -> Option<u32> {
    match video.codec {
        VideoCodec::H264 | VideoCodec::Hevc => sequence.map(|facts| facts.bit_depth_luma),
        VideoCodec::Vp9 => video
            .codec_private
            .get(6)
            .map(|byte| u32::from(byte >> 4))
            .filter(|depth| *depth > 0),
        VideoCodec::Av1 => {
            video
                .codec_private
                .get(2)
                .map(|byte| match (byte & 0x40 != 0, byte & 0x20 != 0) {
                    (false, _) => 8,
                    (true, false) => 10,
                    (true, true) => 12,
                })
        }
        _ => None,
    }
}

fn track_facts(track: &TrackInfo) -> TrackFacts {
    let video = track.video.as_ref().map(|video| {
        let sequence = sequence_of(video);
        VideoFacts {
            coded_width: video.width,
            coded_height: video.height,
            rotation: video.orientation.rotation.quarter_turns() * 90,
            mirror: video.orientation.mirror,
            sample_aspect_ratio: sample_aspect_ratio(video, sequence.as_ref()).map(|ratio| Ratio {
                num: ratio.num,
                den: ratio.den,
            }),
            bit_depth: bit_depth(video, sequence.as_ref()),
            color: declared_color(video, sequence.as_ref()),
            nominal_frame_rate: video.frame_rate,
            alpha: video.alpha,
        }
    });
    TrackFacts {
        kind: match track.kind {
            TrackKind::Video => TrackFactsKind::Video,
            TrackKind::Audio => TrackFactsKind::Audio,
            TrackKind::Other => TrackFactsKind::Other,
        },
        codec: track_codec(track),
        duration_ticks: track
            .duration
            .map(|duration| to_media_time(duration, track.timescale).ticks()),
        language: track.language.clone(),
        title: track.title.clone(),
        default: track.default,
        video,
        audio: track.audio.as_ref().map(|audio| AudioFacts {
            sample_rate: audio.sample_rate,
            channels: audio.channels,
            bits_per_sample: audio.bits_per_sample,
        }),
    }
}

fn track_codec(track: &TrackInfo) -> String {
    if let Some(video) = &track.video {
        return crate::video_stream::codec_name(video.codec);
    }
    let Some(audio) = &track.audio else {
        return "unknown".into();
    };
    match audio.codec {
        AudioCodec::Aac => "aac".into(),
        AudioCodec::Mp3 => "mp3".into(),
        AudioCodec::Opus => "opus".into(),
        AudioCodec::Vorbis => "vorbis".into(),
        AudioCodec::Flac => "flac".into(),
        AudioCodec::Alac => "alac".into(),
        AudioCodec::Pcm(format) => pcm_name(format),
        AudioCodec::Ac3 => "ac3".into(),
        AudioCodec::Eac3 => "eac3".into(),
        AudioCodec::Dts => "dts".into(),
        AudioCodec::Other(fourcc) => fourcc.to_string(),
    }
}

/// The `FFmpeg` name of a PCM layout (`pcm_s16le`, `pcm_f32be`, `pcm_u8`).
fn pcm_name(format: alpha2_container::PcmFormat) -> String {
    let kind = if format.float {
        'f'
    } else if format.signed {
        's'
    } else {
        'u'
    };
    let endian = match (format.bits, format.big_endian) {
        (8, _) => "",
        (_, true) => "be",
        (_, false) => "le",
    };
    format!("pcm_{kind}{}{endian}", format.bits)
}

#[cfg(test)]
#[path = "probe_tests.rs"]
mod tests;