alpha2-host-core 0.6.2

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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! Loads extractor plugins. The trust policy picks a manifest's artifact, which is checked against
//! its hash and loaded as an [`Extractor`] the session drives like any other. wasm modules run in
//! wasmtime, sandboxed, with capped memory and bounded calls. Native libraries run in the process,
//! and only for plugins the caller allows.
//!
//! The caller fetches: [`load`] asks a [`Fetch`] for each file by URL and hash.

mod native;
#[cfg(test)]
mod silence_tests;
#[cfg(test)]
mod tests;
mod wasm;

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

use alpha2_engine::extract::{
    ArtifactKind, AudioInput, Descriptor, Emitter, Extractor, ExtractorError, ManifestError,
    PassInfo, PluginArtifact, PluginManifest, RunContext, VideoFormat, VideoInput, WASM_TARGET,
};
use alpha2_media::CancelToken;
use alpha2_model::{DataInterval, DataWord, MAX_DATA_CHANNELS, MAX_DATA_LABEL_BYTES, MadeByPlugin};
use alpha2_plugin_abi::records::{Limits, Record, records};
use alpha2_plugin_abi::{direction, status, video_format};
use alpha2_time::MediaTime;
use sha2::{Digest, Sha256};

/// The error codes plugins fail with, the same on every surface.
pub mod codes {
    /// A manifest, artifact or resource could not be fetched.
    pub const FETCH_FAILED: &str = "PLUGIN_FETCH_FAILED";
    /// A file's SHA-256 or length differs from what the manifest pins.
    pub const HASH_MISMATCH: &str = "PLUGIN_HASH_MISMATCH";
    /// The plugin implements an ABI this build does not.
    pub const ABI_UNSUPPORTED: &str = "PLUGIN_ABI_UNSUPPORTED";
    /// No artifact runs here; the message lists the targets the manifest offers.
    pub const NO_ARTIFACT: &str = "PLUGIN_NO_ARTIFACT";
    /// Only a native artifact runs here, and the caller did not allow native code.
    pub const NATIVE_REFUSED: &str = "PLUGIN_NATIVE_REFUSED";
    /// The host's plugin policy refuses the plugin or one of its files.
    pub const REFUSED: &str = "PLUGIN_REFUSED";
    /// The artifact's descriptor differs from the manifest's.
    pub const DESCRIPTOR_MISMATCH: &str = "PLUGIN_DESCRIPTOR_MISMATCH";
    /// The wasm module uses relaxed SIMD, threads, shared memory, more than one memory or 64-bit
    /// memory, or imports something else.
    pub const UNSUPPORTED_FEATURE: &str = "PLUGIN_UNSUPPORTED_FEATURE";
    /// The manifest is not one, or the artifact did not load.
    pub const LOAD_FAILED: &str = "PLUGIN_LOAD_FAILED";
    /// A wasm trap, or a native panic caught at the boundary.
    pub const TRAPPED: &str = "PLUGIN_TRAPPED";
    /// The wasm module ran past its memory cap or table bound, or a call past its deadline.
    pub const LIMIT: &str = "PLUGIN_LIMIT";
}

/// The code of a load or call that stopped because the caller's cancel token was set. It is not a
/// plugin code: the request ends as cancelled.
pub const CANCELLED: &str = "CANCELLED";

/// Every plugin error code.
pub const PLUGIN_CODES: [&str; 11] = [
    codes::FETCH_FAILED,
    codes::HASH_MISMATCH,
    codes::ABI_UNSUPPORTED,
    codes::NO_ARTIFACT,
    codes::NATIVE_REFUSED,
    codes::REFUSED,
    codes::DESCRIPTOR_MISMATCH,
    codes::UNSUPPORTED_FEATURE,
    codes::LOAD_FAILED,
    codes::TRAPPED,
    codes::LIMIT,
];

/// Why a plugin did not load.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PluginError {
    /// One of [`codes`].
    pub code: &'static str,
    /// What went wrong.
    pub message: String,
}

