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};
pub mod codes {
pub const FETCH_FAILED: &str = "PLUGIN_FETCH_FAILED";
pub const HASH_MISMATCH: &str = "PLUGIN_HASH_MISMATCH";
pub const ABI_UNSUPPORTED: &str = "PLUGIN_ABI_UNSUPPORTED";
pub const NO_ARTIFACT: &str = "PLUGIN_NO_ARTIFACT";
pub const NATIVE_REFUSED: &str = "PLUGIN_NATIVE_REFUSED";
pub const REFUSED: &str = "PLUGIN_REFUSED";
pub const DESCRIPTOR_MISMATCH: &str = "PLUGIN_DESCRIPTOR_MISMATCH";
pub const UNSUPPORTED_FEATURE: &str = "PLUGIN_UNSUPPORTED_FEATURE";
pub const LOAD_FAILED: &str = "PLUGIN_LOAD_FAILED";
pub const TRAPPED: &str = "PLUGIN_TRAPPED";
pub const LIMIT: &str = "PLUGIN_LIMIT";
}
pub const CANCELLED: &str = "CANCELLED";
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,
];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PluginError {
pub code: &'static str,
pub message: String,
}
impl PluginError {
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())
}
}
pub fn parse_manifest(text: &str) -> Result<PluginManifest, PluginError> {
PluginManifest::from_json(text).map_err(PluginError::from)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Policy {
pub allow_native: bool,
pub force_wasm: bool,
pub memory_bytes: u64,
pub call_deadline: Duration,
}
pub const DEFAULT_MEMORY_BYTES: u64 = 1024 * 1024 * 1024;
pub const MAX_MEMORY_BYTES: u64 = 1 << 31;
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,
}
}
}
pub const TARGET: &str = env!("ALPHA2_HOST_CORE_TARGET");
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(", ")
),
))
}
}
}
#[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
})
}
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))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Fetched {
pub path: PathBuf,
pub local: bool,
}
pub trait Fetch {
fn fetch(&mut self, url: &str, sha256: &str, bytes: u64) -> Result<Fetched, PluginError>;
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))
}
const MAX_LOG_BYTES: usize = 2048;
const LOG_BUDGET_BYTES: usize = 64 * 1024;
const MAX_FAIL_BYTES: usize = 4096;
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()
}
#[derive(Debug)]
struct LogBudget {
remaining: usize,
exhausted: bool,
}
impl Default for LogBudget {
fn default() -> Self {
Self {
remaining: LOG_BUDGET_BYTES,
exhausted: false,
}
}
}
impl LogBudget {
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)
}
fn log(&mut self, message: &[u8]) {
if let Some(line) = self.line(message) {
alpha2_os::diagnostic!("plugin: {line}");
}
}
}
type Call = Result<Vec<Record>, ExtractorError>;
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;
}
#[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()
}
const RECORD_LIMITS: Limits = Limits {
max_values: MAX_DATA_CHANNELS * 4,
max_text_bytes: MAX_DATA_LABEL_BYTES,
};
#[derive(Debug, Default)]
struct Collected {
records: Vec<Record>,
counts: Vec<usize>,
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}"),
)),
}
}
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
}
}
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()
}
}
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 {
#[must_use]
pub const fn is_native(&self) -> bool {
self.native
}
#[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(())
}
}
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)
}
}