Skip to main content

plughost_core/
errors.rs

1use std::fmt;
2
3/// Format-independent error categories. These describe the failure, not an automatic retry policy.
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5#[non_exhaustive]
6pub enum FailureKind {
7    /// Caller input violated a host contract.
8    InvalidInput,
9    /// The format or plugin does not implement the requested operation.
10    Unsupported,
11    /// The requested plugin or native object was not found.
12    NotFound,
13    /// A module or plugin instance could not be loaded or initialized.
14    Load,
15    /// The requested processing configuration could not be applied.
16    Configuration,
17    /// Processing was requested before successful preparation.
18    NotPrepared,
19    /// The instance or its owning handle is closed.
20    Closed,
21    /// Processing cannot continue until the reported restart condition is handled.
22    RestartRequired,
23    /// The operation requires the editor to be closed.
24    EditorOpen,
25    /// The saved state belongs to another plugin identity.
26    StateMismatch,
27    /// Native state could not be saved, decoded, or restored.
28    State,
29    /// A plugin processing call or its output failed validation.
30    Processing,
31    /// A native editor operation failed.
32    Editor,
33    /// The host could not complete a platform or resource operation.
34    Host,
35    /// A helper response or shared-memory message violated the internal protocol.
36    Protocol,
37    /// The helper exited unexpectedly or was terminated.
38    Crashed,
39    /// An operation exceeded its configured deadline.
40    TimedOut,
41    /// The application cancelled the operation, which terminated the helper.
42    Cancelled,
43}
44
45/// A portable category with the original diagnostic message, including native codes when provided.
46#[derive(Clone, Debug, PartialEq, Eq)]
47#[non_exhaustive]
48pub struct Failure {
49    /// Portable category for programmatic handling.
50    pub kind: FailureKind,
51    /// Human-readable diagnostic; do not parse it as a stable error code.
52    pub message: String,
53}
54
55impl Failure {
56    /// Constructs a category and diagnostic report.
57    #[must_use]
58    pub fn new(kind: FailureKind, message: impl Into<String>) -> Self {
59        Self {
60            kind,
61            message: message.into(),
62        }
63    }
64}
65
66impl fmt::Display for Failure {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.write_str(&self.message)
69    }
70}
71
72impl std::error::Error for Failure {}
73
74const EVENT_CAPACITY: &str =
75    "the block or pending edit queue exceeds MAX_BLOCK_EVENTS or MAX_BLOCK_SYSEX_BYTES";
76const EVENT_PORT_COUNT: &str = "the event routing exceeds the maximum ports per slot or chain";
77const DUPLICATE_EVENT_PORT: &str = "event output port ID occurs more than once in one slot";
78const EVENT_ROUTE: &str = "the event route does not name an available source";
79const EVENT_PORT: &str = "the event names an event port the chain does not have";
80const AUDIO_SLOT_COUNT: &str = "the audio configuration needs one routing entry per plugin";
81const AUDIO_BUS_COUNT: &str = "the audio configuration exceeds the maximum buses per direction";
82const AUDIO_CHANNEL_COUNT: &str =
83    "the audio configuration exceeds the maximum active channels per direction";
84const DUPLICATE_AUDIO_BUS: &str = "audio bus ID occurs more than once in one direction";
85const AUDIO_BUS_LAYOUT: &str = "an active audio bus must have a nonempty layout";
86const AUDIO_ROUTE: &str = "the audio route does not name an available source";
87const CHANNEL_ADAPTATION: &str =
88    "the explicit channel adaptation does not match the source and target layouts";
89const BLOCK_EVENTS: &str = "events must be notes, expressions in their ranges, MIDI 1.0 channel messages or complete \
90     system exclusive messages, in offset order and inside the block or render input";
91const AUDIO_BUFFERS: &str = "audio buffers must match the bus channel count and contain equal frame \
92     counts, at most the prepared maximum block size";
93const AUDIO_SAMPLE_FORMAT: &str =
94    "audio sample precision does not match the prepared configuration";
95const STATE_SIZE: &str = "plugin component and controller state together exceed the maximum size";
96const STATE_BYTES: &str = "the bytes are not a plugin state this plughost version can read";
97const PARAMETER_CHOICE_PAGE: &str =
98    "parameter choice pages need a valid start index and a nonzero entry count within the maximum";
99const PRESET_SIZE: &str = "the preset file exceeds the maximum size";
100const AUTOMATION: &str =
101    "automation must be ordered, normalized, inside the block and address a loaded slot";
102const NOT_AUTOMATABLE: &str = "parameter cannot be automated";
103const TRANSPORT: &str =
104    "transport values must be finite, representable, and describe a valid tempo, meter and loop";
105const SAMPLE_RATE: &str = "sample rate must be finite and greater than zero";
106const BLOCK_SIZE: &str = "maximum block size must be between 1 and i32::MAX";
107const OUTPUT_COUNT: &str = "the configuration needs one output layout per plugin";
108const EMPTY_CHAIN: &str = "a chain must contain at least one plugin";
109const INVALID_SLOT: &str = "the slot does not contain a loaded plugin";
110const PARAMETER_VALUE: &str = "parameter value must be finite and normalized to 0..=1";
111const PARAMETER_TEXT: &str =
112    "parameter text must be accepted by the plugin, NUL-free and within the maximum UTF-8 bytes";
113const PLAIN_PARAMETER_VALUE: &str =
114    "plain parameter value must be finite and within the native parameter range";
115const UNKNOWN_PARAMETER: &str = "the parameter does not exist";
116const READ_ONLY_PARAMETER: &str = "the parameter is read-only";
117const HOST_IDENTITY: &str =
118    "host identity must be NUL-free, with a non-empty name of at most 127 UTF-16 code units";
119const PRESET_DISCOVERY_TARGET: &str = "a preset discovery target needs a non-empty, NUL-free provider \
120     ID and, for a file location, an absolute, NUL-free Unicode path, each within the text limit";
121
122/// Messages shared by several plughost crates.
123pub const MAIN_BUS: &str = "the plugin has no main audio bus for the requested layout";
124/// Diagnostic for excessive native output; reset is required before further processing.
125pub const OUTPUT_EVENT_CAPACITY: &str = "the plugin produced more events or system exclusive bytes in one block than MAX_BLOCK_EVENTS or MAX_BLOCK_SYSEX_BYTES allow; reset before processing again";
126/// Diagnostic for a missing native event port.
127pub const UNKNOWN_EVENT_PORT: &str = "the plugin has no event port with this ID";
128/// Prefix identifying processing-path audit diagnostics.
129pub const AUDIT: &str = "real-time audit:";
130/// Diagnostic prefix for output event kinds with no portable representation.
131pub const UNCONVERTIBLE_OUTPUT_EVENTS: &str = "output events with no portable form (chords, scales, choke, text expression, MIDI 2.0) were not delivered:";
132/// Diagnostic for state belonging to another plugin class.
133pub const STATE_MISMATCH: &str = "the state belongs to a different plugin class";
134/// Diagnostic for a chain without a prepared processing configuration.
135pub const CHAIN_NOT_PREPARED: &str = "the chain is not prepared";
136
137/// A request rejected before changing the plugin or its processing configuration.
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139#[non_exhaustive]
140pub enum InputError {
141    /// Routing entries do not match the number of loaded plugin slots.
142    AudioSlotCount,
143    /// A direction exceeds `MAX_AUDIO_BUSES`.
144    AudioBusCount,
145    /// A direction exceeds `MAX_AUDIO_CHANNELS` active channels.
146    AudioChannelCount,
147    /// A native bus ID occurs more than once in one direction.
148    DuplicateAudioBus {
149        /// Native ID associated with the invalid request.
150        id: u64,
151    },
152    /// An active bus requested the empty layout.
153    AudioBusLayout {
154        /// Native ID associated with the invalid request.
155        id: u64,
156    },
157    /// An active input bus names a missing or inactive source.
158    AudioRoute {
159        /// Zero-based destination plugin slot.
160        slot: usize,
161        /// Native destination input bus ID.
162        bus: u64,
163    },
164    /// The requested conversion does not match the two layouts.
165    ChannelAdaptation {
166        /// Layout supplied by the source.
167        source: crate::Layout,
168        /// Layout requested by the destination.
169        target: crate::Layout,
170    },
171    /// Channel counts or per-channel frame lengths do not match the prepared buses, or a block
172    /// has more frames than the prepared maximum block size.
173    AudioBuffers,
174    /// Sample precision differs from the prepared configuration.
175    AudioSampleFormat,
176    /// Aggregate component and controller state exceeds `MAX_STATE_BYTES`.
177    StateSize,
178    /// Bytes given to `PluginState::from_bytes` are not a state that plughost wrote, or are one
179    /// of a later format version.
180    StateBytes,
181    /// A discrete-choice page has an invalid start index or count.
182    ParameterChoicePage,
183    /// Native preset bytes exceed `MAX_PRESET_BYTES`.
184    PresetSize,
185    /// Transport contains a non-finite, unrepresentable, or inconsistent value.
186    Transport,
187    /// Automation is unordered, out of range, outside the block, or names a missing slot.
188    Automation,
189    /// The addressed parameter does not support sample-timed automation.
190    NotAutomatable {
191        /// Native ID associated with the invalid request.
192        id: u64,
193    },
194    /// Host text contains NUL, or its name is empty or exceeds 127 UTF-16 code units.
195    HostIdentity,
196    /// A preset discovery provider ID is empty, contains NUL or exceeds
197    /// [`PRESET_DISCOVERY_TEXT_BYTES`](crate::PRESET_DISCOVERY_TEXT_BYTES), or its file location
198    /// is not an absolute Unicode path within that size and without NUL.
199    PresetDiscoveryTarget,
200    /// A chain was created or configured without a plugin.
201    EmptyChain,
202    /// The sample rate is not finite and greater than zero.
203    SampleRate,
204    /// Maximum block size is outside `1..=i32::MAX`.
205    BlockSize,
206    /// The legacy configuration does not provide one output layout per plugin.
207    OutputCount,
208    /// The plugin has no main audio bus with the requested layout.
209    MainBus,
210    /// The slot index does not address a loaded plugin.
211    Slot,
212    /// The parameter value is not finite and normalized to `0..=1`.
213    ParameterValue,
214    /// Display text is excessive, contains NUL, or is rejected by the plugin.
215    ParameterText,
216    /// The native-unit parameter value is non-finite or outside the native range.
217    PlainParameterValue,
218    /// The requested parameter ID does not exist.
219    UnknownParameter {
220        /// Native ID associated with the invalid request.
221        id: u64,
222    },
223    /// A host edit addressed a read-only parameter.
224    ReadOnlyParameter {
225        /// Native ID associated with the invalid request.
226        id: u64,
227    },
228    /// Combined automation/events or SysEx bytes exceed the per-block capacity.
229    EventCapacity,
230    /// An event routing direction exceeds `MAX_EVENT_PORTS`.
231    EventPortCount,
232    /// An output port ID occurs more than once in a slot.
233    DuplicateEventPort {
234        /// Native ID associated with the invalid request.
235        id: u64,
236    },
237    /// An event input route names an unavailable source.
238    EventRoute {
239        /// Zero-based destination plugin slot.
240        slot: usize,
241        /// Native destination event input port ID.
242        port: u64,
243    },
244    /// An event names an external port the chain does not expose.
245    EventPort {
246        /// Invalid zero-based external event port index.
247        port: usize,
248    },
249    /// Events that are not valid, in offset order, or inside the block, or for a render before
250    /// the end of its input.
251    Events,
252    /// A bundle or preset path cannot be represented by the helper's Unicode path protocol.
253    PathEncoding,
254    /// A realtime quantum is zero frames or exceeds the prepared maximum block size.
255    RealtimeQuantum,
256    /// A realtime latency is not one, two or three quanta.
257    RealtimeLatency,
258    /// A dry fallback needs as many output channels as input channels.
259    RealtimeDry,
260    /// No remote editor region was set, or the one given does not have a finite position and a
261    /// positive size within an existing display.
262    RemoteRegion,
263    /// The slot has no open remote editor.
264    RemoteEditor,
265}
266
267impl fmt::Display for InputError {
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        match self {
270            Self::EventCapacity => f.write_str(EVENT_CAPACITY),
271            Self::EventPortCount => {
272                write!(f, "{EVENT_PORT_COUNT} ({})", crate::MAX_EVENT_PORTS)
273            }
274            Self::DuplicateEventPort { id } => write!(f, "{DUPLICATE_EVENT_PORT} ({id})"),
275            Self::EventRoute { slot, port } => {
276                write!(f, "{EVENT_ROUTE} (slot {slot}, input port {port})")
277            }
278            Self::EventPort { port } => write!(f, "{EVENT_PORT} ({port})"),
279            Self::Events => f.write_str(BLOCK_EVENTS),
280            Self::AudioSlotCount => f.write_str(AUDIO_SLOT_COUNT),
281            Self::AudioBusCount => write!(f, "{AUDIO_BUS_COUNT} ({})", crate::MAX_AUDIO_BUSES),
282            Self::AudioChannelCount => {
283                write!(f, "{AUDIO_CHANNEL_COUNT} ({})", crate::MAX_AUDIO_CHANNELS)
284            }
285            Self::DuplicateAudioBus { id } => write!(f, "{DUPLICATE_AUDIO_BUS} ({id})"),
286            Self::AudioBusLayout { id } => write!(f, "{AUDIO_BUS_LAYOUT} ({id})"),
287            Self::AudioRoute { slot, bus } => {
288                write!(f, "{AUDIO_ROUTE} (slot {slot}, input bus {bus})")
289            }
290            Self::ChannelAdaptation { source, target } => {
291                write!(f, "{CHANNEL_ADAPTATION} ({source:?} to {target:?})")
292            }
293            Self::AudioBuffers => f.write_str(AUDIO_BUFFERS),
294            Self::AudioSampleFormat => f.write_str(AUDIO_SAMPLE_FORMAT),
295            Self::StateSize => write!(f, "{STATE_SIZE} ({} MiB)", crate::MAX_STATE_BYTES >> 20),
296            Self::StateBytes => f.write_str(STATE_BYTES),
297            Self::ParameterChoicePage => write!(
298                f,
299                "{PARAMETER_CHOICE_PAGE} ({})",
300                crate::PARAMETER_CHOICE_PAGE_SIZE
301            ),
302            Self::PresetSize => write!(f, "{PRESET_SIZE} ({} MiB)", crate::MAX_PRESET_BYTES >> 20),
303            Self::Automation => f.write_str(AUTOMATION),
304            Self::NotAutomatable { id } => write!(f, "{NOT_AUTOMATABLE} ({id})"),
305            Self::Transport => f.write_str(TRANSPORT),
306            Self::HostIdentity => f.write_str(HOST_IDENTITY),
307            Self::PresetDiscoveryTarget => f.write_str(PRESET_DISCOVERY_TARGET),
308            Self::EmptyChain => f.write_str(EMPTY_CHAIN),
309            Self::SampleRate => f.write_str(SAMPLE_RATE),
310            Self::BlockSize => f.write_str(BLOCK_SIZE),
311            Self::OutputCount => f.write_str(OUTPUT_COUNT),
312            Self::MainBus => f.write_str(MAIN_BUS),
313            Self::Slot => f.write_str(INVALID_SLOT),
314            Self::ParameterText => write!(f, "{PARAMETER_TEXT} ({})", crate::PARAMETER_TEXT_BYTES),
315            Self::PlainParameterValue => f.write_str(PLAIN_PARAMETER_VALUE),
316            Self::ParameterValue => f.write_str(PARAMETER_VALUE),
317            Self::UnknownParameter { id } => write!(f, "{UNKNOWN_PARAMETER} ({id})"),
318            Self::ReadOnlyParameter { id } => write!(f, "{READ_ONLY_PARAMETER} ({id})"),
319            Self::PathEncoding => f.write_str(PATH_ENCODING),
320            Self::RealtimeQuantum => f.write_str(REALTIME_QUANTUM),
321            Self::RealtimeLatency => f.write_str(REALTIME_LATENCY),
322            Self::RealtimeDry => f.write_str(REALTIME_DRY),
323            Self::RemoteRegion => f.write_str(REMOTE_REGION),
324            Self::RemoteEditor => f.write_str(REMOTE_EDITOR),
325        }
326    }
327}
328
329impl std::error::Error for InputError {}
330
331const PATH_ENCODING: &str = "plugin bundle and preset paths must be valid Unicode";
332const REALTIME_QUANTUM: &str =
333    "a realtime quantum must be at least one frame and at most the prepared maximum block size";
334const REALTIME_LATENCY: &str = "a realtime latency must be one, two or three quanta";
335const REALTIME_DRY: &str = "a dry fallback needs as many output channels as input channels";
336const REMOTE_EDITOR: &str = "the slot has no open remote editor";
337const REMOTE_REGION: &str = "a remote editor needs a region set, with a finite position and a positive size within an existing display";
338
339const INPUT: &str = "invalid render input";
340const LATENCY_CHANGED: &str = "the processor's latency changed during rendering";
341const LATENCY_NOT_APPLIED: &str = "a plugin announced a new latency that is not applied yet; reset \
342     or prepare the chain again before rendering";
343const TAIL_DURATION: &str = "maximum tail seconds must be finite and non-negative";
344const SILENCE_THRESHOLD: &str = "silence threshold must be finite and non-negative";
345const SILENCE_HOLD: &str = "silence hold seconds must be finite and non-negative";
346const RENDER_LENGTH: &str =
347    "render duration or sample buffer length exceeds the representable range";
348const SESSION_CLOSED: &str = "the render session is no longer active";
349const NON_FINITE_OUTPUT: &str = "the processor output a NaN or infinite sample";
350pub(crate) const MESSAGE_TOO_LARGE: &str = "the message exceeds the maximum size";
351pub(crate) const MALFORMED_MESSAGE: &str = "the message could not be decoded";
352pub(crate) const MALFORMED_MENU: &str = "a menu's items do not form a tree within the depth limit";
353
354/// Errors from the offline render rules.
355#[derive(Clone, Debug, PartialEq, Eq)]
356#[non_exhaustive]
357pub enum RenderError {
358    /// The streaming render session has already finished, been cancelled or failed.
359    SessionClosed,
360    /// A shared processing or control input contract was violated, including input channels
361    /// that do not match the processor or do not all have the requested number of frames
362    /// ([`InputError::AudioBuffers`]) and render events
363    /// that are not valid, not in offset order or not before the end of the input
364    /// ([`InputError::Events`]). Events on ports the processor lacks fail its
365    /// [`Process::validate_events`](crate::render::Process::validate_events).
366    Input(InputError),
367    /// Maximum tail duration is not finite and non-negative.
368    TailDuration,
369    /// Silence threshold is not finite and non-negative.
370    SilenceThreshold,
371    /// Silence hold duration is not finite and non-negative.
372    SilenceHold,
373    /// Render duration or sample storage exceeds the representable range.
374    LengthOverflow,
375    /// The processor’s latency changed during a render.
376    LatencyChanged {
377        /// Latency at render start, in frames.
378        before: u32,
379        /// New latency, in frames.
380        after: u32,
381    },
382    /// A plugin announced a new latency before the render started, and the processor has not
383    /// applied it yet.
384    LatencyNotApplied,
385    /// The processor output a NaN or infinite sample, first at `frame` of the output after the
386    /// removed latency (for a session, of the `push` or `finish` call), whatever the tail policy.
387    /// Output from the start of the failing block on is not delivered.
388    NonFiniteOutput {
389        /// The first output frame holding one, in any channel.
390        frame: usize,
391    },
392}
393
394impl RenderError {
395    /// Classifies a render error without deriving a retry policy.
396    pub fn kind(&self) -> FailureKind {
397        match self {
398            Self::SessionClosed => FailureKind::Closed,
399            Self::Input(_)
400            | Self::TailDuration
401            | Self::SilenceThreshold
402            | Self::SilenceHold
403            | Self::LengthOverflow => FailureKind::InvalidInput,
404            Self::LatencyChanged { .. } => FailureKind::Configuration,
405            Self::LatencyNotApplied => FailureKind::RestartRequired,
406            Self::NonFiniteOutput { .. } => FailureKind::Processing,
407        }
408    }
409}
410
411impl fmt::Display for RenderError {
412    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413        match self {
414            RenderError::SessionClosed => f.write_str(SESSION_CLOSED),
415            RenderError::Input(_) => f.write_str(INPUT),
416            RenderError::TailDuration => f.write_str(TAIL_DURATION),
417            RenderError::SilenceThreshold => f.write_str(SILENCE_THRESHOLD),
418            RenderError::SilenceHold => f.write_str(SILENCE_HOLD),
419            RenderError::LengthOverflow => f.write_str(RENDER_LENGTH),
420            RenderError::LatencyChanged { before, after } => {
421                write!(f, "{LATENCY_CHANGED} ({before} to {after} samples)")
422            }
423            RenderError::LatencyNotApplied => f.write_str(LATENCY_NOT_APPLIED),
424            RenderError::NonFiniteOutput { frame } => {
425                write!(f, "{NON_FINITE_OUTPUT} (at output frame {frame})")
426            }
427        }
428    }
429}
430
431impl std::error::Error for RenderError {
432    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
433        match self {
434            RenderError::Input(error) => Some(error),
435            _ => None,
436        }
437    }
438}