alpha2-host 0.8.0

Native project-rendering sidecar and batch CLI for alpha2.
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! Serves the `extract` operation. The host runs the extraction session and its supplier, and the
//! client runs the extractor, one step at a time over protocol frames.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::sync::{Mutex, OnceLock, PoisonError};
use std::time::{Duration, Instant};

use alpha2_engine::extract::{
    AudioInput, Delivery, Direction, Emit, ExtractRequest, ExtractSession, FramePlace, Need,
    SessionError, Step, SuppliedAudio, SuppliedFrame, Supplier, VideoInput,
};
use alpha2_host_core::host_frames::Attachment;
use alpha2_media::CancelToken;
use alpha2_model::{MediaFingerprint, Project};
use alpha2_time::MediaTime;
use serde::Deserialize;
use serde_json::{Value, json};

use crate::HostError;
use crate::PROTOCOL_VERSION;
use crate::host::Host;
use crate::serve_io::Responder;
pub use alpha2_host_core::requests::{ExtractHostRequest, PluginRequest};

/// How long a client may take to acknowledge a `pass`, `video` or `audio` step by default.
pub const DEFAULT_STEP_TIMEOUT: Duration = Duration::from_secs(60);

/// `serve`'s extraction flags.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ExtractOptions {
    /// How long a client may take to acknowledge a step; `None` waits forever.
    pub step_timeout: Option<Duration>,
    /// The most linear memory a wasm plugin may have.
    pub plugin_memory_bytes: u64,
    /// The longest one wasm plugin call may run.
    pub plugin_call_deadline: Duration,
    /// What the operator allows plugins, read once at start.
    pub plugins: &'static crate::plugin_policy::PluginPolicy,
}

impl ExtractOptions {
    /// The flags' defaults.
    pub const DEFAULT: Self = Self {
        step_timeout: Some(DEFAULT_STEP_TIMEOUT),
        plugin_memory_bytes: alpha2_host_core::plugins::DEFAULT_MEMORY_BYTES,
        plugin_call_deadline: alpha2_host_core::plugins::DEFAULT_CALL_DEADLINE,
        plugins: &crate::plugin_policy::DEFAULT_POLICY,
    };
}

impl Default for ExtractOptions {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// The acknowledgements of running extract requests, by request id; the request reader routes
/// each `extract.ack` here as it does a `cancel`.
fn acks() -> &'static Mutex<HashMap<String, Sender<String>>> {
    static ACKS: OnceLock<Mutex<HashMap<String, Sender<String>>>> = OnceLock::new();
    ACKS.get_or_init(Mutex::default)
}

/// Hands an `extract.ack` header to its request; an ack for no running request is dropped.
pub fn route_ack(request_id: &str, header: String) {
    let routes = acks().lock().unwrap_or_else(PoisonError::into_inner);
    if let Some(route) = routes.get(request_id) {
        let _ = route.send(header);
    }
}

/// Removes a request's route when its run ends.
struct AckRoute(String);

impl Drop for AckRoute {
    fn drop(&mut self) {
        acks()
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&self.0);
    }
}

/// Set once the input has ended: no acknowledgement can arrive, so new routes start closed.
static ACKS_CLOSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Closes every route, so a run waiting on an acknowledgement sees its route close.
pub fn close_ack_routes() {
    let mut routes = acks().lock().unwrap_or_else(PoisonError::into_inner);
    ACKS_CLOSED.store(true, std::sync::atomic::Ordering::Release);
    routes.clear();
}

fn register(request_id: &str) -> (AckRoute, Receiver<String>) {
    let (sender, receiver) = std::sync::mpsc::channel();
    let mut routes = acks().lock().unwrap_or_else(PoisonError::into_inner);
    if !ACKS_CLOSED.load(std::sync::atomic::Ordering::Acquire) {
        routes.insert(request_id.to_owned(), sender);
    }
    (AckRoute(request_id.to_owned()), receiver)
}

