alpha2-media 0.9.0

Host-independent media vocabulary and I/O contracts for alpha2.
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
//! Export containers and the codecs each offers.
//!
//! Every host validates requests against this one policy. It is narrower than what the muxers
//! accept: a container offers only codecs its mainstream players decode. `QuickTime` does not
//! play VP9, AV1 or Opus in MOV, `WebM` is VP8/VP9/AV1 with Opus/Vorbis by definition,
//! `ProRes` is offered in MOV only, and WAVE holds PCM sound and no video. Whether a runtime can
//! encode a codec is up to each host.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

use crate::{AudioCodec, PcmSampleFormat, VideoCodec};

/// What an export's sound is stored as: an encoded codec, or PCM in a WAVE file.
///
/// Containers offer them per [`Container::audio_codecs`].
#[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ExportAudioCodec {
    /// AAC-LC.
    Aac,
    /// Opus.
    Opus,
    /// 32-bit IEEE float PCM, the mix's own samples.
    PcmF32,
    /// 24-bit signed integer PCM.
    PcmS24,
    /// 16-bit signed integer PCM.
    PcmS16,
}

impl ExportAudioCodec {
    /// Every codec, in the order the engine lists them.
    pub const ALL: [Self; 5] = [
        Self::Aac,
        Self::Opus,
        Self::PcmF32,
        Self::PcmS24,
        Self::PcmS16,
    ];

    /// Stable identifier used by every protocol and binding.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Aac => "aac",
            Self::Opus => "opus",
            Self::PcmF32 => "pcm-f32",
            Self::PcmS24 => "pcm-s24",
            Self::PcmS16 => "pcm-s16",
        }
    }

    /// The codec an encoder writes it with, at a rate; `None` for PCM.
    #[must_use]
    pub const fn encoded(self) -> Option<AudioCodec> {
        match self {
            Self::Aac => Some(AudioCodec::Aac),
            Self::Opus => Some(AudioCodec::Opus),
            Self::PcmF32 | Self::PcmS24 | Self::PcmS16 => None,
        }
    }

    /// The sample format PCM is stored in; `None` for an encoded codec.
    #[must_use]
    pub const fn pcm(self) -> Option<PcmSampleFormat> {
        match self {
            Self::Aac | Self::Opus => None,
            Self::PcmF32 => Some(PcmSampleFormat::F32),
            Self::PcmS24 => Some(PcmSampleFormat::S24),
            Self::PcmS16 => Some(PcmSampleFormat::S16),
        }
    }
}

impl From<AudioCodec> for ExportAudioCodec {
    fn from(codec: AudioCodec) -> Self {
        match codec {
            AudioCodec::Aac => Self::Aac,
            AudioCodec::Opus => Self::Opus,
        }
    }
}

impl fmt::Display for ExportAudioCodec {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for ExportAudioCodec {
    type Err = ContainerError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::ALL
            .into_iter()
            .find(|codec| codec.as_str() == value)
            .ok_or_else(|| ContainerError::UnknownAudioCodec(value.to_owned()))
    }
}

/// The file format an export is written in.
#[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Container {
    /// ISO base media file (MP4).
    Mp4,
    /// `QuickTime` movie.
    Mov,
    /// Matroska.
    Mkv,
    /// `WebM`, the Matroska subset browsers play.
    Webm,
    /// RIFF WAVE: PCM sound, no video.
    Wav,
}

impl Container {
    /// Every container, in the order the engine lists them.
    pub const ALL: [Self; 5] = [Self::Mp4, Self::Mov, Self::Mkv, Self::Webm, Self::Wav];