impl PluginError {
    /// An error with `code`.
    pub fn new(code: &'static str, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

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

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

impl From<ManifestError> for PluginError {
    fn from(error: ManifestError) -> Self {
        let code = match error {
            ManifestError::UnsupportedAbi(_) => codes::ABI_UNSUPPORTED,
            _ => codes::LOAD_FAILED,
        };
        Self::new(code, error.to_string())
    }
}

/// Reads and checks a manifest.
///
/// # Errors
/// `PLUGIN_ABI_UNSUPPORTED` for another ABI, `PLUGIN_LOAD_FAILED` for a manifest that is not one.
pub fn parse_manifest(text: &str) -> Result<PluginManifest, PluginError> {
    PluginManifest::from_json(text).map_err(PluginError::from)
}

/// What the caller allows a plugin. A program that calls [`load`] is its own operator: it decides
/// here what the `alpha2-host` operator decides with its `serve` flags.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Policy {
    /// Native code runs with the process's rights; refused unless allowed.
    pub allow_native: bool,
    /// The wasm artifact even where a native one is allowed.
    pub force_wasm: bool,
    /// The most linear memory a wasm module may have, in bytes; at most [`MAX_MEMORY_BYTES`].
    pub memory_bytes: u64,
    /// The longest one wasm call may run.
    pub call_deadline: Duration,
}

/// Linear memory a wasm plugin may grow to when the caller sets no cap.
pub const DEFAULT_MEMORY_BYTES: u64 = 1024 * 1024 * 1024;
/// The most memory a wasm plugin may have, the span its `i32` offsets address; a larger cap is
/// taken as this.
pub const MAX_MEMORY_BYTES: u64 = 1 << 31;
/// How long one wasm call may run when the caller sets no deadline.
pub const DEFAULT_CALL_DEADLINE: Duration = Duration::from_secs(300);

impl Default for Policy {
    fn default() -> Self {
        Self {
            allow_native: false,
            force_wasm: false,
            memory_bytes: DEFAULT_MEMORY_BYTES,
            call_deadline: DEFAULT_CALL_DEADLINE,
        }
    }
}

/// The Rust target triple this build runs on, as manifests name native artifacts.
pub const TARGET: &str = env!("ALPHA2_HOST_CORE_TARGET");

/// Picks the native artifact for `target` when the policy allows native code, else the wasm one.
///
/// # Errors
/// `PLUGIN_NATIVE_REFUSED` when only a native artifact runs here and native code is not allowed,
/// `PLUGIN_NO_ARTIFACT`, listing the offered targets, when none runs here.
pub fn select<'m>(
    manifest: &'m PluginManifest,
    policy: &Policy,
    target: &str,
) -> Result<&'m PluginArtifact, PluginError> {
    let native = manifest.artifact(target, ArtifactKind::Cdylib);
    let wasm = manifest.artifact(WASM_TARGET, ArtifactKind::Wasm);
    match (native, wasm) {
        (Some(native), _) if policy.allow_native && !policy.force_wasm => Ok(native),
        (_, Some(wasm)) => Ok(wasm),
        (Some(_), None) if policy.force_wasm => Err(PluginError::new(
            codes::NO_ARTIFACT,
            format!(
                "{} has no wasm artifact; it offers {target} only",
                manifest.id
            ),
        )),
        (Some(_), None) => Err(PluginError::new(
            codes::NATIVE_REFUSED,
            format!(
                "{} runs here only as native code, which has the process's rights; allow native \
                 code for this plugin to run it",
                manifest.id
            ),
        )),
        (None, None) => {
            let offered = manifest
                .artifacts
                .iter()
                .map(|artifact| format!("{} ({:?})", artifact.target, artifact.kind).to_lowercase())
                .collect::<Vec<_>>();
            Err(PluginError::new(
                codes::NO_ARTIFACT,
                format!(
                    "{} has no artifact for {target} and no wasm artifact; it offers {}",
                    manifest.id,
                    offered.join(", ")
                ),
            ))
        }
    }
}

/// Hex SHA-256 of `bytes`.
#[must_use]
pub fn sha256_hex(bytes: &[u8]) -> String {
    Sha256::digest(bytes)
        .iter()
        .fold(String::new(), |mut hex, byte| {
            use fmt::Write;
            let _ = write!(hex, "{byte:02x}");
            hex
        })
}

