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
//! The `export` request and the format it resolves to.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use alpha2_engine::{AudioTap, MAX_AUDIO_TAPS, TapPoint};
use alpha2_media::{
    Container, ContainerError, ExportAudioCodec, ExportFormat, ExportFormatRequest, VideoCodec,
};
use alpha2_model::AudioNodeRef;
use serde::Deserialize;
use serde_json::Value;

use super::RequestError;
use super::media::{ExportMedia, ProjectJson, ProxyRequest, output_key};
use super::settings::{
    AudioQualityRequest, ExportStrategy, LoudnessRequest, MemoryRequest, RateRequest,
    RenderCacheRequest, VideoInputPolicy, VideoQualityRequest,
};
use crate::codecs::{NativeAudioCodec, NativeVideoCodec};
use crate::effect_request::EffectRequest;

/// An `export` request.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "each is a field of the protocol's request"
)]
pub struct ExportRequest {
    /// Always the protocol version.
    #[serde(rename = "protocolVersion")]
    pub protocol_version: u32,
    /// The caller's id for the request.
    #[serde(rename = "requestId")]
    pub request_id: String,
    /// Read by the dispatcher.
    #[serde(default)]
    pub operation: serde::de::IgnoredAny,
    /// The frame's attachment list, read with the frame.
    #[serde(default)]
    pub attachments: serde::de::IgnoredAny,
    /// The project to export.
    pub project: ProjectJson,
    /// Originals by source ID.
    pub assets: HashMap<String, super::MediaLocation>,
    /// Proxies by source ID.
    #[serde(default)]
    pub proxies: HashMap<String, Vec<ProxyRequest>>,
    /// Image sequence frames by source ID, in project order; `null` where the sequence has a gap.
    #[serde(default)]
    pub frames: HashMap<String, Vec<Option<PathBuf>>>,
    /// Files an SVG's `<image href>` or a Lottie file's image assets name, by source ID and then by
    /// locator.
    #[serde(default)]
    pub resources: HashMap<String, HashMap<String, super::MediaLocation>>,
    /// Whether a remote original whose project records a content hash is read whole and hashed.
    #[serde(rename = "remoteContentHash", default)]
    pub remote_content_hash: super::RemoteContentHash,
    /// Originals unless the caller asks for proxies.
    #[serde(default)]
    pub media: ExportMedia,
    /// Lookup tables of runtime effects, by name.
    #[serde(rename = "effectAssets", default)]
    pub effect_assets: HashMap<String, PathBuf>,
    /// Font files, in fallback order.
    #[serde(rename = "fonts", default)]
    pub font_files: Vec<PathBuf>,
    /// Runtime effects the project's clips name.
    #[serde(default)]
    pub effects: Vec<EffectRequest>,
    /// The first tick of the range.
    #[serde(rename = "startTicks")]
    pub start_ticks: i64,
    /// The tick after the range.
    #[serde(rename = "endTicks")]
    pub end_ticks: i64,
    /// The output's frame rate.
    #[serde(rename = "frameRate")]
    pub frame_rate: RateRequest,
    /// Whether the export has sound; true by default, as in the CLI, `@alpha2-sh/node` and the
    /// browser exporter.
    #[serde(rename = "includeAudio", default = "included_by_default")]
    pub include_audio: bool,
    /// Whether the export has pictures; `false` writes the mix alone, with no renderer, GPU device
    /// or video encoder.
    #[serde(rename = "includeVideo", default = "included_by_default")]
    pub include_video: bool,
    /// Tracks and buses each written as its own audio file beside the output.
    #[serde(default)]
    pub stems: Vec<StemRequest>,
    /// The container; the one `output`'s extension names when absent.
    #[serde(default)]
    pub container: Option<Container>,
    /// The video codec; the container's default when absent.
    #[serde(rename = "videoCodec", default)]
    pub video_codec: Option<VideoCodec>,
    /// Draw without the project background and write an alpha plane (VP9 in `WebM` or Matroska,
    /// `ProRes` 4444).
    #[serde(default)]
    pub alpha: bool,
    /// 8 or 10; the codec's own when absent (10 for `ProRes`, else 8).
    #[serde(rename = "bitDepth", default)]
    pub bit_depth: Option<u8>,
    /// An encoder by `FFmpeg` name instead of the host's choice.
    #[serde(rename = "videoEncoder", default)]
    pub video_encoder: Option<String>,
    /// Whether frames may reach the encoder without a readback.
    #[serde(rename = "inputPolicy", default)]
    pub input_policy: VideoInputPolicy,
    /// Whether the export may copy packets instead of rendering.
    #[serde(default)]
    pub strategy: ExportStrategy,
    /// The video rate.
    #[serde(rename = "videoQuality", default)]
    pub video_quality: VideoQualityRequest,
    /// The audio codec; the container's default when absent.
    #[serde(rename = "audioCodec", default)]
    pub audio_codec: Option<ExportAudioCodec>,
    /// The audio rate.
    #[serde(rename = "audioQuality", default)]
    pub audio_quality: AudioQualityRequest,
    /// A loudness target; without one the mix keeps its own loudness.
    #[serde(default)]
    pub loudness: Option<LoudnessRequest>,
    /// Frames baked in an earlier export, reused where they match.
    #[serde(rename = "renderCache", default, deserialize_with = "render_cache")]
    pub render_cache: Option<RenderCacheRequest>,
    /// Byte budgets; absent ones fall back to the environment, then the host's defaults.
    #[serde(default)]
    pub memory: MemoryRequest,
    /// The file written.
    pub output: PathBuf,
    /// Replace a regular file at `output` once the export is whole; otherwise an existing output
    /// is refused.
    #[serde(default)]
    pub overwrite: bool,
}