    /// Stable identifier used by every protocol and binding.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Mp4 => "mp4",
            Self::Mov => "mov",
            Self::Mkv => "mkv",
            Self::Webm => "webm",
            Self::Wav => "wav",
        }
    }

    /// Lowercase file extensions without the dot; the first is the preferred one.
    #[must_use]
    pub const fn extensions(self) -> &'static [&'static str] {
        match self {
            Self::Mp4 => &["mp4", "m4v"],
            Self::Mov => &["mov"],
            Self::Mkv => &["mkv"],
            Self::Webm => &["webm"],
            Self::Wav => &["wav"],
        }
    }

    /// Further extensions accepted only for an output without video.
    #[must_use]
    pub const fn audio_only_extensions(self) -> &'static [&'static str] {
        match self {
            Self::Mp4 => &["m4a"],
            Self::Mov | Self::Mkv | Self::Webm | Self::Wav => &[],
        }
    }

    /// The MIME type of a file in this container that has video, or of any WAVE file.
    #[must_use]
    pub const fn mime_type(self) -> &'static str {
        match self {
            Self::Mp4 => "video/mp4",
            Self::Mov => "video/quicktime",
            Self::Mkv => "video/x-matroska",
            Self::Webm => "video/webm",
            Self::Wav => "audio/wav",
        }
    }

    /// The MIME type of a file in this container that holds sound only.
    #[must_use]
    pub const fn audio_mime_type(self) -> &'static str {
        match self {
            Self::Mp4 => "audio/mp4",
            Self::Mov => "video/quicktime",
            Self::Mkv => "audio/x-matroska",
            Self::Webm => "audio/webm",
            Self::Wav => "audio/wav",
        }
    }

    /// Video codecs the container offers, the default first; none for a container that holds
    /// sound only.
    #[must_use]
    pub const fn video_codecs(self) -> &'static [VideoCodec] {
        match self {
            Self::Mp4 | Self::Mkv => &[
                VideoCodec::H264,
                VideoCodec::Hevc,
                VideoCodec::Vp9,
                VideoCodec::Av1,
                VideoCodec::Mpeg4Part2,
            ],
            Self::Mov => &[
                VideoCodec::H264,
                VideoCodec::Hevc,
                VideoCodec::Mpeg4Part2,
                VideoCodec::ProRes,
            ],
            // VP9 first: it has a fast software encoder and every browser decodes it.
            Self::Webm => &[VideoCodec::Vp9, VideoCodec::Av1],
            Self::Wav => &[],
        }
    }

    /// Audio codecs the container offers, the default first, in fallback order.
    #[must_use]
    pub const fn audio_codecs(self) -> &'static [ExportAudioCodec] {
        match self {
            Self::Mp4 | Self::Mkv => &[ExportAudioCodec::Aac, ExportAudioCodec::Opus],
            Self::Mov => &[ExportAudioCodec::Aac],
            Self::Webm => &[ExportAudioCodec::Opus],
            Self::Wav => &[
                ExportAudioCodec::PcmF32,
                ExportAudioCodec::PcmS24,
                ExportAudioCodec::PcmS16,
            ],
        }
    }

    /// The video codec an export in this container gets when it names none; `None` for a
    /// container that holds sound only.
    #[must_use]
    pub const fn default_video_codec(self) -> Option<VideoCodec> {
        self.video_codecs().first().copied()
    }

    /// The audio codec an export in this container gets when it names none.
    #[must_use]
    pub const fn default_audio_codec(self) -> ExportAudioCodec {
        self.audio_codecs()[0]
    }

    /// Whether the container offers `codec`.
    #[must_use]
    pub fn offers_video(self, codec: VideoCodec) -> bool {
        self.video_codecs().contains(&codec)
    }

    /// Whether the container offers `codec`.
    #[must_use]
    pub fn offers_audio(self, codec: impl Into<ExportAudioCodec>) -> bool {
        self.audio_codecs().contains(&codec.into())
    }

    /// The container named by an output extension (without the dot), case-insensitively.
    #[must_use]
    pub fn from_extension(extension: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|container| names(container.extensions(), extension))
    }

    /// The container an extension names for an output without video only.
    #[must_use]
    pub fn from_audio_only_extension(extension: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|container| names(container.audio_only_extensions(), extension))
    }
}

fn names(extensions: &[&str], extension: &str) -> bool {
    extensions
        .iter()
        .any(|known| known.eq_ignore_ascii_case(extension))
}

fn accepted_extensions(container: Container, include_video: bool) -> Vec<&'static str> {
    let mut accepted = container.extensions().to_vec();
    if !include_video {
        accepted.extend(container.audio_only_extensions());
    }
    accepted
}

impl fmt::Display for Container {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for Container {
    type Err = ContainerError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::ALL
            .into_iter()
            .find(|container| container.as_str() == value)
            .ok_or_else(|| ContainerError::Unknown(value.to_owned()))
    }
}