/// One client acknowledgement.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Ack {
    seq: u64,
    #[serde(default)]
    emits: Vec<Value>,
    #[serde(default)]
    error: Option<AckError>,
}

#[derive(Deserialize)]
struct AckError {
    message: String,
}

/// Sends steps and waits for their acknowledgements.
struct Client<'a> {
    out: &'a Responder,
    request_id: &'a str,
    acks: Receiver<String>,
    seq: u64,
    timeout: Option<Duration>,
    cancel: &'a CancelToken,
    waited: Duration,
}

impl Client<'_> {
    /// Sends `step` and returns the client's emits, refusing an error ack, a timeout or a cancel.
    fn step(
        &mut self,
        mut step: Value,
        attachments: &[Attachment],
        timed: bool,
    ) -> Result<Vec<Emit>, HostError> {
        self.seq += 1;
        step["protocolVersion"] = json!(PROTOCOL_VERSION);
        step["type"] = json!("extract.step");
        step["requestId"] = json!(self.request_id);
        step["seq"] = json!(self.seq);
        self.out.send_with(&step, attachments)?;
        let started = Instant::now();
        let deadline = timed
            .then_some(self.timeout)
            .flatten()
            .map(|timeout| started + timeout);
        // The client's step, with no deadline of its own for `begin` and `end`.
        let _idle = crate::heartbeat::request_idle();
        loop {
            if self.cancel.is_cancelled() {
                return Err(HostError::new(
                    "CANCELLED",
                    crate::protocol::cancelled("the extraction was cancelled"),
                ));
            }
            let wait = deadline.map_or(Duration::from_millis(100), |deadline| {
                deadline
                    .saturating_duration_since(Instant::now())
                    .min(Duration::from_millis(100))
            });
            match self.acks.recv_timeout(wait) {
                Ok(header) => {
                    let ack: Ack = serde_json::from_str(&header).map_err(|error| {
                        HostError::new("INVALID_REQUEST", format!("invalid extract.ack: {error}"))
                    })?;
                    if ack.seq != self.seq {
                        continue;
                    }
                    self.waited += started.elapsed();
                    if let Some(error) = ack.error {
                        return Err(HostError::new(
                            "EXTRACTOR_FAILED",
                            format!("the extractor failed: {}", error.message),
                        ));
                    }
                    return ack
                        .emits
                        .iter()
                        .enumerate()
                        .map(|(index, emit)| {
                            alpha2_engine::extract::emit_from_json(emit)
                                .map_err(|reason| invalid_emit(index, &reason))
                        })
                        .collect();
                }
                Err(RecvTimeoutError::Timeout) => {
                    if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
                        return Err(HostError::new(
                            "EXTRACTOR_TIMEOUT",
                            format!(
                                "the client did not acknowledge step {} within {} ms",
                                self.seq,
                                self.timeout.map_or(0, |timeout| timeout.as_millis())
                            ),
                        ));
                    }
                }
                Err(RecvTimeoutError::Disconnected) => {
                    return Err(HostError::new(
                        "CANCELLED",
                        crate::protocol::cancelled(format!(
                            "the input ended before step {} was acknowledged",
                            self.seq
                        )),
                    ));
                }
            }
        }
    }
}

fn invalid_emit(index: usize, reason: &str) -> HostError {
    HostError::new("INVALID_EMIT", format!("emit {index} is invalid: {reason}"))
        .with_details(json!({ "index": index, "reason": reason }))
}

fn emit_into(session: &mut ExtractSession, emits: &[Emit]) -> Result<(), HostError> {
    session.emit(emits).map_err(|error| match error {
        SessionError::InvalidEmit { index, reason } => invalid_emit(index, &reason),
        other => HostError::new("INVALID_EMIT", other.to_string()),
    })
}

fn progress_message(request_id: &str, session: &ExtractSession) -> Value {
    let mut message = alpha2_engine::extract::progress_json(session);
    message["protocolVersion"] = json!(PROTOCOL_VERSION);
    message["type"] = json!("progress");
    message["requestId"] = json!(request_id);
    message["phase"] = json!("extract");
    message
}