/// One stem of an export: a track's or a bus's signal written as its own audio file over the
/// export's range, read before the master (no master effects, gain, normalization or limiter).
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct StemRequest {
    /// The track or bus.
    pub node: AudioNodeRef,
    /// Where its signal is read; after the fader when absent.
    #[serde(default)]
    pub tap: TapPoint,
    /// The file written; its extension names the container.
    pub output: PathBuf,
    /// The audio codec; the container's default when absent.
    #[serde(rename = "audioCodec", default)]
    pub audio_codec: Option<ExportAudioCodec>,
    /// The audio rate; the export's `audioQuality` when absent.
    #[serde(rename = "audioQuality", default)]
    pub audio_quality: Option<AudioQualityRequest>,
}

impl StemRequest {
    /// The tap this stem is written from.
    #[must_use]
    pub fn audio_tap(&self) -> AudioTap {
        AudioTap {
            node: self.node.clone(),
            point: self.tap,
        }
    }

    /// The container `output`'s extension names and the codec it is written in.
    ///
    /// # Errors
    /// `INVALID_INPUT` naming what does not resolve.
    pub fn format(&self) -> Result<AudioFileFormat, RequestError> {
        AudioFileFormat::resolve(None, &self.output, self.audio_codec)
    }
}

impl ExportRequest {
    /// Cross-field rules no single setting's parse can see, checked by the protocol and the CLI
    /// before a device or encoder opens.
    ///
    /// # Errors
    /// `INVALID_REQUEST` for a URL in a path field; `INVALID_INPUT` naming the rule: loudness and
    /// stems need `includeAudio`, an export without video needs it too and names nothing of a
    /// video stream, the container and codecs must resolve ([`Self::format`],
    /// [`Self::audio_format`]), and every stem must resolve and write a file of its own.
    pub fn check(&self) -> Result<(), RequestError> {
        super::refuse_urls(
            &self.proxies,
            &self.frames,
            &self.effect_assets,
            &self.font_files,
        )?;
        super::refuse_url("output", &self.output)?;
        if let Some(cache) = &self.render_cache {
            super::refuse_url("renderCache.directory", &cache.directory)?;
        }
        for stem in &self.stems {
            super::refuse_url("a stem's output", &stem.output)?;
        }
        if self.loudness.is_some() && !self.include_audio {
            return Err(RequestError::invalid_input(
                "loudness normalizes the export's audio and needs includeAudio: true",
            ));
        }
        if !self.include_video && !self.include_audio {
            return Err(RequestError::invalid_input(
                "includeVideo: false writes the export's audio alone and needs includeAudio: true",
            ));
        }
        if !self.stems.is_empty() && !self.include_audio {
            return Err(RequestError::invalid_input(
                "stems are written from the export's audio and need includeAudio: true",
            ));
        }
        if self.include_video {
            self.format()?;
        } else {
            self.refuse_video_settings()?;
            self.audio_format()?;
        }
        self.check_stems()
    }

    fn refuse_video_settings(&self) -> Result<(), RequestError> {
        let named = [
            ("alpha", self.alpha),
            ("bitDepth", self.bit_depth.is_some()),
            ("videoEncoder", self.video_encoder.is_some()),
        ];
        match named.into_iter().find(|(_, named)| *named) {
            Some((field, _)) => Err(RequestError::invalid_input(format!(
                "{field} describes the export's video, and includeVideo is false"
            ))),
            None => Ok(()),
        }
    }