/// # Errors
/// `PLUGIN_HASH_MISMATCH` when `bytes` are not the `size` bytes with the pinned `sha256`. Only
/// for a `local` file does the message state the length or digest found.
pub fn verify(
    bytes: &[u8],
    sha256: &str,
    size: u64,
    what: &str,
    local: bool,
) -> Result<(), PluginError> {
    let length_differs = bytes.len() as u64 != size;
    if !length_differs && sha256_hex(bytes) == sha256 {
        return Ok(());
    }
    let message = if !local {
        format!("{what} does not match the length and SHA-256 the manifest pins")
    } else if length_differs {
        format!("{what} is {} bytes; the manifest pins {size}", bytes.len())
    } else {
        format!(
            "{what} has SHA-256 {}; the manifest pins {sha256}",
            sha256_hex(bytes)
        )
    };
    Err(PluginError::new(codes::HASH_MISMATCH, message))
}

/// A file a [`Fetch`] supplied.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Fetched {
    /// Where its bytes are.
    pub path: PathBuf,
    /// A local file the caller named; false for a download, whose content a mismatch message
    /// must not describe.
    pub local: bool,
}

/// Where a plugin's files come from.
pub trait Fetch {
    /// The file a manifest's `url` names, a path under the manifest's directory or an `https:`
    /// URL. The loader checks its bytes against `sha256` and `bytes` itself.
    ///
    /// # Errors
    /// `PLUGIN_FETCH_FAILED`, or `PLUGIN_HASH_MISMATCH` when the fetcher checks too.
    fn fetch(&mut self, url: &str, sha256: &str, bytes: u64) -> Result<Fetched, PluginError>;

    /// The file to load for the native artifact read from `verified`, whose checked `bytes` have
    /// the pinned `sha256`. Called only when this process has not loaded that artifact yet; the
    /// library then stays loaded until the process exits. A host loads its own copy of the bytes
    /// here, so the file it checked cannot be replaced before the load.
    ///
    /// # Errors
    /// `PLUGIN_LOAD_FAILED` when it cannot be prepared.
    fn prepare_native(
        &mut self,
        verified: &Path,
        bytes: &[u8],
        sha256: &str,
    ) -> Result<PathBuf, PluginError> {
        let _ = (bytes, sha256);
        Ok(verified.to_path_buf())
    }
}

fn read_verified(
    fetch: &mut dyn Fetch,
    url: &str,
    sha256: &str,
    size: u64,
) -> Result<(PathBuf, Vec<u8>), PluginError> {
    use std::io::Read;
    let Fetched { path, local } = fetch.fetch(url, sha256, size)?;
    let failed = |error: std::io::Error| {
        PluginError::new(codes::FETCH_FAILED, format!("{}: {error}", path.display()))
    };
    let file = std::fs::File::open(&path).map_err(failed)?;
    let length = file.metadata().map_err(failed)?.len();
    let mut bytes = Vec::with_capacity(usize::try_from(length.min(size)).unwrap_or(0));
    file.take(size.saturating_add(1))
        .read_to_end(&mut bytes)
        .map_err(failed)?;
    if bytes.len() as u64 > size {
        let message = if local {
            format!("{url} is longer than the {size} bytes the manifest pins")
        } else {
            format!("{url} does not match the length and SHA-256 the manifest pins")
        };
        return Err(PluginError::new(codes::HASH_MISMATCH, message));
    }
    verify(&bytes, sha256, size, url, local)?;
    Ok((path, bytes))
}

/// The longest plugin log line written; the rest is cut.
const MAX_LOG_BYTES: usize = 2048;
/// Log text one run may write; later lines are dropped after one notice.
const LOG_BUDGET_BYTES: usize = 64 * 1024;
/// The longest `fail` message kept; the rest is cut.
const MAX_FAIL_BYTES: usize = 4096;

/// The first `max` of `bytes` as UTF-8 text, without a character the cut splits.
fn bounded_text(bytes: &[u8], max: usize) -> String {
    let mut kept = &bytes[..bytes.len().min(max)];
    if kept.len() < bytes.len()
        && let Err(error) = std::str::from_utf8(kept)
        && error.error_len().is_none()
    {
        kept = &kept[..error.valid_up_to()];
    }
    String::from_utf8_lossy(kept).into_owned()
}