fn video_step(frame: &VideoInput) -> (Value, Vec<Attachment>) {
    (
        json!({ "step": "video", "time": frame.time.ticks(), "width": frame.width, "height": frame.height, "format": frame.format }),
        vec![Attachment {
            kind: "application/octet-stream".to_owned(),
            bytes: frame.bytes.clone(),
        }],
    )
}

fn audio_step(block: &AudioInput) -> (Value, Vec<Attachment>) {
    let bytes = block
        .samples
        .iter()
        .flat_map(|sample| sample.to_le_bytes())
        .collect();
    (
        json!({ "step": "audio", "start": block.start.ticks(), "startSample": block.start_sample, "frames": block.frames, "rate": block.rate, "channels": block.channels }),
        vec![Attachment {
            kind: "application/octet-stream".to_owned(),
            bytes,
        }],
    )
}

/// Runs a client-side extractor's session over `supplier`, one step outstanding at a time.
#[allow(clippy::too_many_arguments)]
fn run_client(
    mut session: ExtractSession,
    supplier: &mut dyn Supplier,
    out: &Responder,
    request_id: &str,
    timeout: Option<Duration>,
    cancel: &CancelToken,
) -> Result<(Vec<alpha2_model::DataSet>, Duration), HostError> {
    let (_route, acks) = register(request_id);
    let mut client = Client {
        out,
        request_id,
        acks,
        seq: 0,
        timeout,
        cancel,
        waited: Duration::ZERO,
    };
    out.send(&progress_message(request_id, &session))?;
    let begin = client.step(
        json!({ "step": "begin", "context": alpha2_engine::extract::client_context_json(&session.context()) }),
        &[],
        false,
    )?;
    emit_into(&mut session, &begin)?;
    loop {
        if cancel.is_cancelled() {
            return Err(HostError::new(
                "CANCELLED",
                crate::protocol::cancelled("the extraction was cancelled"),
            ));
        }
        match session.next() {
            Step::Need(need) => match &need {
                Need::SourceFrame { .. } | Need::TimelineFrame { .. } => {
                    extract_media_step();
                    match supplier.frame(&need).map_err(HostError::classify)? {
                        Some(frame) => session
                            .supply_video(frame)
                            .map_err(|error| HostError::new("INTERNAL", error.to_string()))?,
                        None => session
                            .supply_end()
                            .map_err(|error| HostError::new("INTERNAL", error.to_string()))?,
                    }
                }
                Need::SourceAudio { .. } | Need::TimelineAudio { .. } => {
                    extract_media_step();
                    let block = supplier.audio(&need).map_err(HostError::classify)?;
                    session
                        .supply_audio(block)
                        .map_err(|error| HostError::new("INTERNAL", error.to_string()))?;
                }
            },
            Step::PassBoundary { pass, direction } => {
                out.send(&progress_message(request_id, &session))?;
                let direction = match direction {
                    Direction::Forward => "forward",
                    Direction::Backward => "backward",
                };
                let emits = client.step(
                    json!({ "step": "pass", "pass": pass, "direction": direction }),
                    &[],
                    true,
                )?;
                emit_into(&mut session, &emits)?;
            }
            Step::Deliver(delivery) => {
                let (step, attachments) = match &delivery {
                    Delivery::Video(frame) => video_step(frame),
                    Delivery::Audio(block) => audio_step(block),
                };
                let emits = client.step(step, &attachments, true)?;
                emit_into(&mut session, &emits)?;
                out.send(&progress_message(request_id, &session))?;
            }
            Step::Done => break,
        }
    }
    out.send(&progress_message(request_id, &session))?;
    let end = client.step(json!({ "step": "end" }), &[], false)?;
    emit_into(&mut session, &end)?;
    let sets = session
        .finish()
        .map_err(|error| HostError::new("INVALID_EMIT", error.to_string()))?;
    Ok((sets, client.waited))
}