    fn check_stems(&self) -> Result<(), RequestError> {
        if self.stems.len() > MAX_AUDIO_TAPS {
            return Err(RequestError::invalid_input(format!(
                "stems has {} entries; an export writes at most {MAX_AUDIO_TAPS}",
                self.stems.len()
            )));
        }
        let mut outputs = HashMap::from([(output_key(&self.output), &self.output)]);
        for (index, stem) in self.stems.iter().enumerate() {
            if stem.output.as_os_str().is_empty() {
                return Err(RequestError::invalid_input(format!(
                    "stems[{index}].output must not be empty"
                )));
            }
            stem.format().map_err(|error| {
                RequestError::invalid_input(format!("stems[{index}].{}", error.message))
            })?;
            if let Some(earlier) = outputs.insert(output_key(&stem.output), &stem.output) {
                return Err(RequestError::invalid_input(format!(
                    "stems[{index}].output: two outputs of the export write one file: {} and {}",
                    earlier.display(),
                    stem.output.display()
                )));
            }
        }
        Ok(())
    }

    /// The format of an export with video: `container` must agree with `output`'s extension, and
    /// each named codec must be offered by the container; unnamed ones take its default.
    ///
    /// # Errors
    /// `INVALID_INPUT` naming what does not resolve.
    pub fn format(&self) -> Result<ResolvedFormat, RequestError> {
        let bit_depth = self
            .bit_depth
            .map(|bits| {
                alpha2_media::BitDepth::from_bits(bits).ok_or_else(|| {
                    RequestError::invalid_input(format!("bitDepth: {bits} is not 8 or 10"))
                })
            })
            .transpose()?;
        ResolvedFormat::resolve(
            self.container,
            &self.output,
            self.video_codec,
            self.audio_codec,
        )?
        .with_pixels(alpha2_media::OutputPixels {
            bit_depth,
            alpha: self.alpha,
        })
    }

    /// The format of an export without video (`includeVideo: false`): `output` may also end in
    /// one of the container's audio-only extensions, and no video codec is named.
    ///
    /// # Errors
    /// `INVALID_INPUT` naming what does not resolve.
    pub fn audio_format(&self) -> Result<AudioFileFormat, RequestError> {
        resolve(&ExportFormatRequest {
            container: self.container,
            output_extension: Some(extension_of(&self.output)?),
            video: self.video_codec,
            audio: self.audio_codec,
            include_video: false,
            include_audio: true,
        })
        .map(|format| AudioFileFormat {
            container: format.container,
            codec: format.audio,
        })
    }
}

/// The container and codec of a file that holds sound only: an export without video, or a stem.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct AudioFileFormat {
    /// The output container.
    pub container: Container,
    /// The audio codec.
    pub codec: ExportAudioCodec,
}

impl AudioFileFormat {
    /// # Errors
    /// `INVALID_INPUT` with the policy's reason, naming `output` or `audioCodec`.
    pub fn resolve(
        container: Option<Container>,
        output: &Path,
        codec: Option<ExportAudioCodec>,
    ) -> Result<Self, RequestError> {
        resolve(&ExportFormatRequest {
            container,
            output_extension: Some(extension_of(output)?),
            video: None,
            audio: codec,
            include_video: false,
            include_audio: true,
        })
        .map(|format| Self {
            container: format.container,
            codec: format.audio,
        })
    }
}

/// The container, codecs and pixel layout an export with video writes, resolved once at the
/// host's edge from the engine's policy ([`alpha2_media::resolve_export_format`]).
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ResolvedFormat {
    /// The output container.
    pub container: Container,
    /// The video encoder family.
    pub video: NativeVideoCodec,
    /// The audio encoder family.
    pub audio: NativeAudioCodec,
    /// The output pixel layout ([`alpha2_media::resolve_pixels`]).
    pub pixels: alpha2_media::PixelLayout,
}

impl ResolvedFormat {
    /// # Errors
    /// `INVALID_INPUT` with the policy's reason.
    pub fn resolve(
        container: Option<Container>,
        output: &Path,
        video: Option<VideoCodec>,
        audio: Option<ExportAudioCodec>,
    ) -> Result<Self, RequestError> {
        let format = resolve(&ExportFormatRequest {
            container,
            output_extension: Some(extension_of(output)?),
            video,
            audio,
            include_video: true,
            include_audio: true,
        })?;
        let Some(video) = format.video else {
            return Err(RequestError::invalid_input(container_message(
                &ContainerError::VideoNotOffered {
                    container: format.container,
                },
            )));
        };
        let audio = format.audio.encoded().ok_or_else(|| {
            RequestError::invalid_input(format!(
                "audioCodec: {} is written to an output without video",
                format.audio
            ))
        })?;
        Ok(Self {
            container: format.container,
            video: NativeVideoCodec::from_model(video),
            audio: NativeAudioCodec::from_model(audio),
            pixels: alpha2_media::resolve_pixels(
                video,
                format.container,
                alpha2_media::OutputPixels::default(),
            )
            .map_err(|error| RequestError::invalid_input(format!("videoCodec: {error}")))?,
        })
    }