/// What is left of a run's log budget.
#[derive(Debug)]
struct LogBudget {
    remaining: usize,
    exhausted: bool,
}

impl Default for LogBudget {
    fn default() -> Self {
        Self {
            remaining: LOG_BUDGET_BYTES,
            exhausted: false,
        }
    }
}

impl LogBudget {
    /// The line to write for a plugin's `message`, cut to [`MAX_LOG_BYTES`]; once the budget is
    /// spent, one notice and then nothing.
    fn line(&mut self, message: &[u8]) -> Option<String> {
        if self.exhausted {
            return None;
        }
        let text = bounded_text(message, MAX_LOG_BYTES);
        if text.len() > self.remaining {
            self.exhausted = true;
            return Some(format!(
                "the plugin logged more than {LOG_BUDGET_BYTES} bytes; its further lines are dropped"
            ));
        }
        self.remaining -= text.len();
        Some(text)
    }

    /// Writes a plugin's diagnostic to standard error, where host diagnostics go; a closed stream
    /// drops it.
    fn log(&mut self, message: &[u8]) {
        if let Some(line) = self.line(message) {
            alpha2_os::diagnostic!("plugin: {line}");
        }
    }
}

/// What one plugin call emitted, or why it failed.
type Call = Result<Vec<Record>, ExtractorError>;

/// How the loader calls a plugin, whichever transport it came through.
trait Transport {
    fn describe(&mut self) -> Result<String, PluginError>;
    fn begin(&mut self, context: &[u8]) -> Call;
    fn pass(&mut self, pass: u32, direction: u32) -> Call;
    fn video(&mut self, time: i64, width: u32, height: u32, format: u32, data: &[u8]) -> Call;
    fn audio(&mut self, block: &AudioInput) -> Call;
    fn end(&mut self) -> Call;
}

/// The most items a declared output takes in one call.
#[derive(Clone, Debug, PartialEq, Eq)]
struct OutputCap {
    name: String,
    items: usize,
}

fn output_caps(descriptor: &Descriptor) -> Vec<OutputCap> {
    descriptor
        .outputs
        .iter()
        .map(|output| OutputCap {
            name: output.name.clone(),
            items: output.max_items(),
        })
        .collect()
}

/// Bounds on one emitted record: the widest sample and the longest text any output takes.
const RECORD_LIMITS: Limits = Limits {
    max_values: MAX_DATA_CHANNELS * 4,
    max_text_bytes: MAX_DATA_LABEL_BYTES,
};

/// What a call's emit and fail callbacks left, turned into the call's outcome.
#[derive(Debug, Default)]
struct Collected {
    records: Vec<Record>,
    /// Records each output took in this call, by output index.
    counts: Vec<usize>,
    /// Why an emit of this call was refused; later emits of the call are refused at once.
    refusal: Option<String>,
    failure: Option<String>,
}

impl Collected {
    fn outcome(&mut self, status: i32) -> Call {
        let collected = std::mem::take(self);
        if let Some(reason) = collected.refusal {
            return Err(ExtractorError::with_code("INVALID_EMIT", reason));
        }
        match status {
            status::OK => Ok(collected.records),
            status::FAILED => {
                Err(ExtractorError::new(collected.failure.unwrap_or_else(
                    || "the plugin failed without saying why".to_owned(),
                )))
            }
            status::TRAPPED => Err(ExtractorError::with_code(
                codes::TRAPPED,
                "the plugin panicked; it caught the panic at its boundary",
            )),
            other => Err(ExtractorError::with_code(
                codes::TRAPPED,
                format!("the plugin returned the unknown status {other}"),
            )),
        }
    }