/// The supplier of source needs from native decoders, and timeline frames from stills.
struct HostSupplier<'a> {
    reader: alpha2_host_core::extract::ReaderSupplier<
        'a,
        alpha2_native::NativeDecoder,
        alpha2_native::NativeAudioDecoder,
    >,
    timeline: Option<TimelineFrames<'a>>,
}

/// Timeline frames drawn through the host's still path.
struct TimelineFrames<'a> {
    host: &'a mut Host,
    project: String,
    assets: HashMap<String, alpha2_host_core::remote::SourceLocation>,
    effect_assets: HashMap<String, PathBuf>,
    effects: Vec<crate::protocol::EffectRequest>,
    canvas: (u32, u32),
}

impl TimelineFrames<'_> {
    fn frame(
        &mut self,
        time: MediaTime,
        size: u32,
        place: Option<&mut FramePlace<'_>>,
    ) -> Result<SuppliedFrame, String> {
        let (width, height) = alpha2_engine::extract::delivered_size(self.canvas, size);
        let project = crate::host::still_project(
            &self.project,
            Some(crate::protocol::StillSize { width, height }),
        )
        .map_err(|error| error.message)?;
        let entry = crate::protocol::StillEntry {
            time: time.ticks(),
            output: None,
        };
        self.host.render_stills(
            &project,
            &self.assets,
            &self.effect_assets,
            self.effects.clone(),
            &[entry],
            false,
            alpha2_native::ExistingOutput::Refuse,
        )?;
        let png = std::mem::take(&mut self.host.reply_attachments)
            .pop()
            .ok_or_else(|| "a still drew nothing".to_owned())?;
        let decoder = png::Decoder::new(std::io::Cursor::new(png.bytes));
        let mut reader = decoder.read_info().map_err(|error| error.to_string())?;
        let len = reader.output_buffer_size().ok_or("an oversized still")?;
        let packed = u64::from(width) * u64::from(height) * 4;
        let fits = reader.output_color_type() == (png::ColorType::Rgba, png::BitDepth::Eight)
            && (reader.info().width, reader.info().height) == (width, height)
            && u64::try_from(len).ok() == Some(packed);
        if let Some(buffer) = place.filter(|_| fits).and_then(|place| place.buffer(len)) {
            reader
                .next_frame(buffer)
                .map_err(|error| error.to_string())?;
            return Ok(SuppliedFrame {
                pts: time,
                width,
                height,
                rgba: Vec::new(),
            });
        }
        let mut rgba = vec![0; len];
        let info = reader
            .next_frame(&mut rgba)
            .map_err(|error| error.to_string())?;
        rgba.truncate(info.buffer_size());
        Ok(SuppliedFrame {
            pts: time,
            width,
            height,
            rgba,
        })
    }
}

impl Supplier for HostSupplier<'_> {
    fn frame(&mut self, need: &Need) -> Result<Option<SuppliedFrame>, String> {
        match need {
            Need::TimelineFrame { time, size, .. } => self
                .timeline
                .as_mut()
                .ok_or_else(|| "no timeline renderer".to_owned())?
                .frame(*time, *size, None)
                .map(Some),
            _ => self.reader.frame(need),
        }
    }

    fn frame_into(
        &mut self,
        need: &Need,
        place: &mut FramePlace<'_>,
    ) -> Result<Option<SuppliedFrame>, String> {
        match need {
            Need::TimelineFrame { time, size, .. } => self
                .timeline
                .as_mut()
                .ok_or_else(|| "no timeline renderer".to_owned())?
                .frame(*time, *size, Some(place))
                .map(Some),
            _ => self.reader.frame_into(need, place),
        }
    }

    fn audio(&mut self, need: &Need) -> Result<SuppliedAudio, String> {
        match need {
            Need::TimelineAudio { .. } => Err(crate::protocol::code_tag(
                "INVALID_INPUT",
                "this host does not supply timeline audio to extractors yet; extract from the source",
            )),
            _ => self.reader.audio(need),
        }
    }
}

