Skip to main content

grafton_ndi/error/
defects.rs

1//! Allocation-free causes and the rare diagnostic payloads errors retain.
2use crate::frames::{MAX_AUDIO_BYTES, MAX_METADATA_BYTES, MAX_VIDEO_BYTES};
3use crate::media::MAX_ALLOCATION_BYTES;
4use crate::{ColorInfo, ColorPrimaries, FrameMetadataStatus, PixelFormat, TransferFunction};
5use std::time::Duration;
6use thiserror::Error;
7
8/// The syntactic defect in an `ndi_color_info` element.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
10#[non_exhaustive]
11pub enum ColorMetadataDefect {
12    /// The element is not closed.
13    #[error("the element is not closed")]
14    UnclosedElement,
15    /// An attribute cannot start at this byte.
16    #[error("an attribute cannot start at this byte")]
17    AttributeStart,
18    /// An attribute has no value.
19    #[error("an attribute has no value")]
20    MissingValue,
21    /// An attribute value is not quoted.
22    #[error("an attribute value is not quoted")]
23    UnquotedValue,
24    /// An attribute value has no closing quote.
25    #[error("an attribute value has no closing quote")]
26    UnclosedValue,
27    /// An attribute occurs twice.
28    #[error("an attribute occurs twice")]
29    DuplicateAttribute,
30    /// A color attribute has an undefined value.
31    #[error("a color attribute has an undefined value")]
32    UndefinedValue,
33    /// A color attribute contains invalid XML value syntax or an unsupported entity reference.
34    #[error("a color attribute has an invalid XML value")]
35    InvalidAttributeValue,
36}
37
38/// The image encoder that refused output.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
40#[non_exhaustive]
41pub enum ImageCodecKind {
42    /// PNG.
43    #[error("PNG")]
44    Png,
45    /// JPEG.
46    #[error("JPEG")]
47    Jpeg,
48    /// WebP.
49    #[error("WebP")]
50    Webp,
51}
52
53/// A numerical codec setting checked by the image encoder.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
55#[non_exhaustive]
56pub enum ImageSettingKind {
57    /// JPEG or lossy WebP quality.
58    #[error("quality")]
59    Quality,
60    /// Lossy WebP encoding effort.
61    #[error("effort")]
62    Effort,
63}
64
65/// The rejected native Discovery Server address, retained only for diagnostics.
66#[derive(Debug, Clone, PartialEq, Eq, Hash, Error)]
67#[error(
68    "the SDK created no {object}: it does not accept {address:?} as a Discovery Server address"
69)]
70pub struct DiscoveryAddressFailure {
71    /// The kind of object the SDK refused to create.
72    pub object: &'static str,
73    /// The address the caller supplied.
74    pub address: Box<str>,
75}
76
77/// The malformed native discovery data.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
79#[non_exhaustive]
80pub enum DiscoveryDefect {
81    /// An array's span overflows.
82    #[error("SDK discovery array span overflow")]
83    ArraySpanOverflow,
84    /// A nonempty array has no data.
85    #[error("SDK discovery array is null with a nonzero count")]
86    NullArray,
87}
88/// A refusal of the shared media layout and value checks.
89///
90/// Frame validation nests this cause in [`FrameDefect::Layout`]. Standalone
91/// aspect ratios, frame rates, compressed video formats and allocation strides
92/// instead use [`InputDefect::Layout`]. Layout validators used by SDK allocator
93/// callbacks construct only allocation-free variants. The two wide diagnostic
94/// variants arise from standalone value checks and validation of delivered video
95/// headers and compressed formats, never from the `from_sdk_checked` validators
96/// that allocator callbacks use.
97#[derive(Debug, Clone, PartialEq, Error)]
98#[non_exhaustive]
99pub enum LayoutDefect {
100    /// Both parts of the frame rate must fit a positive SDK quantity.
101    #[error("{detail}")]
102    FrameRate {
103        /// Exact values, boxed only on 32-bit targets.
104        detail: CompactDiagnostic<FrameRateDefect>,
105    },
106    /// Compressed dimensions must fit positive SDK quantities.
107    #[error("{detail}")]
108    CompressedVideoDimensions {
109        /// Exact values, boxed only on 32-bit targets.
110        detail: CompactDiagnostic<VideoDimensionsDefect>,
111    },
112
113    /// Video line stride must be positive, got 0.
114    #[error("Video line stride must be positive, got 0")]
115    VideoZeroStride,
116    /// Audio channel stride exceeds i32 range.
117    #[error("Audio channel stride exceeds i32 range")]
118    AudioStrideRange,
119    /// Video frame has invalid width: {0}.
120    #[error("Video frame has invalid width: {0}")]
121    VideoWidth(DiagnosticInteger),
122    /// NDI video frames require even width, got {0}.
123    #[error("NDI video frames require even width, got {0}")]
124    VideoOddWidth(DiagnosticInteger),
125    /// Video frame has invalid height: {0}.
126    #[error("Video frame has invalid height: {0}")]
127    VideoHeight(DiagnosticInteger),
128    /// Uncompressed video frame has invalid line_stride_in_bytes: {0}.
129    #[error("Uncompressed video frame has invalid line_stride_in_bytes: {0}")]
130    VideoSdkStride(i32),
131    /// Video line_stride_in_bytes {stride} is smaller than minimum row size {minimum} for {format:?} width {width}.
132    #[error("Video line_stride_in_bytes {stride} is smaller than minimum row size {minimum} for {format:?} width {width}")]
133    VideoShortStride {
134        /// The stride.
135        stride: usize,
136        /// The minimum.
137        minimum: usize,
138        /// The format.
139        format: PixelFormat,
140        /// The width.
141        width: u32,
142    },
143    /// Video frame exceeds maximum size: {0} bytes > {MAX_VIDEO_BYTES} bytes.
144    #[error("Video frame exceeds maximum size: {0} bytes > {MAX_VIDEO_BYTES} bytes")]
145    VideoBytes(DiagnosticSize),
146    /// Planar 4:2:0 (YV12/I420) video frames require even height and line stride, got height {height} and stride {stride}.
147    #[error("Planar 4:2:0 (YV12/I420) video frames require even height and line stride, got height {height} and stride {stride}")]
148    VideoPlanar420 {
149        /// The height.
150        height: usize,
151        /// The stride.
152        stride: usize,
153    },
154    /// Semi-planar 4:2:0 (NV12) video frames require even height, got {0}.
155    #[error("Semi-planar 4:2:0 (NV12) video frames require even height, got {0}")]
156    VideoSemiPlanar420(usize),
157    /// UYVA video frames require even line stride, got {0}.
158    #[error("UYVA video frames require even line stride, got {0}")]
159    VideoUyvaStride(usize),
160    /// Video frame has invalid picture aspect ratio: {0}.
161    #[error("Video frame has invalid picture aspect ratio: {0}")]
162    PictureAspectRatio(f32),
163    /// Invalid sample rate: {0}.
164    #[error("Invalid sample rate: {0}")]
165    AudioRate(DiagnosticInteger),
166    /// Invalid number of {kind}: {value}.
167    #[error("Invalid number of {kind}: {value}")]
168    AudioCount {
169        /// The value.
170        value: DiagnosticInteger,
171        /// The kind.
172        kind: AudioCountKind,
173    },
174    /// Invalid channel_stride_in_bytes: {0}.
175    #[error("Invalid channel_stride_in_bytes: {0}")]
176    AudioStride(DiagnosticInteger),
177    /// channel_stride_in_bytes must be a multiple of 4, got {0}.
178    #[error("channel_stride_in_bytes must be a multiple of 4, got {0}")]
179    AudioStrideAlignment(usize),
180    /// channel_stride_in_bytes {stride} is smaller than one channel of audio samples {minimum}.
181    #[error(
182        "channel_stride_in_bytes {stride} is smaller than one channel of audio samples {minimum}"
183    )]
184    AudioShortStride {
185        /// The stride.
186        stride: usize,
187        /// The minimum.
188        minimum: usize,
189    },
190    /// Audio frame exceeds maximum size: {0} bytes > {MAX_AUDIO_BYTES} bytes.
191    #[error("Audio frame exceeds maximum size: {0} bytes > {MAX_AUDIO_BYTES} bytes")]
192    AudioBytes(DiagnosticSize),
193}
194
195/// Typed causes of [`crate::Error::InvalidFrame`].
196///
197/// Shared layout refusals use [`FrameDefect::Layout`] and [`LayoutDefect`].
198/// Ordinary causes retain their evidence inline without allocating. Boxed
199/// diagnostic fields retain caller or SDK text only for the documented exceptions.
200#[derive(Debug, Clone, PartialEq, Error)]
201#[non_exhaustive]
202pub enum FrameDefect {
203    /// A FourCC does not identify a supported packet-envelope codec.
204    #[error("Unknown packet envelope codec FourCC: 0x{fourcc:08X}")]
205    UnknownEnvelopeCodec {
206        /// The unrecognized FourCC value.
207        fourcc: u32,
208    },
209    /// A refusal of the shared media layout or value checks.
210    #[error(transparent)]
211    Layout(LayoutDefect),
212    /// A codec cannot encode this dimension.
213    #[error("{codec} {dimension} {length} exceeds maximum supported value {maximum}")]
214    ImageDimension {
215        /// The codec.
216        codec: ImageCodecKind,
217        /// The dimension.
218        dimension: ImageAxisKind,
219        /// The actual length.
220        length: usize,
221        /// The codec's maximum.
222        maximum: usize,
223    },
224    /// Metadata frame length does not include a trailing NUL terminator.
225    #[error("Metadata frame length does not include a trailing NUL terminator")]
226    MetadataMissingTerminator,
227    /// Metadata frame contains an interior NUL byte.
228    #[error("Metadata frame contains an interior NUL byte")]
229    MetadataInteriorNul,
230    /// Metadata frame has non-zero length with null data pointer.
231    #[error("Metadata frame has non-zero length with null data pointer")]
232    MetadataNullData,
233    /// Video frame has null data pointer.
234    #[error("Video frame has null data pointer")]
235    NullVideoData,
236    /// Audio frame has null data pointer.
237    #[error("Audio frame has null data pointer")]
238    NullAudioData,
239    /// Audio data pointer is not aligned for f32.
240    #[error("Audio data pointer is not aligned for f32")]
241    AudioMisaligned,
242    /// Zero-length audio frame has non-null data pointer.
243    #[error("Zero-length audio frame has non-null data pointer")]
244    EmptyAudioHasData,
245    /// V210 stride must be a multiple of four and cover every complete pixel group.
246    #[error("V210 stride must be a multiple of four and cover every complete pixel group")]
247    V210Stride,
248    /// V210 storage exceeds the video limit.
249    #[error("V210 storage exceeds the video limit")]
250    V210Storage,
251    /// V210 conversion requires a positive width divisible by six.
252    #[error("V210 conversion requires a positive width divisible by six")]
253    V210Width,
254    /// P216 frame format and dimensions must match the V210 layout.
255    #[error("P216 frame format and dimensions must match the V210 layout")]
256    P216LayoutMismatch,
257    /// planar destination rate, channels and samples must match the interleaved source.
258    #[error("planar destination rate, channels and samples must match the interleaved source")]
259    PlanarAudioMismatch,
260    /// The SDK returned FrameSync audio with dimensions different from the request.
261    #[error("FrameSync audio rate, channels and samples must match the request")]
262    FrameSyncAudioMismatch,
263    /// Truncated compressed packet header.
264    #[error("Truncated compressed packet header")]
265    PacketHeaderTruncated,
266    /// Unsupported compressed packet header size.
267    #[error("Unsupported compressed packet header size")]
268    PacketHeaderSize,
269    /// Cannot send a packet with an unsupported header version or unknown flags.
270    #[error("Cannot send a packet with an unsupported header version or unknown flags")]
271    PacketHeaderUnsupported,
272    /// Packet codec does not match the frame's codec.
273    #[error("Packet codec does not match the frame's codec")]
274    PacketCodecMismatch,
275    /// Empty codec payload.
276    #[error("Empty codec payload")]
277    EmptyCodecPayload,
278    /// Packet header lengths do not match the size of the frame.
279    #[error("Packet header lengths do not match the size of the frame")]
280    PacketLengthsMismatch,
281    /// Keyframes require codec configuration data.
282    #[error("Keyframes require codec configuration data")]
283    KeyframeConfigurationMissing,
284    /// AAC packets must carry the keyframe flag.
285    #[error("AAC packets must carry the keyframe flag")]
286    AacKeyframeMissing,
287    /// AAC packets require their AudioSpecificConfig as codec configuration data.
288    #[error("AAC packets require their AudioSpecificConfig as codec configuration data")]
289    AacConfigurationMissing,
290    /// The AAC configuration names a different sample rate than the frame.
291    #[error("The AAC configuration names a different sample rate than the frame")]
292    AacRateMismatch,
293    /// The AAC configuration names a different channel layout than the frame.
294    #[error("The AAC configuration names a different channel layout than the frame")]
295    AacChannelsMismatch,
296    /// Invalid compressed packet length.
297    #[error("Invalid compressed packet length")]
298    PacketLength,
299    /// Compressed packet length overflow.
300    #[error("Compressed packet length overflow")]
301    PacketLengthOverflow,
302    /// Truncated compressed packet.
303    #[error("Truncated compressed packet")]
304    PacketTruncated,
305    /// Packet size overflow.
306    #[error("Packet size overflow")]
307    PacketSizeOverflow,
308    /// Invalid compressed packet payload size.
309    #[error("Invalid compressed packet payload size")]
310    PacketPayloadSize,
311    /// Unknown compressed video FourCC.
312    #[error("Unknown compressed video FourCC")]
313    UnknownCompressedVideo,
314    /// A SpeedHQ frame begins with its quality, a byte below 100.
315    #[error("A SpeedHQ frame begins with its quality, a byte below 100")]
316    SpeedHqQuality,
317    /// An H.264 or HEVC picture on the preview stream is at most 640 pixels wide and 640 high.
318    #[error(
319        "An H.264 or HEVC picture on the preview stream is at most 640 pixels wide and 640 high"
320    )]
321    PreviewVideoDimensions,
322    /// Invalid compressed video size.
323    #[error("Invalid compressed video size")]
324    CompressedVideoSize,
325    /// Truncated SpeedHQ frame.
326    #[error("Truncated SpeedHQ frame")]
327    SpeedHqTruncated,
328    /// Opus is sent at 8000, 12000, 16000, 24000 or 48000 Hz.
329    #[error("Opus is sent at 8000, 12000, 16000, 24000 or 48000 Hz")]
330    OpusSampleRate,
331    /// An Opus frame holds 2.5, 5, 10, 20, 40 or 60 ms of audio.
332    #[error("An Opus frame holds 2.5, 5, 10, 20, 40 or 60 ms of audio")]
333    OpusDuration,
334    /// An AAC frame holds 1024 samples per channel.
335    #[error("An AAC frame holds 1024 samples per channel")]
336    AacSampleCount,
337    /// AAC is sent at a sample rate its configuration can name, from 7350 to 96000 Hz.
338    #[error("AAC is sent at a sample rate its configuration can name, from 7350 to 96000 Hz")]
339    AacSampleRate,
340    /// AAC is sent with one to six or eight channels.
341    #[error("AAC is sent with one to six or eight channels")]
342    AacChannels,
343    /// Invalid compressed audio size.
344    #[error("Invalid compressed audio size")]
345    CompressedAudioSize,
346    /// Invalid compressed frame buffer.
347    #[error("Invalid compressed frame buffer")]
348    CompressedBuffer,
349    /// Invalid scatter block count.
350    #[error("Invalid scatter block count")]
351    ScatterBlockCount,
352    /// Scatter blocks must not be empty.
353    #[error("Scatter blocks must not be empty")]
354    EmptyScatterBlock,
355    /// Scatter frame exceeds the packet size limit.
356    #[error("Scatter frame exceeds the packet size limit")]
357    ScatterSize,
358    /// The first scatter block must hold the frame's complete header.
359    #[error("The first scatter block must hold the frame's complete header")]
360    ScatterHeader,
361    /// Unknown compressed audio FourCC.
362    #[error("Unknown compressed audio FourCC")]
363    UnknownCompressedAudio,
364    /// Unknown scan type: 0x{code:08X}.
365    #[error("Unknown scan type: 0x{code:08X}")]
366    UnknownScanType {
367        /// The code.
368        code: u32,
369    },
370    /// Audio buffer has {actual} samples, requires at least {minimum}.
371    #[error("Audio buffer has {actual} samples, requires at least {minimum}")]
372    AudioBufferTooSmall {
373        /// The actual.
374        actual: usize,
375        /// The minimum.
376        minimum: usize,
377    },
378    /// Metadata frame has negative length: {length}.
379    #[error("Metadata frame has negative length: {length}")]
380    MetadataNegativeLength {
381        /// The length.
382        length: i32,
383    },
384    /// Metadata exceeds maximum size: {length} bytes > {MAX_METADATA_BYTES} bytes.
385    #[error("Metadata exceeds maximum size: {length} bytes > {MAX_METADATA_BYTES} bytes")]
386    MetadataTooLarge {
387        /// The length.
388        length: usize,
389    },
390    /// Frame metadata is missing a NUL terminator within {MAX_METADATA_BYTES} bytes.
391    #[error("Frame metadata is missing a NUL terminator within {MAX_METADATA_BYTES} bytes")]
392    MetadataUnterminated,
393    /// Video data length {actual}, expected {expected} bytes for validated layout.
394    #[error("Video data length {actual}, expected {expected} bytes for validated layout")]
395    VideoDataLength {
396        /// The actual.
397        actual: usize,
398        /// The expected.
399        expected: usize,
400    },
401    /// Audio data length {actual}, expected {expected} samples ({channels} channels x {samples} samples) for validated layout.
402    #[error("{detail}")]
403    AudioDataLength {
404        /// Exact values, boxed only on 32-bit targets.
405        detail: CompactDiagnostic<AudioLengthDefect>,
406    },
407    /// Zero-length audio frame has non-zero channel_stride_in_bytes: {stride}.
408    #[error("Zero-length audio frame has non-zero channel_stride_in_bytes: {stride}")]
409    EmptyAudioStride {
410        /// The stride.
411        stride: i32,
412    },
413    /// Invalid zero-length audio state: sample_rate={sample_rate}, no_channels={channels}.
414    #[error("Invalid zero-length audio state: sample_rate={sample_rate}, no_channels={channels}")]
415    EmptyAudioFormat {
416        /// The sample rate.
417        sample_rate: i32,
418        /// The channels.
419        channels: i32,
420    },
421    /// Unknown audio format FourCC: 0x{fourcc:08X}.
422    #[error("Unknown audio format FourCC: 0x{fourcc:08X}")]
423    UnknownAudioFormat {
424        /// The fourcc.
425        fourcc: u32,
426    },
427    /// Unknown pixel format FourCC: 0x{fourcc:08X}.
428    #[error("Unknown pixel format FourCC: 0x{fourcc:08X}")]
429    UnknownPixelFormat {
430        /// The fourcc.
431        fourcc: u32,
432    },
433    /// FrameSync audio input-format query returned {channels} channels of {samples} samples.
434    #[error(
435        "FrameSync audio input-format query returned {channels} channels of {samples} samples"
436    )]
437    FrameSyncAudioInput {
438        /// The channels.
439        channels: usize,
440        /// The samples.
441        samples: usize,
442    },
443    /// Buffer too small for {format:?}: got {actual} bytes, expected at least {minimum}.
444    #[error("Buffer too small for {format:?}: got {actual} bytes, expected at least {minimum}")]
445    VideoBufferTooSmall {
446        /// The format.
447        format: PixelFormat,
448        /// The actual.
449        actual: usize,
450        /// The minimum.
451        minimum: usize,
452    },
453    /// V210 buffer has {actual} words, requires {minimum}.
454    #[error("V210 buffer has {actual} words, requires {minimum}")]
455    V210BufferTooSmall {
456        /// The actual.
457        actual: usize,
458        /// The minimum.
459        minimum: usize,
460    },
461    /// interleaved audio has {actual} samples, which is not a multiple of {channels} channels.
462    #[error(
463        "interleaved audio has {actual} samples, which is not a multiple of {channels} channels"
464    )]
465    InterleavedAudioLength {
466        /// The actual.
467        actual: usize,
468        /// The channels.
469        channels: u32,
470    },
471    /// audio destination has {actual} samples, requires {minimum}.
472    #[error("audio destination has {actual} samples, requires {minimum}")]
473    AudioDestinationLength {
474        /// The actual.
475        actual: usize,
476        /// The minimum.
477        minimum: usize,
478    },
479    /// The frame's color description cannot be read because its metadata was withheld ({status:?}); ColorPolicy::Override explicitly supplies its color conversion.
480    #[error("The frame's color description cannot be read because its metadata was withheld ({status:?}); ColorPolicy::Override explicitly supplies its color conversion")]
481    ColorMetadataWithheld {
482        /// The status.
483        status: FrameMetadataStatus,
484    },
485    /// The frame's metadata holds ndi_color_info elements that differ: {first:?} and {second:?}.
486    #[error(
487        "The frame's metadata holds ndi_color_info elements that differ: {first:?} and {second:?}"
488    )]
489    ConflictingColorMetadata {
490        /// The first.
491        first: ColorInfo,
492        /// The second.
493        second: ColorInfo,
494    },
495    /// The frame's ndi_color_info gives the {transfer} transfer function; HdrPolicy::CodeValues encodes its code values to a tagged PNG.
496    #[error("The frame's ndi_color_info gives the {transfer} transfer function; HdrPolicy::CodeValues encodes its code values to a tagged PNG")]
497    HdrRefused {
498        /// The transfer.
499        transfer: TransferFunction,
500    },
501
502    /// Malformed color text; the issue is typed and its original diagnostic is boxed.
503    #[error("{diagnostic}")]
504    ColorMetadata {
505        /// The syntax or value refusal.
506        issue: ColorMetadataDefect,
507        /// Original text, including the bounded peer-text excerpt.
508        diagnostic: Box<str>,
509    },
510    /// The encoder's diagnostic, whose content is supplied by that library.
511    #[error("{codec} encoding failed: {diagnostic}")]
512    EncodingFailed {
513        /// The encoder.
514        codec: ImageCodecKind,
515        /// The library diagnostic.
516        diagnostic: Box<str>,
517    },
518}
519/// Typed causes of [`crate::Error::InvalidInput`].
520///
521/// [`InputDefect::Layout`] reports standalone aspect ratios, frame rates,
522/// compressed video formats and allocation strides through [`LayoutDefect`].
523///
524/// Ordinary causes retain their evidence inline without allocating. Boxed
525/// diagnostic fields retain caller or SDK text only for the documented exceptions.
526#[derive(Debug, Clone, PartialEq, Error)]
527#[non_exhaustive]
528pub enum InputDefect {
529    /// A refusal of the shared media layout or value checks.
530    #[error(transparent)]
531    Layout(LayoutDefect),
532
533    /// A list element is empty, contains a comma, or contains a NUL.
534    #[error("{setting} element {index} must be nonempty and contain neither a comma nor a NUL")]
535    ListElement {
536        /// The setting that contains the invalid element.
537        setting: &'static str,
538        /// The zero-based position in the list.
539        index: usize,
540    },
541    /// Host must be a bare hostname, IP address or NDI machine name.
542    #[error("Host must be a bare hostname, IP address or NDI machine name")]
543    InvalidHostQuery,
544    /// PTZ preset must be within 0..=99.
545    #[error("PTZ preset must be within 0..=99")]
546    PtzPreset,
547    /// an explicit NDI library path must be absolute.
548    #[error("an explicit NDI library path must be absolute")]
549    RelativeLibraryPath,
550    /// a listener accepts one Discovery Server endpoint.
551    #[error("a listener accepts one Discovery Server endpoint")]
552    MultipleDiscoveryServers,
553    /// the registration was issued by another advertiser.
554    #[error("the registration was issued by another advertiser")]
555    ForeignRegistration,
556    /// a recorder must record video, audio or metadata; an empty track selection would record all three.
557    #[error("a recorder must record video, audio or metadata; an empty track selection would record all three")]
558    EmptyRecordingTracks,
559    /// a recorder with an exact file name cannot roll over at a format change, because the next file would have the same name; use a filename pattern with `{index}`, or leave format-change rollover unset.
560    #[error("a recorder with an exact file name cannot roll over at a format change, because the next file would have the same name; use a filename pattern with {{index}}, or leave format-change rollover unset")]
561    ExactNameFormatRollover,
562    /// a recorder with an exact file name cannot roll over at a size limit, because the next file would have the same name; use a filename pattern with `{index}`.
563    #[error("a recorder with an exact file name cannot roll over at a size limit, because the next file would have the same name; use a filename pattern with {{index}}")]
564    ExactNameSizeRollover,
565    /// unmatched filename-pattern brace.
566    #[error("unmatched filename-pattern brace")]
567    FilenamePatternBrace,
568    /// A filename index would change the output directory.
569    #[error(
570        "filename-pattern indexes must be in the file name; move {{index}} out of the directory"
571    )]
572    FilenamePatternIndexInDirectory,
573    /// The expanded recording path ends without a file name.
574    #[error("recording file path must end with a file name")]
575    RecordingPathMissingFilename,
576    /// file position exceeds 64-bit ticks.
577    #[error("file position exceeds 64-bit ticks")]
578    FilePositionOverflow,
579    /// a recording start cannot use Timecode::SYNTHESIZE; choose an explicit start such as zero.
580    #[error(
581        "a recording start cannot use Timecode::SYNTHESIZE; choose an explicit start such as zero"
582    )]
583    SynthesizeRecordingStart,
584    /// the session counter is exhausted.
585    #[error("the session counter is exhausted")]
586    SessionCounterExhausted,
587    /// the recorder generation is exhausted.
588    #[error("the recorder generation is exhausted")]
589    RecorderGenerationExhausted,
590    /// Allocator limits must be positive.
591    #[error("Allocator limits must be positive")]
592    AllocatorPositiveLimits,
593    /// The allocation limit exceeds the maximum supported receive allocation.
594    #[error("max_allocation_bytes exceeds {MAX_ALLOCATION_BYTES} bytes")]
595    AllocatorAllocationLimit,
596    /// max_concurrent_calls exceeds max_allocations, which counts every call in progress.
597    #[error("max_concurrent_calls exceeds max_allocations, which counts every call in progress")]
598    AllocatorConcurrentLimit,
599    /// max_bytes is less than max_concurrent_calls allocations of max_allocation_bytes.
600    #[error("max_bytes is less than max_concurrent_calls allocations of max_allocation_bytes")]
601    AllocatorByteLimit,
602    /// Compressed allocations have a byte size, not a configurable stride.
603    #[error("Compressed allocations have a byte size, not a configurable stride")]
604    CompressedAllocationStride,
605    /// External allocation is smaller than the request's minimum.
606    #[error("External allocation is smaller than the request's minimum")]
607    ExternalAllocationTooSmall,
608    /// External allocation is larger than the request's capacity limit.
609    #[error("External allocation is larger than the request's capacity limit")]
610    ExternalAllocationTooLarge,
611    /// External allocation is not aligned to 64 bytes.
612    #[error("External allocation is not aligned to 64 bytes")]
613    ExternalAllocationAlignment,
614    /// Process allocator generation budget exhausted.
615    #[error("Process allocator generation budget exhausted")]
616    AllocatorGenerationBudget,
617    /// Allocator token space exhausted.
618    #[error("Allocator token space exhausted")]
619    AllocatorTokensExhausted,
620    /// Allocator limits differ from the existing process allocator service.
621    #[error("Allocator limits differ from the existing process allocator service")]
622    AllocatorLimitsDiffer,
623    /// Advanced configuration exceeds its byte limit.
624    #[error("Advanced configuration exceeds its byte limit")]
625    ConfigurationTooLarge,
626    /// Invalid Advanced configuration JSON.
627    #[error("Invalid Advanced configuration JSON")]
628    ConfigurationJson,
629    /// Advanced configuration must be a JSON object.
630    #[error("Advanced configuration must be a JSON object")]
631    ConfigurationNotObject,
632    /// queue requires 1..=65536 frames and a positive addressable byte limit.
633    #[error("queue requires 1..=65536 frames and a positive addressable byte limit")]
634    QueueLimits,
635    /// queue submission identifiers exhausted.
636    #[error("queue submission identifiers exhausted")]
637    QueueIdentifiersExhausted,
638    /// queued conversion requires a sender without advertiser registrations.
639    #[error("queued conversion requires a sender without advertiser registrations")]
640    QueuedSenderRegistered,
641    /// timeout {requested:?} exceeds MAX_TIMEOUT (4294967294 ms, about 49.7 days).
642    #[error("timeout {requested:?} exceeds MAX_TIMEOUT (4294967294 ms, about 49.7 days)")]
643    TimeoutTooLong {
644        /// The requested.
645        requested: DiagnosticDuration,
646    },
647    /// timeout {requested:?} ends at an instant this platform cannot represent.
648    #[error("timeout {requested:?} ends at an instant this platform cannot represent")]
649    TimeoutInstantOverflow {
650        /// The requested.
651        requested: DiagnosticDuration,
652    },
653    /// receive delay {requested:?} exceeds 2000 ms.
654    #[error("receive delay {requested:?} exceeds {} ms", crate::ReceiveDelay::MAX.to_sdk())]
655    ReceiveDelayTooLong {
656        /// The requested.
657        requested: DiagnosticDuration,
658    },
659    /// {name} must be finite and within {minimum}..={maximum}.
660    #[error("{detail}")]
661    PtzValue {
662        /// Exact values, boxed only on 32-bit targets.
663        detail: CompactDiagnostic<PtzDefect>,
664    },
665    /// {member} is already registered.
666    #[error("{member} is already registered")]
667    AlreadyRegistered {
668        /// The member.
669        member: &'static str,
670    },
671    /// {what} must not be empty.
672    #[error("{what} must not be empty")]
673    Empty {
674        /// The what.
675        what: &'static str,
676    },
677    /// {what} is not lossless UTF-8.
678    #[error("{what} is not lossless UTF-8")]
679    PathNotUtf8 {
680        /// The what.
681        what: &'static str,
682    },
683    /// unsupported filename-pattern token {{{token}}}.
684    #[error("unsupported filename-pattern token {{{token}}}")]
685    FilenamePatternToken {
686        /// The token.
687        token: Box<str>,
688    },
689    /// async {queue} queue capacity must be between 1 and 4096, not {capacity}.
690    #[error("async {queue} queue capacity must be between 1 and 4096, not {capacity}")]
691    FileQueueCapacity {
692        /// The queue.
693        queue: &'static str,
694        /// The capacity.
695        capacity: usize,
696    },
697    /// An allocation of {bytes} bytes exceeds the capacity limit of {limit} bytes.
698    #[error("An allocation of {bytes} bytes exceeds the capacity limit of {limit} bytes")]
699    AllocationTooLarge {
700        /// The bytes.
701        bytes: usize,
702        /// The limit.
703        limit: usize,
704    },
705    /// KVM key symbol {keysym:#x} exceeds the SDK's range, 0..=0x7fffffff.
706    #[error("KVM key symbol {keysym:#x} exceeds the SDK's range, 0..=0x7fffffff")]
707    KvmKeySymbol {
708        /// The keysym.
709        keysym: u32,
710    },
711    /// KVM position ({x}, {y}) is not within 0..=1 on each axis.
712    #[error("KVM position ({x}, {y}) is not within 0..=1 on each axis")]
713    KvmPosition {
714        /// The x.
715        x: f32,
716        /// The y.
717        y: f32,
718    },
719    /// KVM wheel units {units} are not finite.
720    #[error("KVM wheel units {units} are not finite")]
721    KvmWheel {
722        /// The units.
723        units: f32,
724    },
725    /// {count} KVM touch points are more than the SDK can count.
726    #[error("{count} KVM touch points are more than the SDK can count")]
727    KvmTouchCount {
728        /// The count.
729        count: usize,
730    },
731    /// frame retains {bytes} bytes of allocation capacity, exceeding the queue's {limit} byte limit.
732    #[error("frame retains {bytes} bytes of allocation capacity, exceeding the queue's {limit} byte limit")]
733    QueueFrameTooLarge {
734        /// The bytes.
735        bytes: usize,
736        /// The limit.
737        limit: usize,
738    },
739    /// A codec setting falls outside its supported range.
740    #[error("{codec} {setting} must be in {minimum}..={maximum}, got {value}")]
741    ImageSetting {
742        /// The codec.
743        codec: ImageCodecKind,
744        /// The setting.
745        setting: ImageSettingKind,
746        /// The requested value.
747        value: u8,
748        /// The minimum.
749        minimum: u8,
750        /// The maximum.
751        maximum: u8,
752    },
753    /// {codec} images are 8 bits a channel; SampleDepth::Sixteen needs ImageFormat::Png.
754    #[error("{codec} images are 8 bits a channel; SampleDepth::Sixteen needs ImageFormat::Png")]
755    SixteenBitNeedsPng {
756        /// The codec.
757        codec: ImageCodecKind,
758    },
759    /// The image needs a color tag and only PNG can write it.
760    #[error(
761        "{codec} cannot carry the required color tag for {} primaries and {} transfer. Use ImageFormat::Png",
762        primaries.map_or("unspecified", ColorPrimaries::name),
763        transfer.map_or("SDR", TransferFunction::name)
764    )]
765    ColorTagNeedsPng {
766        /// The codec.
767        codec: ImageCodecKind,
768        /// The frame's primaries, if known.
769        primaries: Option<ColorPrimaries>,
770        /// The frame's transfer, if given.
771        transfer: Option<TransferFunction>,
772    },
773    /// The expanded SDK filename is relative on this platform.
774    #[error("the expanded recording file path must be absolute. Use {{prefix}} with a RecordingTarget or supply an absolute pattern")]
775    RecordingPathNotAbsolute,
776    /// recording file path may reach {longest_bytes} UTF-8 bytes, exceeding the {maximum_bytes}-byte event path limit ({index_digits_reserved} digits reserved for index growth).
777    #[error("recording file path may reach {longest_bytes} UTF-8 bytes, exceeding the {maximum_bytes}-byte event path limit ({index_digits_reserved} digits reserved for index growth)")]
778    RecordingPathTooLong {
779        /// The maximum bytes.
780        maximum_bytes: usize,
781        /// The longest bytes.
782        longest_bytes: usize,
783        /// The index digits reserved.
784        index_digits_reserved: usize,
785    },
786
787    /// The SDK refused the supplied address; arbitrary address text is boxed.
788    #[error("{0}")]
789    DiscoveryAddressRejected(Box<DiscoveryAddressFailure>),
790    /// No server was named in the options, and the SDK resolved no usable
791    /// Discovery Server from its configuration.
792    #[error("the SDK created no {object}: no Discovery Server was named, and the configuration names none it accepts")]
793    DiscoveryConfigurationRejected {
794        /// The kind of object the SDK refused to create.
795        object: &'static str,
796    },
797    /// SpeedHQ guidance was applied to another codec.
798    #[cfg(feature = "advanced")]
799    #[error("SpeedHQ quality guidance does not apply to {codec:?}")]
800    SpeedHqCodec {
801        /// The requested codec.
802        codec: crate::advanced::VideoCodec,
803    },
804}
805/// Typed causes of [`crate::Error::UnexpectedSdkResult`].
806///
807/// Causes retain their evidence inline without allocating.
808#[derive(Debug, Clone, PartialEq, Error, Copy, Eq, Hash)]
809#[non_exhaustive]
810pub enum SdkResultDefect {
811    /// native completion protocol failed; use QueuedSender::close to recover retained frames.
812    #[error(
813        "native completion protocol failed; use QueuedSender::close to recover retained frames"
814    )]
815    UnknownCompletion,
816    /// {operation} returned a negative count: {value}.
817    #[error("{operation} returned a negative count: {value}")]
818    NegativeCount {
819        /// The operation.
820        operation: crate::NativeFunction,
821        /// The value.
822        value: DiagnosticInteger,
823    },
824    /// {operation} returned a string longer than the 4 MiB one string may be.
825    #[error("{operation} returned a string longer than the 4 MiB one string may be")]
826    UnterminatedText {
827        /// The operation.
828        operation: crate::NativeFunction,
829    },
830    /// SDK returned invalid receive delay: {millis} ms.
831    #[error("SDK returned invalid receive delay: {millis} ms")]
832    InvalidReceiveDelay {
833        /// The millis.
834        millis: i32,
835    },
836    /// the source format reports a negative {what}: {value}.
837    #[error("the source format reports a negative {what}: {value}")]
838    NegativeFormatCount {
839        /// The what.
840        what: &'static str,
841        /// The value.
842        value: i32,
843    },
844    /// source format reports {count} video tracks; the SDK layout holds {capacity}.
845    #[error("source format reports {count} video tracks; the SDK layout holds {capacity}")]
846    FileTrackCount {
847        /// The count.
848        count: u32,
849        /// The capacity.
850        capacity: usize,
851    },
852    /// the File library wrote past the {bytes} bytes this crate's SDK headers give {name}.
853    #[error("the File library wrote past the {bytes} bytes this crate's SDK headers give {name}")]
854    FileStructureTooLarge {
855        /// The bytes.
856        bytes: usize,
857        /// The name.
858        name: &'static str,
859    },
860    /// {diagnostic}.
861    #[error("{diagnostic}")]
862    EventTypeMismatch {
863        /// The diagnostic.
864        diagnostic: &'static str,
865    },
866    /// {operation} returned {value}.
867    #[error("{operation} returned {value}")]
868    InvalidGuidance {
869        /// The operation.
870        operation: crate::NativeFunction,
871        /// The value.
872        value: i32,
873    },
874    /// NDIlib_avsync_synchronize reported a format change to {sample_rate} Hz and {channels} channels.
875    #[error("NDIlib_avsync_synchronize reported a format change to {sample_rate} Hz and {channels} channels")]
876    AvSyncFormatChange {
877        /// The sample rate.
878        sample_rate: i32,
879        /// The channels.
880        channels: i32,
881    },
882    /// {operation} returned unknown status {code}.
883    #[error("{operation} returned unknown status {code}")]
884    UnknownStatus {
885        /// The operation.
886        operation: crate::NativeFunction,
887        /// The code.
888        code: i32,
889    },
890    /// {operation} returned {kind}.
891    #[error("{operation} returned {kind}")]
892    UnexpectedFrameType {
893        /// The operation.
894        operation: crate::NativeFunction,
895        /// The kind.
896        kind: u32,
897    },
898
899    /// A native discovery descriptor violates its array contract.
900    #[error("{0}")]
901    MalformedDiscoveryData(DiscoveryDefect),
902}
903
904/// The image axis that exceeded an encoder limit.
905#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
906#[non_exhaustive]
907pub enum ImageAxisKind {
908    /// Width.
909    #[error("width")]
910    Width,
911    /// Height.
912    #[error("height")]
913    Height,
914}
915
916/// Exact diagnostic evidence, inline on 64-bit targets and boxed on 32-bit targets.
917///
918/// Only the wide cold-path causes use this holder. Boxing on 32-bit targets
919/// preserves the existing compact `Error` budget while keeping every diagnostic
920/// value. Common layout, timeout, HDR and withheld-metadata causes stay inline.
921#[derive(Debug, Clone, PartialEq, Eq, Hash)]
922pub struct CompactDiagnostic<T> {
923    #[cfg(target_pointer_width = "64")]
924    value: T,
925    #[cfg(not(target_pointer_width = "64"))]
926    value: Box<T>,
927}
928impl<T> CompactDiagnostic<T> {
929    /// Retain exact diagnostic evidence.
930    #[must_use]
931    pub fn new(value: T) -> Self {
932        Self {
933            #[cfg(target_pointer_width = "64")]
934            value,
935            #[cfg(not(target_pointer_width = "64"))]
936            value: Box::new(value),
937        }
938    }
939    /// Recover the evidence without another allocation.
940    #[must_use]
941    pub fn into_inner(self) -> T {
942        #[cfg(target_pointer_width = "64")]
943        {
944            self.value
945        }
946        #[cfg(not(target_pointer_width = "64"))]
947        {
948            *self.value
949        }
950    }
951}
952impl<T> std::ops::Deref for CompactDiagnostic<T> {
953    type Target = T;
954    fn deref(&self) -> &T {
955        &self.value
956    }
957}
958impl<T: std::fmt::Display> std::fmt::Display for CompactDiagnostic<T> {
959    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
960        std::fmt::Display::fmt(&**self, f)
961    }
962}
963
964/// The audio count that failed validation.
965#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
966#[non_exhaustive]
967pub enum AudioCountKind {
968    /// Channel count.
969    #[error("channels")]
970    Channels,
971    /// Samples per channel.
972    #[error("samples")]
973    Samples,
974}
975
976/// Exact values reported by `FrameRate`.
977#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
978#[error("Invalid frame rate {numerator}/{denominator}: both parts must be in 1..=2147483647")]
979pub struct FrameRateDefect {
980    /// The numerator.
981    pub numerator: i64,
982    /// The denominator.
983    pub denominator: i64,
984}
985
986/// Exact values reported by `CompressedVideoDimensions`.
987#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
988#[error("Compressed video dimensions {width}x{height} must each be in 1..=2147483647")]
989pub struct VideoDimensionsDefect {
990    /// The width.
991    pub width: i64,
992    /// The height.
993    pub height: i64,
994}
995
996/// Exact values reported by `AudioDataLength`.
997#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
998#[error("Audio data length {actual}, expected {expected} samples ({channels} channels x {samples} samples) for validated layout")]
999pub struct AudioLengthDefect {
1000    /// The actual.
1001    pub actual: usize,
1002    /// The expected.
1003    pub expected: usize,
1004    /// The channels.
1005    pub channels: u32,
1006    /// The samples.
1007    pub samples: u32,
1008}
1009
1010/// Exact values reported by `PtzValue`.
1011#[derive(Debug, Clone, Copy, PartialEq, Error)]
1012#[error("{name} must be finite and within {minimum}..={maximum}")]
1013pub struct PtzDefect {
1014    /// The name.
1015    pub name: &'static str,
1016    /// The minimum.
1017    pub minimum: f32,
1018    /// The maximum.
1019    pub maximum: f32,
1020}
1021
1022/// An exact unsigned byte count with 32-bit alignment.
1023///
1024/// Layout size refusals retain counts beyond the address space of 32-bit
1025/// targets without allocating or increasing the alignment of an error.
1026#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1027pub struct DiagnosticSize([u32; 2]);
1028impl DiagnosticSize {
1029    /// Retain the byte count without allocating.
1030    #[must_use]
1031    pub const fn new(value: u64) -> Self {
1032        Self([value as u32, (value >> 32) as u32])
1033    }
1034    /// The original unsigned byte count.
1035    #[must_use]
1036    pub const fn get(self) -> u64 {
1037        (self.0[0] as u64) | ((self.0[1] as u64) << 32)
1038    }
1039}
1040impl From<u64> for DiagnosticSize {
1041    fn from(value: u64) -> Self {
1042        Self::new(value)
1043    }
1044}
1045impl std::fmt::Display for DiagnosticSize {
1046    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1047        std::fmt::Display::fmt(&self.get(), f)
1048    }
1049}
1050impl std::fmt::Debug for DiagnosticSize {
1051    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1052        std::fmt::Debug::fmt(&self.get(), f)
1053    }
1054}
1055
1056/// An exact signed 64-bit diagnostic value with 32-bit alignment.
1057///
1058/// Two words keep common layout refusals inline even on 32-bit MSVC, where an
1059/// `i64` field would enlarge every `Error`. Read the original value with `get`.
1060#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1061pub struct DiagnosticInteger([u32; 2]);
1062impl DiagnosticInteger {
1063    /// Retain all bits without allocating or depending on native i64 alignment.
1064    #[must_use]
1065    pub const fn new(value: i64) -> Self {
1066        let bits = value as u64;
1067        Self([bits as u32, (bits >> 32) as u32])
1068    }
1069    /// The original signed value.
1070    #[must_use]
1071    pub const fn get(self) -> i64 {
1072        ((self.0[0] as u64) | ((self.0[1] as u64) << 32)) as i64
1073    }
1074}
1075impl From<i64> for DiagnosticInteger {
1076    fn from(value: i64) -> Self {
1077        Self::new(value)
1078    }
1079}
1080impl From<i32> for DiagnosticInteger {
1081    fn from(value: i32) -> Self {
1082        Self::new(value.into())
1083    }
1084}
1085impl From<u32> for DiagnosticInteger {
1086    fn from(value: u32) -> Self {
1087        Self::new(value.into())
1088    }
1089}
1090impl std::fmt::Display for DiagnosticInteger {
1091    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1092        std::fmt::Display::fmt(&self.get(), f)
1093    }
1094}
1095impl std::fmt::Debug for DiagnosticInteger {
1096    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1097        std::fmt::Debug::fmt(&self.get(), f)
1098    }
1099}
1100
1101/// Exact timeout evidence, stored in three 32-bit words without allocation.
1102///
1103/// `get` returns the original `Duration`; `Debug` uses its usual diagnostic
1104/// format. The stable alignment preserves the compact Error budget on MSVC.
1105#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1106pub struct DiagnosticDuration {
1107    seconds: [u32; 2],
1108    nanoseconds: u32,
1109}
1110impl DiagnosticDuration {
1111    /// Retain a duration exactly without allocating.
1112    #[must_use]
1113    pub const fn new(value: Duration) -> Self {
1114        let seconds = value.as_secs();
1115        Self {
1116            seconds: [seconds as u32, (seconds >> 32) as u32],
1117            nanoseconds: value.subsec_nanos(),
1118        }
1119    }
1120    /// The original duration, reconstructed in aligned stack storage.
1121    #[must_use]
1122    pub const fn get(self) -> Duration {
1123        Duration::new(
1124            (self.seconds[0] as u64) | ((self.seconds[1] as u64) << 32),
1125            self.nanoseconds,
1126        )
1127    }
1128}
1129impl From<Duration> for DiagnosticDuration {
1130    fn from(value: Duration) -> Self {
1131        Self::new(value)
1132    }
1133}
1134impl PartialEq<Duration> for DiagnosticDuration {
1135    fn eq(&self, other: &Duration) -> bool {
1136        self.get() == *other
1137    }
1138}
1139impl PartialEq<DiagnosticDuration> for Duration {
1140    fn eq(&self, other: &DiagnosticDuration) -> bool {
1141        *self == other.get()
1142    }
1143}
1144impl std::fmt::Debug for DiagnosticDuration {
1145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1146        std::fmt::Debug::fmt(&self.get(), f)
1147    }
1148}