    /// Takes a batch whole, or refuses it and keeps nothing of it.
    fn emit(&mut self, batch: &[u8], caps: &[OutputCap]) -> i32 {
        if self.refusal.is_some() {
            return status::FAILED;
        }
        let start = self.records.len();
        self.counts.resize(caps.len(), 0);
        for record in records(batch, RECORD_LIMITS) {
            let refusal = match record {
                Err(error) => Some(error.to_string()),
                Ok(record) => {
                    let output = usize::from(record.output());
                    match (caps.get(output), self.counts.get_mut(output)) {
                        (Some(cap), Some(count)) if *count < cap.items => {
                            *count += 1;
                            self.records.push(record);
                            None
                        }
                        (Some(cap), _) => Some(format!(
                            "the plugin emitted more than {} items to output {} in one call",
                            cap.items, cap.name
                        )),
                        _ => Some(format!(
                            "the plugin emitted to output {output}, which it does not declare"
                        )),
                    }
                }
            };
            if let Some(reason) = refusal {
                self.records.truncate(start);
                self.refusal = Some(reason);
                return status::FAILED;
            }
        }
        status::OK
    }
}

/// A loaded plugin, ready to run as an extractor.
pub struct PluginExtractor {
    descriptor: Descriptor,
    params: serde_json::Map<String, serde_json::Value>,
    plugin: MadeByPlugin,
    transport: Box<dyn Transport>,
    native: bool,
}

impl fmt::Debug for PluginExtractor {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PluginExtractor")
            .field("id", &self.descriptor.id)
            .field("plugin", &self.plugin)
            .finish_non_exhaustive()
    }
}

/// Loads the artifact `policy` picks from `manifest`, fetching it and every resource through
/// `fetch`, to run with `params`. Once `cancel` is set, the load stops before the next file, and
/// a wasm call of the plugin it returns stops within about 50 ms; a module compile and a native
/// call run to their end.
///
/// # Errors
/// A [`PluginError`] for the first check that fails, [`CANCELLED`] once `cancel` is set.
pub fn load(
    manifest: &PluginManifest,
    params: serde_json::Map<String, serde_json::Value>,
    policy: &Policy,
    fetch: &mut dyn Fetch,
    cancel: &CancelToken,
) -> Result<PluginExtractor, PluginError> {
    let artifact = select(manifest, policy, TARGET)?;
    let stopped = || {
        if cancel.is_cancelled() {
            Err(PluginError::new(CANCELLED, "the plugin load was cancelled"))
        } else {
            Ok(())
        }
    };
    let mut resources = HashMap::new();
    for resource in &manifest.resources {
        stopped()?;
        let (_, bytes) = read_verified(fetch, &resource.url, &resource.sha256, resource.bytes)?;
        resources.insert(resource.name.clone(), bytes);
    }
    stopped()?;
    let (path, bytes) = read_verified(fetch, &artifact.url, &artifact.sha256, artifact.bytes)?;
    let caps = output_caps(&manifest.descriptor);
    let native = artifact.kind == ArtifactKind::Cdylib;
    let mut transport: Box<dyn Transport> = match artifact.kind {
        ArtifactKind::Wasm => Box::new(wasm::WasmTransport::new(
            &manifest.id,
            &bytes,
            &artifact.sha256,
            resources,
            caps,
            policy,
            cancel.clone(),
        )?),
        ArtifactKind::Cdylib => Box::new(native::NativeTransport::new(
            &artifact.sha256,
            || fetch.prepare_native(&path, &bytes, &artifact.sha256),
            resources,
            caps,
        )?),
        ArtifactKind::Staticlib => {
            return Err(PluginError::new(
                codes::NO_ARTIFACT,
                "a static library is linked at build time, not loaded",
            ));
        }
    };
    let described: Descriptor = serde_json::from_str(&transport.describe()?).map_err(|error| {
        PluginError::new(
            codes::DESCRIPTOR_MISMATCH,
            format!("the artifact's descriptor does not parse: {error}"),
        )
    })?;
    if described != manifest.descriptor {
        return Err(PluginError::new(
            codes::DESCRIPTOR_MISMATCH,
            format!(
                "the artifact {} describes another extractor than the manifest",
                artifact.url
            ),
        ));
    }
    Ok(PluginExtractor {
        descriptor: described,
        params,
        plugin: MadeByPlugin {
            version: manifest.version.clone(),
            artifact_sha256: artifact.sha256.clone(),
        },
        transport,
        native,
    })
}