/// Answers an `extract` request with a client-side extractor.
///
/// # Errors
/// The session's refusal of the request, a supplier or protocol failure, or the extractor's.
#[allow(clippy::too_many_lines)]
pub fn handle(
    host: &mut Host,
    request: ExtractHostRequest,
    out: &Responder,
    options: ExtractOptions,
) -> Result<Value, HostError> {
    let started = Instant::now();
    request.check()?;
    let ExtractHostRequest {
        request_id,
        project,
        assets,
        proxies,
        frames,
        resources,
        media,
        effect_assets,
        font_files,
        effects,
        request,
        descriptor,
        plugin,
        remote_content_hash,
        ..
    } = request;
    // Taken first, so a cancel also stops the plugin's fetch and calls.
    let cancel = crate::termination::export_cancel();
    // A plugin is fetched, checked and loaded before any media is read.
    let (descriptor, mut plugin) = match (descriptor, plugin) {
        (Some(descriptor), _) => (descriptor, None),
        (None, Some(plugin)) => {
            let loaded = load_plugin(&plugin, &request, options, &cancel)?;
            (
                alpha2_engine::extract::Extractor::describe(&loaded).clone(),
                Some(loaded),
            )
        }
        (None, None) => unreachable!("checked: one of descriptor and plugin"),
    };
    let parsed = Project::from_json(project.text())
        .map_err(|error| HostError::classify(crate::error_message(error)))?;
    let session = ExtractSession::new(&parsed, &descriptor, request.clone()).map_err(|error| {
        HostError::new(
            "INVALID_REQUEST",
            format!("invalid extract request: {error}"),
        )
    })?;
    let (paths, original) = host.extract_media(
        project.text(),
        &assets,
        &proxies,
        &frames,
        &resources,
        &effect_assets,
        &font_files,
        media,
        request.input.source_id.as_ref(),
        remote_content_hash,
    )?;
    let renderer = alpha2_render::CpuRenderer::new(1);
    let source = request.input.source_id.clone();
    let path = |id: &alpha2_media::SourceId| paths.get(id.as_str()).cloned();
    let video = match (&source, &descriptor.input) {
        (Some(id), alpha2_engine::extract::InputSpec::Video { .. }) => {
            let path = path(id).ok_or_else(|| {
                HostError::new("MISSING_INPUT", format!("no media for source {id}"))
            })?;
            let decoder = alpha2_native::NativeDecoder::open(&path)
                .map_err(|error| HostError::classify(error.to_string()))?;
            Some(alpha2_host_core::extract::VideoReader::new(
                decoder,
                id.clone(),
                (*cancel).clone(),
            ))
        }
        _ => None,
    };
    let audio = match (&source, session.context().audio) {
        (Some(id), Some((rate, _, _))) => {
            let path = path(id).ok_or_else(|| {
                HostError::new("MISSING_INPUT", format!("no media for source {id}"))
            })?;
            let decoder =
                alpha2_native::NativeAudioDecoder::open_stream(&path, rate, request.input.stream)
                    .map_err(|error| HostError::classify(error.to_string()))?;
            Some(alpha2_host_core::extract::AudioReader::new(
                decoder,
                id.clone(),
                rate,
                (*cancel).clone(),
            ))
        }
        _ => None,
    };
    let canvas = (parsed.settings.width, parsed.settings.height);
    let timeline = source.is_none().then(|| TimelineFrames {
        host: &mut *host,
        project: project.text().to_owned(),
        assets: paths.clone(),
        effect_assets: effect_assets.clone(),
        effects,
        canvas,
    });
    let mut supplier = HostSupplier {
        reader: alpha2_host_core::extract::ReaderSupplier::new(&renderer, video, audio),
        timeline,
    };
    let (mut sets, waited) = match plugin.as_mut() {
        Some(plugin) => (
            run_plugin(
                session,
                &mut supplier,
                (!plugin.calls_are_bounded(), plugin),
                out,
                &request_id,
                &cancel,
            )?,
            Duration::ZERO,
        ),
        None => run_client(
            session,
            &mut supplier,
            out,
            &request_id,
            options.step_timeout,
            &cancel,
        )?,
    };
    for set in &mut sets {
        if set.anchor.source().is_some() {
            set.made_from.clone_from(&original);
        }
        if let (Some(plugin), Some(made_by)) = (&plugin, set.made_by.as_mut()) {
            made_by.plugin = Some(plugin.made_by());
        }
    }
    let total = started.elapsed();
    Ok(json!({
        "dataSets": sets,
        "timings": {
            "totalMs": total.as_secs_f64() * 1_000.0,
            "clientMs": waited.as_secs_f64() * 1_000.0,
        },
    }))
}