/// Why a container request cannot be resolved.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ContainerError {
    /// A container name outside [`Container::ALL`].
    Unknown(String),
    /// An audio codec name outside [`ExportAudioCodec::ALL`].
    UnknownAudioCodec(String),
    /// No container was named and the extension names none.
    UnknownExtension {
        /// The output's extension, `None` when it has none.
        extension: Option<String>,
        /// Whether the output has video, which decides the extensions it may end in.
        include_video: bool,
    },
    /// The output's extension is not one of the named container's.
    ExtensionMismatch {
        /// The container the request named.
        container: Container,
        /// The output's extension, empty when it has none.
        extension: String,
        /// Whether the output has video, which decides the extensions it may end in.
        include_video: bool,
    },
    /// The output's extension is one the container takes only without video.
    AudioOnlyExtension {
        /// The container the extension names.
        container: Container,
        /// The output's extension.
        extension: String,
    },
    /// The output has neither video nor audio.
    NoStreams,
    /// The container holds sound only and the output has video.
    VideoNotOffered {
        /// The resolved container.
        container: Container,
    },
    /// A video codec was named for an output without video.
    VideoCodecWithoutVideo {
        /// The requested codec.
        codec: VideoCodec,
    },
    /// The container does not offer the requested video codec.
    VideoCodecNotOffered {
        /// The resolved container.
        container: Container,
        /// The requested codec.
        codec: VideoCodec,
    },
    /// The container does not offer the requested audio codec.
    AudioCodecNotOffered {
        /// The resolved container.
        container: Container,
        /// The requested codec.
        codec: ExportAudioCodec,
    },
}

fn dotted(extensions: &[&str]) -> String {
    let dotted: Vec<String> = extensions.iter().map(|ext| format!(".{ext}")).collect();
    dotted.join(", ")
}

fn listed<T>(items: &[T], name: impl Fn(&T) -> &'static str) -> String {
    items.iter().map(name).collect::<Vec<_>>().join(", ")
}

impl fmt::Display for ContainerError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unknown(name) => write!(
                formatter,
                "unknown container \"{name}\"; expected one of {}",
                listed(&Container::ALL, |container| container.as_str())
            ),
            Self::UnknownAudioCodec(name) => write!(
                formatter,
                "unknown audio codec \"{name}\"; expected one of {}",
                listed(&ExportAudioCodec::ALL, |codec| codec.as_str())
            ),
            Self::UnknownExtension {
                extension,
                include_video,
            } => {
                let every: Vec<&str> = Container::ALL
                    .into_iter()
                    .filter(|container| !(*include_video && container.video_codecs().is_empty()))
                    .flat_map(|container| accepted_extensions(container, *include_video))
                    .collect();
                match extension {
                    Some(extension) => write!(
                        formatter,
                        "the output extension \".{extension}\" names no container; use one of {}",
                        dotted(&every)
                    ),
                    None => write!(
                        formatter,
                        "the output has no extension to name its container; use one of {}",
                        dotted(&every)
                    ),
                }
            }
            Self::ExtensionMismatch {
                container,
                extension,
                include_video,
            } => {
                let found = if extension.is_empty() {
                    "no extension".to_owned()
                } else {
                    format!("\".{extension}\"")
                };
                write!(
                    formatter,
                    "a {container} output must end in {}, not {found}",
                    dotted(&accepted_extensions(*container, *include_video))
                )
            }
            Self::AudioOnlyExtension {
                container,
                extension,
            } => write!(
                formatter,
                "\".{extension}\" names a {container} output without video; a {container} \
                 output with video ends in {}",
                dotted(container.extensions())
            ),
            Self::NoStreams => {
                formatter.write_str("an output without video and without audio holds nothing")
            }
            Self::VideoNotOffered { container } => write!(
                formatter,
                "{container} holds sound only; it takes an output without video"
            ),
            Self::VideoCodecWithoutVideo { codec } => write!(
                formatter,
                "video codec {} was named for an output without video",
                codec.as_str()
            ),
            Self::VideoCodecNotOffered { container, codec } => write!(
                formatter,
                "{container} does not offer video codec {}; it offers {}",
                codec.as_str(),
                listed(container.video_codecs(), |codec| codec.as_str())
            ),
            Self::AudioCodecNotOffered { container, codec } => write!(
                formatter,
                "{container} does not offer audio codec {}; it offers {}",
                codec.as_str(),
                listed(container.audio_codecs(), |codec| codec.as_str())
            ),
        }
    }
}

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