impl PluginExtractor {
    /// Whether the plugin is a native library, which runs in the process with no deadline of its
    /// own; a wasm module's calls end at the policy's call deadline.
    #[must_use]
    pub const fn is_native(&self) -> bool {
        self.native
    }

    /// What `made_by.plugin` records for data this plugin makes.
    #[must_use]
    pub fn made_by(&self) -> &MadeByPlugin {
        &self.plugin
    }

    fn deliver(&self, records: Vec<Record>, out: &mut Emitter) -> Result<(), ExtractorError> {
        for record in records {
            let name = |output: u16| {
                self.descriptor
                    .outputs
                    .get(usize::from(output))
                    .map(|spec| spec.name.as_str())
                    .ok_or_else(|| {
                        ExtractorError::with_code(
                            "INVALID_EMIT",
                            format!(
                                "the plugin emitted to output {output}, which it does not declare"
                            ),
                        )
                    })
            };
            match record {
                Record::Sample {
                    output,
                    time,
                    values,
                } => out.sample(name(output)?, MediaTime(time), &values),
                Record::Word {
                    output,
                    start,
                    end,
                    text,
                    speaker,
                } => out.word(
                    name(output)?,
                    DataWord {
                        start: MediaTime(start),
                        end: MediaTime(end),
                        text,
                        speaker,
                    },
                ),
                Record::Interval {
                    output,
                    start,
                    end,
                    label,
                    score,
                } => out.interval(
                    name(output)?,
                    DataInterval {
                        start: MediaTime(start),
                        end: MediaTime(end),
                        label,
                        score,
                    },
                ),
            }
        }
        Ok(())
    }
}

/// Emits are taken only from frames, blocks and `end`.
fn nothing_emitted(records: &[Record], step: &str) -> Result<(), ExtractorError> {
    if records.is_empty() {
        Ok(())
    } else {
        Err(ExtractorError::with_code(
            "INVALID_EMIT",
            format!("the plugin emitted during {step}, which takes no emits"),
        ))
    }
}

impl Extractor for PluginExtractor {
    fn describe(&self) -> &Descriptor {
        &self.descriptor
    }

    fn begin(&mut self, context: &RunContext) -> Result<(), ExtractorError> {
        let context = serde_json::json!({
            "range": context.range,
            "passes": context.passes,
            "from": context.from,
            "video": context.video.map(|(size, format)| {
                serde_json::json!({ "size": size, "format": format })
            }),
            "audio": context.audio.map(|(rate, channels, block_frames)| serde_json::json!({
                "rate": rate, "channels": channels, "block_frames": block_frames
            })),
            "frame_rate": context.frame_rate,
            "params": self.params,
        });
        let records = self.transport.begin(context.to_string().as_bytes())?;
        nothing_emitted(&records, "begin")
    }

    fn pass(&mut self, pass: &PassInfo) -> Result<(), ExtractorError> {
        let way = match pass.direction {
            alpha2_engine::extract::Direction::Forward => direction::FORWARD,
            alpha2_engine::extract::Direction::Backward => direction::BACKWARD,
        };
        let index = u32::try_from(pass.pass).unwrap_or(u32::MAX);
        let records = self.transport.pass(index, way)?;
        nothing_emitted(&records, "a pass start")
    }

    fn video(&mut self, frame: &VideoInput, out: &mut Emitter) -> Result<(), ExtractorError> {
        let format = match frame.format {
            VideoFormat::Rgba8 => video_format::RGBA8,
            VideoFormat::Luma8 => video_format::LUMA8,
        };
        let records = self.transport.video(
            frame.time.ticks(),
            frame.width,
            frame.height,
            format,
            &frame.bytes,
        )?;
        self.deliver(records, out)
    }

    fn audio(&mut self, block: &AudioInput, out: &mut Emitter) -> Result<(), ExtractorError> {
        let records = self.transport.audio(block)?;
        self.deliver(records, out)
    }

    fn end(&mut self, out: &mut Emitter) -> Result<(), ExtractorError> {
        let records = self.transport.end()?;
        self.deliver(records, out)
    }
}