fn plugin_error(error: alpha2_host_core::plugins::PluginError) -> HostError {
    if error.code == alpha2_host_core::plugins::CANCELLED {
        return HostError::new(error.code, crate::protocol::cancelled(error.message));
    }
    let mut host = HostError::new(error.code, error.message);
    host.details = error.details.map(Value::Object);
    host
}

/// Whether `error` is a refusal by the resource root the operator set.
fn resource_root_refusal(error: &alpha2_host_core::plugins::PluginError) -> bool {
    error
        .details
        .as_ref()
        .and_then(|details| details.get("policy"))
        .and_then(Value::as_str)
        == Some("resource_root")
}

/// Fetches and checks the manifest, then loads the artifact the request picks within the
/// operator's policy.
fn load_plugin(
    plugin: &PluginRequest,
    request: &ExtractRequest,
    options: ExtractOptions,
    cancel: &CancelToken,
) -> Result<alpha2_host_core::plugins::PluginExtractor, HostError> {
    use alpha2_host_core::plugins;
    let operator = options.plugins;
    operator.allows_plugins().map_err(plugin_error)?;
    if let Some((slot, path)) = plugin.supplied.iter().find(|(_, path)| !path.is_absolute()) {
        return Err(HostError::new(
            "INVALID_REQUEST",
            format!(
                "plugin.supplied.{slot} is not an absolute path: {}",
                path.display()
            ),
        ));
    }
    let download = crate::plugin_fetch::https();
    let (text, base) =
        crate::plugin_fetch::manifest(&plugin.manifest, &plugin.sha256, &*download, operator)
            .map_err(plugin_error)?;
    let manifest = plugins::parse_manifest(&text).map_err(plugin_error)?;
    let policy = plugins::Policy {
        allow_native: plugin.allow_native && operator.allows_native(),
        force_wasm: plugin.force_wasm,
        memory_bytes: options.plugin_memory_bytes,
        call_deadline: options.plugin_call_deadline,
        resource_root: operator.resource_root.clone(),
        isolation: operator.isolation().map_err(plugin_error)?,
    };
    let mut fetcher = crate::plugin_fetch::Fetcher::new(
        base,
        crate::plugin_fetch::cache_directory(),
        download,
        operator,
    )
    .with_cancel(cancel.clone());
    plugins::load(
        plugins::LoadRequest {
            manifest: &manifest,
            manifest_sha256: &plugin.sha256,
            params: &request.params,
            supplied: &plugin.supplied,
        },
        &policy,
        &mut fetcher,
        cancel,
    )
    .map_err(|error| {
        if resource_root_refusal(&error) {
            let message = match &operator.resource_root {
                plugins::ResourceRoot::Dir(root) => format!(
                    "{}; this host was started with --plugin-resource-root {}",
                    error.message,
                    root.display()
                ),
                _ => "this host was started without --plugin-resource-root, so a request may \
                      not fill a resource slot"
                    .to_owned(),
            };
            plugins::PluginError { message, ..error }
        } else if error.code == plugins::codes::NATIVE_REFUSED && plugin.allow_native {
            plugins::PluginError::new(
                error.code,
                format!(
                    "{} runs here only as native code, and this host was not started with \
                         --plugins native",
                    manifest.id
                ),
            )
        } else {
            error
        }
    })
    .map_err(plugin_error)
}