    /// # Errors
    /// `INVALID_INPUT` naming `alpha` or `bitDepth` when the codec cannot be written so in the
    /// container.
    pub fn with_pixels(self, pixels: alpha2_media::OutputPixels) -> Result<Self, RequestError> {
        let layout = alpha2_media::resolve_pixels(self.video.model(), self.container, pixels)
            .map_err(|error| {
                let field = match error {
                    alpha2_media::OutputPixelsError::BitDepthUnsupported { .. } => "bitDepth",
                    _ => "alpha",
                };
                RequestError::invalid_input(format!("{field}: {error}"))
            })?;
        Ok(Self {
            pixels: layout,
            ..self
        })
    }
}

fn extension_of(output: &Path) -> Result<&str, RequestError> {
    output
        .extension()
        .map_or(Some(""), std::ffi::OsStr::to_str)
        .ok_or_else(|| RequestError::invalid_input("output path is not UTF-8"))
}

fn resolve(request: &ExportFormatRequest<'_>) -> Result<ExportFormat, RequestError> {
    alpha2_media::resolve_export_format(request)
        .map_err(|error| RequestError::invalid_input(container_message(&error)))
}

fn container_message(error: &ContainerError) -> String {
    format!("{}: {error}", error.field())
}

/// Checked before the typed parse so a bad value is reported as `INVALID_INPUT` naming the field,
/// not as a malformed request.
pub(super) fn check_settings(
    setting: &dyn Fn(&str) -> Result<Option<Value>, RequestError>,
) -> Result<(), RequestError> {
    if let Some(quality) = setting("videoQuality")? {
        VideoQualityRequest::from_json(&quality).map_err(RequestError::invalid_input)?;
    }
    if let Some(quality) = setting("audioQuality")? {
        AudioQualityRequest::from_json(&quality).map_err(RequestError::invalid_input)?;
    }
    if let Some(cache) = setting("renderCache")?.filter(|value| !value.is_null()) {
        RenderCacheRequest::from_json(&cache).map_err(RequestError::invalid_input)?;
    }
    if let Some(loudness) = setting("loudness")?.filter(|value| !value.is_null()) {
        LoudnessRequest::from_json(&loudness).map_err(RequestError::invalid_input)?;
    }
    // A budget the caller sets is its input too: a misspelled or mistyped field names itself.
    if let Some(alpha) = setting("alpha")?
        && !alpha.is_boolean()
    {
        return Err(RequestError::invalid_input(format!(
            "alpha: {alpha} is not true or false"
        )));
    }
    if let Some(bits) = setting("bitDepth")?.filter(|value| !value.is_null())
        && !matches!(bits.as_u64(), Some(8 | 10))
    {
        return Err(RequestError::invalid_input(format!(
            "bitDepth: {bits} is not 8 or 10"
        )));
    }
    if let Some(memory) = setting("memory")? {
        serde_json::from_value::<MemoryRequest>(memory)
            .map_err(|error| RequestError::invalid_input(format!("memory: {error}")))?;
    }
    check_format_names(setting)
}

/// An unknown `container`, `videoCodec` or `audioCodec` is `INVALID_INPUT` naming the field, not a
/// malformed request.
fn check_format_names(
    setting: &dyn Fn(&str) -> Result<Option<Value>, RequestError>,
) -> Result<(), RequestError> {
    if let Some(container) = setting("container")?.filter(|value| !value.is_null()) {
        serde_json::from_value::<Container>(container.clone()).map_err(|_| {
            RequestError::invalid_input(format!(
                "container: {}",
                ContainerError::Unknown(container.to_string().trim_matches('"').to_owned())
            ))
        })?;
    }
    for (field, names) in [
        ("videoCodec", "h264, hevc, vp9, av1, mpeg4-part2, prores"),
        ("audioCodec", "aac, opus, pcm-f32, pcm-s24, pcm-s16"),
    ] {
        if let Some(codec) = setting(field)?.filter(|value| !value.is_null()) {
            let known = codec.as_str().is_some_and(|name| {
                if field == "videoCodec" {
                    name.parse::<VideoCodec>().is_ok()
                } else {
                    name.parse::<ExportAudioCodec>().is_ok()
                }
            });
            if !known {
                return Err(RequestError::invalid_input(format!(
                    "{field}: unknown codec {codec}; expected one of {names}"
                )));
            }
        }
    }
    Ok(())
}

const fn included_by_default() -> bool {
    true
}

fn render_cache<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<RenderCacheRequest>, D::Error> {
    let value = Option::<Value>::deserialize(deserializer)?;
    value
        .filter(|value| !value.is_null())
        .map(|value| RenderCacheRequest::from_json(&value).map_err(serde::de::Error::custom))
        .transpose()
}