/// What an export asks to be written as.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ExportFormatRequest<'a> {
    /// The container, when the request names one.
    pub container: Option<Container>,
    /// The output's extension without the dot, empty for a path without one; `None` without a
    /// path.
    pub output_extension: Option<&'a str>,
    /// The video codec, when the request names one.
    pub video: Option<VideoCodec>,
    /// The audio codec, when the request names one.
    pub audio: Option<ExportAudioCodec>,
    /// Whether the output has a video stream.
    pub include_video: bool,
    /// Whether the output has an audio stream.
    pub include_audio: bool,
}

impl Default for ExportFormatRequest<'_> {
    /// Names nothing, with video and audio.
    fn default() -> Self {
        Self {
            container: None,
            output_extension: None,
            video: None,
            audio: None,
            include_video: true,
            include_audio: true,
        }
    }
}

/// The container and codecs an export writes.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ExportFormat {
    /// The output container.
    pub container: Container,
    /// The video codec; `None` for an output without video.
    pub video: Option<VideoCodec>,
    /// The audio codec, used when the output has audio.
    pub audio: ExportAudioCodec,
}

/// Resolves an export's container and codecs.
///
/// - Without a container, the output extension decides; with neither, the container is MP4.
/// - A named container and the output extension must agree. An output without video may also
///   end in one of the container's [`Container::audio_only_extensions`].
/// - An output has video, audio or both; a container that holds sound only takes no video, and
///   an output without video names no video codec.
/// - A missing codec takes the container default; a named codec must be offered.
///
/// # Errors
/// Returns the first [`ContainerError`] in the order above.
pub fn resolve_export_format(
    request: &ExportFormatRequest<'_>,
) -> Result<ExportFormat, ContainerError> {
    let ExportFormatRequest {
        container,
        output_extension,
        video,
        audio,
        include_video,
        include_audio,
    } = *request;
    let container = match (container, output_extension) {
        (Some(container), Some(extension)) => {
            if include_video && names(container.audio_only_extensions(), extension) {
                return Err(ContainerError::AudioOnlyExtension {
                    container,
                    extension: extension.to_owned(),
                });
            }
            if !names(&accepted_extensions(container, include_video), extension) {
                return Err(ContainerError::ExtensionMismatch {
                    container,
                    extension: extension.to_owned(),
                    include_video,
                });
            }
            container
        }
        (Some(container), None) => container,
        (None, Some(extension)) => match Container::from_extension(extension) {
            Some(container) => container,
            None => match Container::from_audio_only_extension(extension) {
                Some(container) if !include_video => container,
                Some(container) => {
                    return Err(ContainerError::AudioOnlyExtension {
                        container,
                        extension: extension.to_owned(),
                    });
                }
                None => {
                    return Err(ContainerError::UnknownExtension {
                        extension: (!extension.is_empty()).then(|| extension.to_owned()),
                        include_video,
                    });
                }
            },
        },
        (None, None) => Container::Mp4,
    };
    if !include_video && !include_audio {
        return Err(ContainerError::NoStreams);
    }
    let video = if include_video {
        let Some(default) = container.default_video_codec() else {
            return Err(ContainerError::VideoNotOffered { container });
        };
        let video = video.unwrap_or(default);
        if !container.offers_video(video) {
            return Err(ContainerError::VideoCodecNotOffered {
                container,
                codec: video,
            });
        }
        Some(video)
    } else {
        if let Some(codec) = video {
            return Err(ContainerError::VideoCodecWithoutVideo { codec });
        }
        None
    };
    let audio = audio.unwrap_or(container.default_audio_codec());
    if !container.offers_audio(audio) {
        return Err(ContainerError::AudioCodecNotOffered {
            container,
            codec: audio,
        });
    }
    Ok(ExportFormat {
        container,
        video,
        audio,
    })
}

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