fn extract_media_step() {
    crate::heartbeat::request_step(crate::heartbeat::RequestSide::Input, "extract media");
}

/// Runs a plugin the host loaded through the session, with progress and cancel as for a client.
fn run_plugin(
    mut session: ExtractSession,
    supplier: &mut dyn Supplier,
    (unbounded, extractor): (bool, &mut dyn alpha2_engine::extract::Extractor),
    out: &Responder,
    request_id: &str,
    cancel: &CancelToken,
) -> Result<Vec<alpha2_model::DataSet>, HostError> {
    use alpha2_engine::extract::{DriveError, Emitter, ExtractorError, PassInfo};
    let call = || {
        if unbounded {
            crate::heartbeat::request_step(crate::heartbeat::RequestSide::Plugin, "plugin call");
            None
        } else {
            crate::heartbeat::request_idle()
        }
    };
    let failed = |error: ExtractorError| {
        let mut failure = match error.code {
            Some(code @ alpha2_host_core::plugins::CANCELLED) => {
                HostError::new(code, crate::protocol::cancelled(error.message))
            }
            Some(code) => HostError::new(code, error.message),
            None => HostError::new(
                "EXTRACTOR_FAILED",
                format!("the extractor failed: {}", error.message),
            ),
        };
        failure.details = error.details.map(Value::Object);
        failure
    };
    let internal = |error: SessionError| HostError::new("INTERNAL", error.to_string());
    out.send(&progress_message(request_id, &session))?;
    let called = call();
    extractor.begin(&session.context()).map_err(failed)?;
    drop(called);
    loop {
        if cancel.is_cancelled() {
            return Err(HostError::new(
                "CANCELLED",
                crate::protocol::cancelled("the extraction was cancelled"),
            ));
        }
        match session.next() {
            Step::Need(need) => match &need {
                Need::SourceFrame { .. } | Need::TimelineFrame { .. } => {
                    extract_media_step();
                    alpha2_engine::extract::supply_frame(&mut session, &need, extractor, supplier)
                        .map_err(|error| match error {
                            DriveError::Supplier(error) => HostError::classify(error),
                            DriveError::Session(error) => internal(error),
                            other => HostError::new("INTERNAL", other.to_string()),
                        })?;
                }
                Need::SourceAudio { .. } | Need::TimelineAudio { .. } => {
                    extract_media_step();
                    let block = supplier.audio(&need).map_err(HostError::classify)?;
                    session.supply_audio(block).map_err(internal)?;
                }
            },
            Step::PassBoundary { pass, direction } => {
                out.send(&progress_message(request_id, &session))?;
                let called = call();
                extractor
                    .pass(&PassInfo { pass, direction })
                    .map_err(failed)?;
                drop(called);
            }
            Step::Deliver(delivery) => {
                let mut emitter = Emitter::default();
                let called = call();
                match &delivery {
                    Delivery::Video(frame) => extractor.video(frame, &mut emitter),
                    Delivery::Audio(block) => extractor.audio(block, &mut emitter),
                }
                .map_err(failed)?;
                drop(called);
                emit_into(&mut session, emitter.emits())?;
                out.send(&progress_message(request_id, &session))?;
            }
            Step::Done => break,
        }
    }
    out.send(&progress_message(request_id, &session))?;
    let mut emitter = Emitter::default();
    let called = call();
    extractor.end(&mut emitter).map_err(failed)?;
    drop(called);
    emit_into(&mut session, emitter.emits())?;
    session
        .finish()
        .map_err(|error| HostError::new("INVALID_EMIT", error.to_string()))
}

/// The conformed original's fingerprint, which `made_from` records.
pub fn original_fingerprint(
    catalog: &alpha2_assets::AssetCatalog,
    source: &alpha2_media::SourceId,
) -> Option<MediaFingerprint> {
    match &catalog.entry(source)?.original {
        alpha2_assets::OriginalState::Online { fingerprint } => Some(fingerprint.clone()),
        _ => None,
    }
}