Skip to main content

rtci_shared/
error.rs

1//! The error type shared across the stack.
2//!
3//! One [`Error`](crate::error::Error) enum spans every layer — buffers, UDP, ICE, DTLS, SCTP, SRTP, RTP/RTCP, SDP and
4//! the data channel — so a value can propagate from the innermost codec to the application
5//! without conversion at each boundary. The higher-level crates re-export it, which is why an
6//! application only ever imports one error type.
7#![allow(dead_code)]
8
9use std::io;
10use std::net;
11use std::net::SocketAddr;
12use std::num::ParseIntError;
13use std::string::FromUtf8Error;
14use std::time::SystemTimeError;
15use substring::Substring;
16use thiserror::Error;
17
18/// A type alias for `std::result::Result` with this crate's [`enum@Error`] type.
19pub type Result<T> = std::result::Result<T, Error>;
20
21/// Unified error type for all WebRTC sub-protocols.
22///
23/// Aggregates errors from every layer of the WebRTC stack — buffers, RTP/RTCP,
24/// SRTP, STUN, TURN, ICE, DTLS, SCTP, data channels, SDP, mDNS, and the
25/// top-level peer connection — into a single enum so callers only need to
26/// handle one error type.
27///
28/// The enum is `#[non_exhaustive]`: new variants may be added in future
29/// releases without a semver-breaking change.
30#[derive(Error, Debug, PartialEq)]
31#[non_exhaustive]
32pub enum Error {
33    /// Buffer: full.
34    #[error("buffer: full")]
35    ErrBufferFull,
36    /// Buffer: closed.
37    #[error("buffer: closed")]
38    ErrBufferClosed,
39    /// Buffer: short.
40    #[error("buffer: short")]
41    ErrBufferShort,
42    /// Packet too big.
43    #[error("packet too big")]
44    ErrPacketTooBig,
45    /// I/O timeout.
46    #[error("i/o timeout")]
47    ErrTimeout,
48    /// UDP: listener closed.
49    #[error("udp: listener closed")]
50    ErrClosedListener,
51    /// UDP: listen queue exceeded.
52    #[error("udp: listen queue exceeded")]
53    ErrListenQueueExceeded,
54    /// UDP: listener accept ch closed.
55    #[error("udp: listener accept ch closed")]
56    ErrClosedListenerAcceptCh,
57    /// Obs cannot be nil.
58    #[error("obs cannot be nil")]
59    ErrObsCannotBeNil,
60    /// Se of closed network connection.
61    #[error("se of closed network connection")]
62    ErrUseClosedNetworkConn,
63    /// Addr is not a net.UDPAddr.
64    #[error("addr is not a net.UDPAddr")]
65    ErrAddrNotUdpAddr,
66    /// Something went wrong with locAddr.
67    #[error("something went wrong with locAddr")]
68    ErrLocAddr,
69    /// Already closed.
70    #[error("already closed")]
71    ErrAlreadyClosed,
72    /// No remAddr defined.
73    #[error("no remAddr defined")]
74    ErrNoRemAddr,
75    /// Address already in use.
76    #[error("address already in use")]
77    ErrAddressAlreadyInUse,
78    /// No such UDPConn.
79    #[error("no such UDPConn")]
80    ErrNoSuchUdpConn,
81    /// Cannot remove unspecified IP by the specified IP.
82    #[error("cannot remove unspecified IP by the specified IP")]
83    ErrCannotRemoveUnspecifiedIp,
84    /// No address assigned.
85    #[error("no address assigned")]
86    ErrNoAddressAssigned,
87    /// 1:1 NAT requires more than one mapping.
88    #[error("1:1 NAT requires more than one mapping")]
89    ErrNatRequriesMapping,
90    /// Length mismtach between mappedIPs and localIPs.
91    #[error("length mismtach between mappedIPs and localIPs")]
92    ErrMismatchLengthIp,
93    /// Non-udp translation is not supported yet.
94    #[error("non-udp translation is not supported yet")]
95    ErrNonUdpTranslationNotSupported,
96    /// No associated local address.
97    #[error("no associated local address")]
98    ErrNoAssociatedLocalAddress,
99    /// No NAT binding found.
100    #[error("no NAT binding found")]
101    ErrNoNatBindingFound,
102    /// Has no permission.
103    #[error("has no permission")]
104    ErrHasNoPermission,
105    /// Host name must not be empty.
106    #[error("host name must not be empty")]
107    ErrHostnameEmpty,
108    /// Failed to parse IP address.
109    #[error("failed to parse IP address")]
110    ErrFailedToParseIpaddr,
111    /// No interface is available.
112    #[error("no interface is available")]
113    ErrNoInterface,
114    /// Not found.
115    #[error("not found")]
116    ErrNotFound,
117    /// Unexpected network.
118    #[error("unexpected network")]
119    ErrUnexpectedNetwork,
120    /// Can't assign requested address.
121    #[error("can't assign requested address")]
122    ErrCantAssignRequestedAddr,
123    /// Unknown network.
124    #[error("unknown network")]
125    ErrUnknownNetwork,
126    /// No router linked.
127    #[error("no router linked")]
128    ErrNoRouterLinked,
129    /// Invalid port number.
130    #[error("invalid port number")]
131    ErrInvalidPortNumber,
132    /// Unexpected type-switch failure.
133    #[error("unexpected type-switch failure")]
134    ErrUnexpectedTypeSwitchFailure,
135    /// Bind failed.
136    #[error("bind failed")]
137    ErrBindFailed,
138    /// End port is less than the start.
139    #[error("end port is less than the start")]
140    ErrEndPortLessThanStart,
141    /// Port space exhausted.
142    #[error("port space exhausted")]
143    ErrPortSpaceExhausted,
144    /// Vnet is not enabled.
145    #[error("vnet is not enabled")]
146    ErrVnetDisabled,
147    /// Invalid local IP in static_ips.
148    #[error("invalid local IP in static_ips")]
149    ErrInvalidLocalIpInStaticIps,
150    /// Mapped in static_ips is beyond subnet.
151    #[error("mapped in static_ips is beyond subnet")]
152    ErrLocalIpBeyondStaticIpsSubset,
153    /// All static_ips must have associated local IPs.
154    #[error("all static_ips must have associated local IPs")]
155    ErrLocalIpNoStaticsIpsAssociated,
156    /// Router already started.
157    #[error("router already started")]
158    ErrRouterAlreadyStarted,
159    /// Router already stopped.
160    #[error("router already stopped")]
161    ErrRouterAlreadyStopped,
162    /// Static IP is beyond subnet.
163    #[error("static IP is beyond subnet")]
164    ErrStaticIpIsBeyondSubnet,
165    /// Address space exhausted.
166    #[error("address space exhausted")]
167    ErrAddressSpaceExhausted,
168    /// No IP address is assigned for eth0.
169    #[error("no IP address is assigned for eth0")]
170    ErrNoIpaddrEth0,
171    /// Invalid mask.
172    #[error("Invalid mask")]
173    ErrInvalidMask,
174
175    //ExportKeyingMaterial errors
176    /// TLS handshake is in progress.
177    #[error("tls handshake is in progress")]
178    HandshakeInProgress,
179    /// Context is not supported for export_keying_material.
180    #[error("context is not supported for export_keying_material")]
181    ContextUnsupported,
182    /// Export_keying_material can not be used with a reserved label.
183    #[error("export_keying_material can not be used with a reserved label")]
184    ReservedExportKeyingMaterial,
185    /// No cipher suite for export_keying_material.
186    #[error("no cipher suite for export_keying_material")]
187    CipherSuiteUnset,
188    /// Export_keying_material hash.
189    #[error("export_keying_material hash: {0}")]
190    Hash(String),
191    /// Mutex poison.
192    #[error("mutex poison: {0}")]
193    PoisonError(String),
194
195    //RTCP errors
196    /// Wrong marshal size.
197    #[error("Wrong marshal size")]
198    WrongMarshalSize,
199    /// Packet lost exceeds maximum amount of packets
200    /// that can possibly be lost.
201    #[error("Invalid total lost count")]
202    InvalidTotalLost,
203    /// Packet contains an invalid header.
204    #[error("Invalid header")]
205    InvalidHeader,
206    /// Packet contains empty compound.
207    #[error("Empty compound packet")]
208    EmptyCompound,
209    /// Invalid first packet in compound packets. First packet
210    /// should either be a SenderReport packet or ReceiverReport
211    #[error("First packet in compound must be SR or RR")]
212    BadFirstPacket,
213    /// CNAME was not defined.
214    #[error("Compound missing SourceDescription with CNAME")]
215    MissingCname,
216    /// Packet was defined before CNAME.
217    #[error("Feedback packet seen before CNAME")]
218    PacketBeforeCname,
219    /// Too many reports.
220    #[error("Too many reports")]
221    TooManyReports,
222    /// Too many chunks.
223    #[error("Too many chunks")]
224    TooManyChunks,
225    /// Too many sources.
226    #[error("too many sources")]
227    TooManySources,
228    /// Packet received is too short.
229    #[error("Packet too short to be read")]
230    PacketTooShort,
231    /// Buffer is too short.
232    #[error("Buffer too short to be written")]
233    BufferTooShort,
234    /// Wrong packet type.
235    #[error("Wrong packet type")]
236    WrongType,
237    /// SDES received is too long.
238    #[error("SDES must be < 255 octets long")]
239    SdesTextTooLong,
240    /// SDES type is missing.
241    #[error("SDES item missing type")]
242    SdesMissingType,
243    /// An RTCP CNAME given to a connection that is not 1 to 255 octets (RFC 3550 section 6.5:
244    /// an SDES item's text has an 8-bit length; RFC 7022: a CNAME names its source).
245    #[error("an RTCP CNAME must be 1 to 255 octets long")]
246    ErrRtcpCnameLength,
247    /// Reason is too long.
248    #[error("Reason must be < 255 octets long")]
249    ReasonTooLong,
250    /// Invalid packet version.
251    #[error("Invalid packet version")]
252    BadVersion,
253    /// Invalid padding value.
254    #[error("Invalid padding value")]
255    WrongPadding,
256    /// Wrong feedback message type.
257    #[error("Wrong feedback message type")]
258    WrongFeedbackType,
259    /// Wrong payload type.
260    #[error("Wrong payload type")]
261    WrongPayloadType,
262    /// Header length is too small.
263    #[error("Header length is too small")]
264    HeaderTooSmall,
265    /// Media ssrc was defined as zero.
266    #[error("Media SSRC must be 0")]
267    SsrcMustBeZero,
268    /// Missing REMB identifier.
269    #[error("Missing REMB identifier")]
270    MissingRembIdentifier,
271    /// SSRC number and length mismatches.
272    #[error("SSRC num and length do not match")]
273    SsrcNumAndLengthMismatch,
274    /// Invalid size or start index.
275    #[error("Invalid size or startIndex")]
276    InvalidSizeOrStartIndex,
277    /// Delta exceeds limit.
278    #[error("Delta exceed limit")]
279    DeltaExceedLimit,
280    /// Packet status chunk is not 2 bytes.
281    #[error("Packet status chunk must be 2 bytes")]
282    PacketStatusChunkLength,
283    /// Invalid bitrate.
284    #[error("Invalid bitrate")]
285    InvalidBitrate,
286    /// Wrong chunk type.
287    #[error("Wrong chunk type")]
288    WrongChunkType,
289    /// Struct contains unexpected member type.
290    #[error("Struct contains unexpected member type")]
291    BadStructMemberType,
292    /// Cannot read into non-pointer.
293    #[error("Cannot read into non-pointer")]
294    BadReadParameter,
295    /// Invalid block size.
296    #[error("Invalid block size")]
297    InvalidBlockSize,
298
299    //RTP errors
300    /// RTP header size insufficient.
301    #[error("RTP header size insufficient")]
302    ErrHeaderSizeInsufficient,
303    /// RTP header size insufficient for extension.
304    #[error("RTP header size insufficient for extension")]
305    ErrHeaderSizeInsufficientForExtension,
306    /// Buffer too small.
307    #[error("buffer too small")]
308    ErrBufferTooSmall,
309    /// Extension not enabled.
310    #[error("extension not enabled")]
311    ErrHeaderExtensionsNotEnabled,
312    /// Extension not found.
313    #[error("extension not found")]
314    ErrHeaderExtensionNotFound,
315
316    /// Header extension id must be between 1 and 14 for RFC 5285 extensions.
317    #[error("header extension id must be between 1 and 14 for RFC 5285 extensions")]
318    ErrRfc8285oneByteHeaderIdrange,
319    /// Header extension payload must be 16bytes or less for RFC 5285 one byte extensions.
320    #[error("header extension payload must be 16bytes or less for RFC 5285 one byte extensions")]
321    ErrRfc8285oneByteHeaderSize,
322
323    /// Header extension id must be between 1 and 255 for RFC 5285 extensions.
324    #[error("header extension id must be between 1 and 255 for RFC 5285 extensions")]
325    ErrRfc8285twoByteHeaderIdrange,
326    /// Header extension payload must be 255bytes or less for RFC 5285 two byte extensions.
327    #[error("header extension payload must be 255bytes or less for RFC 5285 two byte extensions")]
328    ErrRfc8285twoByteHeaderSize,
329
330    /// Header extension id must be 0 for none RFC 5285 extensions.
331    #[error("header extension id must be 0 for none RFC 5285 extensions")]
332    ErrRfc3550headerIdrange,
333
334    /// Packet is not large enough.
335    #[error("packet is not large enough")]
336    ErrShortPacket,
337    /// Invalid nil packet.
338    #[error("invalid nil packet")]
339    ErrNilPacket,
340    /// Too many PDiff.
341    #[error("too many PDiff")]
342    ErrTooManyPDiff,
343    /// Too many spatial layers.
344    #[error("too many spatial layers")]
345    ErrTooManySpatialLayers,
346    /// NALU Type is unhandled.
347    #[error("NALU Type is unhandled")]
348    ErrUnhandledNaluType,
349
350    /// Corrupted H265 packet.
351    #[error("corrupted h265 packet")]
352    ErrH265CorruptedPacket,
353    /// Invalid H265 packet type.
354    #[error("invalid h265 packet type")]
355    ErrInvalidH265PacketType,
356
357    /// Payload is too small for OBU extension header.
358    #[error("payload is too small for OBU extension header")]
359    ErrPayloadTooSmallForObuExtensionHeader,
360    /// Payload is too small for OBU payload size.
361    #[error("payload is too small for OBU payload size")]
362    ErrPayloadTooSmallForObuPayloadSize,
363
364    /// Extension_payload must be in 32-bit words.
365    #[error("extension_payload must be in 32-bit words")]
366    HeaderExtensionPayloadNot32BitWords,
367    /// Too many CSRCs for the 4-bit CC field.
368    #[error("too many CSRCs: {0} exceeds the 4-bit CC field maximum of 15")]
369    TooManyCSRCs(usize),
370    /// One-byte header extension payload length outside 1-16 bytes.
371    #[error(
372        "one-byte header extension payload length {0} is outside the RFC 8285 valid range of 1-16 bytes"
373    )]
374    OneByteHeaderExtensionPayloadOutOfRange(usize),
375    /// Two-byte header extension payload longer than 255 bytes.
376    #[error(
377        "two-byte header extension payload length {0} exceeds the RFC 8285 maximum of 255 bytes"
378    )]
379    TwoByteHeaderExtensionPayloadTooLarge(usize),
380    /// Total extension payload length exceeds u16::MAX.
381    #[error("total extension payload length {0} exceeds u16::MAX (65535 bytes)")]
382    ExtensionPayloadTotalOverflow(usize),
383    /// NALU length exceeds u16::MAX.
384    #[error("NALU length {0} exceeds u16::MAX (65535 bytes)")]
385    NaluTooLarge(usize),
386    /// Audio level overflow.
387    #[error("audio level overflow")]
388    AudioLevelOverflow,
389    /// Playout delay overflow.
390    #[error("playout delay overflow")]
391    PlayoutDelayOverflow,
392    /// Payload is not large enough.
393    #[error("payload is not large enough")]
394    PayloadIsNotLargeEnough,
395    /// STAP-A declared size is larger than buffer.
396    #[error("STAP-A declared size({0}) is larger than buffer({1})")]
397    StapASizeLargerThanBuffer(usize, usize),
398    /// NALU type is currently not handled.
399    #[error("nalu type {0} is currently not handled")]
400    NaluTypeIsNotHandled(u8),
401
402    //SRTP
403    /// Duplicated packet.
404    #[error("duplicated packet")]
405    ErrDuplicated,
406    /// SRTP master key is not long enough.
407    #[error("SRTP master key is not long enough")]
408    ErrShortSrtpMasterKey,
409    /// SRTP master salt is not long enough.
410    #[error("SRTP master salt is not long enough")]
411    ErrShortSrtpMasterSalt,
412    /// No such SRTP Profile.
413    #[error("no such SRTP Profile")]
414    ErrNoSuchSrtpProfile,
415    /// IndexOverKdr > 0 is not supported yet.
416    #[error("indexOverKdr > 0 is not supported yet")]
417    ErrNonZeroKdrNotSupported,
418    /// Exporter called with wrong label.
419    #[error("exporter called with wrong label")]
420    ErrExporterWrongLabel,
421    /// No config provided.
422    #[error("no config provided")]
423    ErrNoConfig,
424    /// No conn provided.
425    #[error("no conn provided")]
426    ErrNoConn,
427    /// Failed to verify auth tag.
428    #[error("failed to verify auth tag")]
429    ErrFailedToVerifyAuthTag,
430    /// Packet is too short to be RTP packet.
431    #[error("packet is too short to be RTP packet")]
432    ErrTooShortRtp,
433    /// Packet is too short to be RTCP packet.
434    #[error("packet is too short to be RTCP packet")]
435    ErrTooShortRtcp,
436    /// Payload differs.
437    #[error("payload differs")]
438    ErrPayloadDiffers,
439    /// Started channel used incorrectly, should only be closed.
440    #[error("started channel used incorrectly, should only be closed")]
441    ErrStartedChannelUsedIncorrectly,
442    /// Stream has not been inited, unable to close.
443    #[error("stream has not been inited, unable to close")]
444    ErrStreamNotInited,
445    /// Stream is already closed.
446    #[error("stream is already closed")]
447    ErrStreamAlreadyClosed,
448    /// Stream is already inited.
449    #[error("stream is already inited")]
450    ErrStreamAlreadyInited,
451    /// Failed to cast child.
452    #[error("failed to cast child")]
453    ErrFailedTypeAssertion,
454    /// Exceeded the maximum number of packets.
455    #[error("exceeded the maximum number of packets")]
456    ErrExceededMaxPackets,
457
458    /// Index_over_kdr > 0 is not supported yet.
459    #[error("index_over_kdr > 0 is not supported yet")]
460    UnsupportedIndexOverKdr,
461    /// Invalid master key length for AES_256_cm.
462    #[error("invalid master key length for aes_256_cm")]
463    InvalidMasterKeyLength,
464    /// Invalid master salt length for AES_256_cm.
465    #[error("invalid master salt length for aes_256_cm")]
466    InvalidMasterSaltLength,
467    /// Out_len > 32 is not supported for AES_256_cm.
468    #[error("out_len > 32 is not supported for aes_256_cm")]
469    UnsupportedOutLength,
470    /// SRTP Master Key must be len , got.
471    #[error("SRTP Master Key must be len {0}, got {1}")]
472    SrtpMasterKeyLength(usize, usize),
473    /// SRTP Salt must be len , got.
474    #[error("SRTP Salt must be len {0}, got {1}")]
475    SrtpSaltLength(usize, usize),
476    /// SyntaxError.
477    #[error("SyntaxError: {0}")]
478    ExtMapParse(String),
479    /// SSRC not exist in SRTP_SSRC_state.
480    #[error("ssrc {0} not exist in srtp_ssrc_state")]
481    SsrcMissingFromSrtp(u32),
482    /// SRTP SSRC= index=: duplicated.
483    #[error("srtp ssrc={0} index={1}: duplicated")]
484    SrtpSsrcDuplicated(u32, u16),
485    /// SRTP SSRC= seq=: this packet index was already used to encrypt (RFC 3711 Section 3.3.1).
486    #[error("srtp ssrc={0} seq={1}: packet index already used for encryption")]
487    SrtpIndexReused(u32, u16),
488    /// SRTP/SRTCP SSRC refused: the context already holds state for the maximum number of SSRCs.
489    #[error("srtp ssrc={0}: refused, the context already tracks {1} SSRCs")]
490    SrtpTooManySsrcs(u32, usize),
491    /// Srtcp SSRC= index=: duplicated.
492    #[error("srtcp ssrc={0} index={1}: duplicated")]
493    SrtcpSsrcDuplicated(u32, usize),
494    /// SSRC not exist in srtcp_SSRC_state.
495    #[error("ssrc {0} not exist in srtcp_ssrc_state")]
496    SsrcMissingFromSrtcp(u32),
497    /// Stream with SSRC exists.
498    #[error("Stream with ssrc {0} exists")]
499    StreamWithSsrcExists(u32),
500    /// Session RTP/RTCP type must be same as input buffer.
501    #[error("Session RTP/RTCP type must be same as input buffer")]
502    SessionRtpRtcpTypeMismatch,
503    /// Session EOF.
504    #[error("Session EOF")]
505    SessionEof,
506    /// Too short SRTP packet: only bytes, expected > bytes.
507    #[error("too short SRTP packet: only {0} bytes, expected > {1} bytes")]
508    SrtpTooSmall(usize, usize),
509    /// Too short SRTCP packet: only bytes, expected > bytes.
510    #[error("too short SRTCP packet: only {0} bytes, expected > {1} bytes")]
511    SrtcpTooSmall(usize, usize),
512    /// Failed to verify RTP auth tag.
513    #[error("failed to verify rtp auth tag")]
514    RtpFailedToVerifyAuthTag,
515    /// Too short auth tag: only bytes, expected > bytes.
516    #[error("too short auth tag: only {0} bytes, expected > {1} bytes")]
517    RtcpInvalidLengthAuthTag(usize, usize),
518    /// Failed to verify RTCP auth tag.
519    #[error("failed to verify rtcp auth tag")]
520    RtcpFailedToVerifyAuthTag,
521    /// SessionSRTP has been closed.
522    #[error("SessionSRTP has been closed")]
523    SessionSrtpAlreadyClosed,
524    /// This stream is not a RTPStream.
525    #[error("this stream is not a RTPStream")]
526    InvalidRtpStream,
527    /// This stream is not a RTCPStream.
528    #[error("this stream is not a RTCPStream")]
529    InvalidRtcpStream,
530
531    //STUN errors
532    /// Attribute not found.
533    #[error("attribute not found")]
534    ErrAttributeNotFound,
535    /// Transaction is stopped.
536    #[error("transaction is stopped")]
537    ErrTransactionStopped,
538    /// Transaction not exists.
539    #[error("transaction not exists")]
540    ErrTransactionNotExists,
541    /// Transaction exists with same id.
542    #[error("transaction exists with same id")]
543    ErrTransactionExists,
544    /// Agent is closed.
545    #[error("agent is closed")]
546    ErrAgentClosed,
547    /// Transaction is timed out.
548    #[error("transaction is timed out")]
549    ErrTransactionTimeOut,
550    /// No default reason for ErrorCode.
551    #[error("no default reason for ErrorCode")]
552    ErrNoDefaultReason,
553    /// Unexpected EOF.
554    #[error("unexpected EOF")]
555    ErrUnexpectedEof,
556    /// Attribute size is invalid.
557    #[error("attribute size is invalid")]
558    ErrAttributeSizeInvalid,
559    /// Attribute size overflow.
560    #[error("attribute size overflow")]
561    ErrAttributeSizeOverflow,
562    /// Attempt to decode to nil message.
563    #[error("attempt to decode to nil message")]
564    ErrDecodeToNil,
565    /// Unexpected EOF: not enough bytes to read header.
566    #[error("unexpected EOF: not enough bytes to read header")]
567    ErrUnexpectedHeaderEof,
568    /// Integrity check failed.
569    #[error("integrity check failed")]
570    ErrIntegrityMismatch,
571    /// Fingerprint check failed.
572    #[error("fingerprint check failed")]
573    ErrFingerprintMismatch,
574    /// FINGERPRINT before MESSAGE-INTEGRITY attribute.
575    #[error("FINGERPRINT before MESSAGE-INTEGRITY attribute")]
576    ErrFingerprintBeforeIntegrity,
577    /// Bad UNKNOWN-ATTRIBUTES size.
578    #[error("bad UNKNOWN-ATTRIBUTES size")]
579    ErrBadUnknownAttrsSize,
580    /// Invalid length of IP value.
581    #[error("invalid length of IP value")]
582    ErrBadIpLength,
583    /// No connection provided.
584    #[error("no connection provided")]
585    ErrNoConnection,
586    /// Client is closed.
587    #[error("client is closed")]
588    ErrClientClosed,
589    /// No agent is set.
590    #[error("no agent is set")]
591    ErrNoAgent,
592    /// Collector is closed.
593    #[error("collector is closed")]
594    ErrCollectorClosed,
595    /// Unsupported network.
596    #[error("unsupported network")]
597    ErrUnsupportedNetwork,
598    /// Invalid URL.
599    #[error("invalid url")]
600    ErrInvalidUrl,
601    /// Unknown scheme type.
602    #[error("unknown scheme type")]
603    ErrSchemeType,
604    /// Invalid hostname.
605    #[error("invalid hostname")]
606    ErrHost,
607
608    // TURN errors
609    /// TURN: RelayAddress must be valid IP to use RelayAddressGeneratorStatic.
610    #[error("turn: RelayAddress must be valid IP to use RelayAddressGeneratorStatic")]
611    ErrRelayAddressInvalid,
612    /// TURN: PacketConnConfigs and ConnConfigs are empty, unable to proceed.
613    #[error("turn: PacketConnConfigs and ConnConfigs are empty, unable to proceed")]
614    ErrNoAvailableConns,
615    /// TURN: PacketConnConfig must have a non-nil Conn.
616    #[error("turn: PacketConnConfig must have a non-nil Conn")]
617    ErrConnUnset,
618    /// TURN: ListenerConfig must have a non-nil Listener.
619    #[error("turn: ListenerConfig must have a non-nil Listener")]
620    ErrListenerUnset,
621    /// TURN: RelayAddressGenerator has invalid ListeningAddress.
622    #[error("turn: RelayAddressGenerator has invalid ListeningAddress")]
623    ErrListeningAddressInvalid,
624    /// TURN: RelayAddressGenerator in RelayConfig is unset.
625    #[error("turn: RelayAddressGenerator in RelayConfig is unset")]
626    ErrRelayAddressGeneratorUnset,
627    /// TURN: max retries exceeded.
628    #[error("turn: max retries exceeded")]
629    ErrMaxRetriesExceeded,
630    /// TURN: MaxPort must be not 0.
631    #[error("turn: MaxPort must be not 0")]
632    ErrMaxPortNotZero,
633    /// TURN: MaxPort must be not 0.
634    #[error("turn: MaxPort must be not 0")]
635    ErrMinPortNotZero,
636    /// TURN: MaxPort less than MinPort.
637    #[error("turn: MaxPort less than MinPort")]
638    ErrMaxPortLessThanMinPort,
639    /// TURN: relay_conn cannot not be nil.
640    #[error("turn: relay_conn cannot not be nil")]
641    ErrNilConn,
642    /// TURN: TODO.
643    #[error("turn: TODO")]
644    ErrTodo,
645    /// TURN: already listening.
646    #[error("turn: already listening")]
647    ErrAlreadyListening,
648    /// TURN: Server failed to close.
649    #[error("turn: Server failed to close")]
650    ErrFailedToClose,
651    /// TURN: failed to retransmit transaction.
652    #[error("turn: failed to retransmit transaction")]
653    ErrFailedToRetransmitTransaction,
654    /// All retransmissions failed.
655    #[error("all retransmissions failed")]
656    ErrAllRetransmissionsFailed,
657    /// No binding found for channel.
658    #[error("no binding found for channel")]
659    ErrChannelBindNotFound,
660    /// STUN server address is not set for the client.
661    #[error("STUN server address is not set for the client")]
662    ErrStunserverAddressNotSet,
663    /// Only one Allocate caller is allowed.
664    #[error("only one Allocate() caller is allowed")]
665    ErrOneAllocateOnly,
666    /// Already allocated.
667    #[error("already allocated")]
668    ErrAlreadyAllocated,
669    /// Non-STUN message from STUN server.
670    #[error("non-STUN message from STUN server")]
671    ErrNonStunmessage,
672    /// Failed to decode STUN message.
673    #[error("failed to decode STUN message")]
674    ErrFailedToDecodeStun,
675    /// Unexpected STUN request message.
676    #[error("unexpected STUN request message")]
677    ErrUnexpectedStunrequestMessage,
678    /// Channel number not in [0x4000, 0x7FFF].
679    #[error("channel number not in [0x4000, 0x7FFF]")]
680    ErrInvalidChannelNumber,
681    /// ChannelData length != len(Data).
682    #[error("channelData length != len(Data)")]
683    ErrBadChannelDataLength,
684    /// Invalid value for requested family attribute.
685    #[error("invalid value for requested family attribute")]
686    ErrInvalidRequestedFamilyValue,
687    /// Fake error.
688    #[error("fake error")]
689    ErrFakeErr,
690    /// Use of closed network connection.
691    #[error("use of closed network connection")]
692    ErrClosed,
693    /// Addr is not a net.UDPAddr.
694    #[error("addr is not a net.UDPAddr")]
695    ErrUdpaddrCast,
696    /// Try-lock is already locked.
697    #[error("try-lock is already locked")]
698    ErrDoubleLock,
699    /// Transaction closed.
700    #[error("transaction closed")]
701    ErrTransactionClosed,
702    /// Wait_for_result called on non-result transaction.
703    #[error("wait_for_result called on non-result transaction")]
704    ErrWaitForResultOnNonResultTransaction,
705    /// Failed to build refresh request.
706    #[error("failed to build refresh request")]
707    ErrFailedToBuildRefreshRequest,
708    /// Failed to refresh allocation.
709    #[error("failed to refresh allocation")]
710    ErrFailedToRefreshAllocation,
711    /// Failed to get lifetime from refresh response.
712    #[error("failed to get lifetime from refresh response")]
713    ErrFailedToGetLifetime,
714    /// Too short buffer.
715    #[error("too short buffer")]
716    ErrShortBuffer,
717    /// Unexpected response type.
718    #[error("unexpected response type")]
719    ErrUnexpectedResponse,
720    /// AllocatePacketConn must be set.
721    #[error("AllocatePacketConn must be set")]
722    ErrAllocatePacketConnMustBeSet,
723    /// AllocateConn must be set.
724    #[error("AllocateConn must be set")]
725    ErrAllocateConnMustBeSet,
726    /// LeveledLogger must be set.
727    #[error("LeveledLogger must be set")]
728    ErrLeveledLoggerMustBeSet,
729    /// You cannot use the same channel number with different peer.
730    #[error("you cannot use the same channel number with different peer")]
731    ErrSameChannelDifferentPeer,
732    /// Allocations must not be created with nil FivTuple.
733    #[error("allocations must not be created with nil FivTuple")]
734    ErrNilFiveTuple,
735    /// Allocations must not be created with nil FiveTuple.src_addr.
736    #[error("allocations must not be created with nil FiveTuple.src_addr")]
737    ErrNilFiveTupleSrcAddr,
738    /// Allocations must not be created with nil FiveTuple.dst_addr.
739    #[error("allocations must not be created with nil FiveTuple.dst_addr")]
740    ErrNilFiveTupleDstAddr,
741    /// Allocations must not be created with nil turnSocket.
742    #[error("allocations must not be created with nil turnSocket")]
743    ErrNilTurnSocket,
744    /// Allocations must not be created with a lifetime of 0.
745    #[error("allocations must not be created with a lifetime of 0")]
746    ErrLifetimeZero,
747    /// Allocation attempt created with duplicate FiveTuple.
748    #[error("allocation attempt created with duplicate FiveTuple")]
749    ErrDupeFiveTuple,
750    /// Failed to cast net.Addr to *net.UDPAddr.
751    #[error("failed to cast net.Addr to *net.UDPAddr")]
752    ErrFailedToCastUdpaddr,
753    /// Failed to generate nonce.
754    #[error("failed to generate nonce")]
755    ErrFailedToGenerateNonce,
756    /// Failed to send error message.
757    #[error("failed to send error message")]
758    ErrFailedToSendError,
759    /// Duplicated Nonce generated, discarding request.
760    #[error("duplicated Nonce generated, discarding request")]
761    ErrDuplicatedNonce,
762    /// No such user exists.
763    #[error("no such user exists")]
764    ErrNoSuchUser,
765    /// Unexpected class.
766    #[error("unexpected class")]
767    ErrUnexpectedClass,
768    /// Unexpected method.
769    #[error("unexpected method")]
770    ErrUnexpectedMethod,
771    /// Failed to handle.
772    #[error("failed to handle")]
773    ErrFailedToHandle,
774    /// Unhandled STUN packet.
775    #[error("unhandled STUN packet")]
776    ErrUnhandledStunpacket,
777    /// Unable to handle ChannelData.
778    #[error("unable to handle ChannelData")]
779    ErrUnableToHandleChannelData,
780    /// Failed to create STUN message from packet.
781    #[error("failed to create stun message from packet")]
782    ErrFailedToCreateStunpacket,
783    /// Failed to create channel data from packet.
784    #[error("failed to create channel data from packet")]
785    ErrFailedToCreateChannelData,
786    /// Relay already allocated for 5-TUPLE.
787    #[error("relay already allocated for 5-TUPLE")]
788    ErrRelayAlreadyAllocatedForFiveTuple,
789    /// RequestedTransport must be UDP.
790    #[error("RequestedTransport must be UDP")]
791    ErrRequestedTransportMustBeUdp,
792    /// No support for DONT-FRAGMENT.
793    #[error("no support for DONT-FRAGMENT")]
794    ErrNoDontFragmentSupport,
795    /// Request must not contain RESERVATION-TOKEN and EVEN-PORT.
796    #[error("Request must not contain RESERVATION-TOKEN and EVEN-PORT")]
797    ErrRequestWithReservationTokenAndEvenPort,
798    /// No allocation found.
799    #[error("no allocation found")]
800    ErrNoAllocationFound,
801    /// Unable to handle send-indication, no permission added.
802    #[error("unable to handle send-indication, no permission added")]
803    ErrNoPermission,
804    /// Packet write smaller than packet.
805    #[error("packet write smaller than packet")]
806    ErrShortWrite,
807    /// No such channel bind.
808    #[error("no such channel bind")]
809    ErrNoSuchChannelBind,
810    /// Failed writing to socket.
811    #[error("failed writing to socket")]
812    ErrFailedWriteSocket,
813
814    // ICE errors
815    /// Indicates an error with Unknown info.
816    #[error("Unknown type")]
817    ErrUnknownType,
818
819    /// Indicates query arguments are provided in a STUN URL.
820    #[error("queries not supported in stun address")]
821    ErrStunQuery,
822
823    /// Indicates an malformed query is provided.
824    #[error("invalid query")]
825    ErrInvalidQuery,
826
827    /// Indicates malformed port is provided.
828    #[error("url parse: invalid port number")]
829    ErrPort,
830
831    /// Indicates local username fragment insufficient bits are provided.
832    /// Have to be at least 24 bits long.
833    #[error("local username fragment is less than 24 bits long")]
834    ErrLocalUfragInsufficientBits,
835
836    /// Indicates local passoword insufficient bits are provided.
837    /// Have to be at least 128 bits long.
838    #[error("local password is less than 128 bits long")]
839    ErrLocalPwdInsufficientBits,
840
841    /// A local username fragment longer than 32 characters (RFC 8839 section 5.4: "MUST NOT
842    /// send") or with a character that is not an `ice-char` (letters, digits, `+`, `/`).
843    #[error("local username fragment is longer than 32 characters or not made of ice-chars")]
844    ErrLocalUfragInvalid,
845
846    /// A local password longer than 256 characters or with a character that is not an
847    /// `ice-char` (RFC 8839 section 5.4).
848    #[error("local password is longer than 256 characters or not made of ice-chars")]
849    ErrLocalPwdInvalid,
850
851    /// A local server-reflexive, peer-reflexive or relayed candidate without its related
852    /// address (RFC 8839 section 5.1: `raddr` and `rport` "MUST be present" for them).
853    #[error("a local srflx, prflx or relay candidate has no related address")]
854    ErrLocalCandidateWithoutRelatedAddress,
855
856    /// Indicates an unsupported transport type was provided.
857    #[error("invalid transport protocol type")]
858    ErrProtoType,
859
860    /// Indicates agent does not have a valid candidate pair.
861    #[error("no candidate pairs available")]
862    ErrNoCandidatePairs,
863
864    /// Indicates agent connection was canceled by the caller.
865    #[error("connecting canceled by caller")]
866    ErrCanceledByCaller,
867
868    /// Indicates agent was started twice.
869    #[error("attempted to start agent twice")]
870    ErrMultipleStart,
871
872    /// Indicates agent was started with an empty remote ufrag.
873    #[error("remote ufrag is empty")]
874    ErrRemoteUfragEmpty,
875
876    /// Indicates agent was started with an empty remote pwd.
877    #[error("remote pwd is empty")]
878    ErrRemotePwdEmpty,
879
880    /// Indicates agent was started without on_candidate.
881    #[error("no on_candidate provided")]
882    ErrNoOnCandidateHandler,
883
884    /// Indicates GatherCandidates has been called multiple times.
885    #[error("attempting to gather candidates during gathering state")]
886    ErrMultipleGatherAttempted,
887
888    /// Indicates agent was give TURN URL with an empty Username.
889    #[error("username is empty")]
890    ErrUsernameEmpty,
891
892    /// Indicates agent was give TURN URL with an empty Password.
893    #[error("password is empty")]
894    ErrPasswordEmpty,
895
896    /// Indicates we were unable to parse a candidate address.
897    #[error("failed to parse address")]
898    ErrAddressParseFailed,
899
900    /// Indicates that non host candidates were selected for a lite agent.
901    #[error("lite agents must only use host candidates")]
902    ErrLiteUsingNonHostCandidates,
903
904    /// Indicates that current ice agent supports Lite only
905    #[error("lite support only")]
906    ErrLiteSupportOnly,
907
908    /// Indicates that one or more URL was provided to the agent but no host candidate required them.
909    #[error("agent does not need URL with selected candidate types")]
910    ErrUselessUrlsProvided,
911
912    /// Indicates that the specified NAT1To1IPCandidateType is unsupported.
913    #[error("unsupported 1:1 NAT IP candidate type")]
914    ErrUnsupportedNat1to1IpCandidateType,
915
916    /// Indicates that the given 1:1 NAT IP mapping is invalid.
917    #[error("invalid 1:1 NAT IP mapping")]
918    ErrInvalidNat1to1IpMapping,
919
920    /// IPNotFound in NAT1To1IPMapping.
921    #[error("external mapped IP not found")]
922    ErrExternalMappedIpNotFound,
923
924    /// Indicates that the mDNS gathering cannot be used along with 1:1 NAT IP mapping for host
925    /// candidate.
926    #[error("mDNS gathering cannot be used with 1:1 NAT IP mapping for host candidate")]
927    ErrMulticastDnsWithNat1to1IpMapping,
928
929    /// Indicates that 1:1 NAT IP mapping for host candidate is requested, but the host candidate
930    /// type is disabled.
931    #[error("1:1 NAT IP mapping for host candidate ineffective")]
932    ErrIneffectiveNat1to1IpMappingHost,
933
934    /// Indicates that 1:1 NAT IP mapping for srflx candidate is requested, but the srflx candidate
935    /// type is disabled.
936    #[error("1:1 NAT IP mapping for srflx candidate ineffective")]
937    ErrIneffectiveNat1to1IpMappingSrflx,
938
939    /// Indicates an invalid MulticastDNSHostName.
940    #[error("invalid mDNS HostName, must end with .local and can only contain a single '.'")]
941    ErrInvalidMulticastDnshostName,
942
943    /// Indicates mdns is not supported.
944    #[error("mdns is not supported")]
945    ErrMulticastDnsNotSupported,
946
947    /// Indicates Restart was called when Agent is in GatheringStateGathering.
948    #[error("ICE Agent can not be restarted when gathering")]
949    ErrRestartWhenGathering,
950
951    /// Indicates a run operation was canceled by its individual done.
952    #[error("run was canceled by done")]
953    ErrRunCanceled,
954
955    /// Initialized Indicates TCPMux is not initialized and that invalidTCPMux is used.
956    #[error("TCPMux is not initialized")]
957    ErrTcpMuxNotInitialized,
958
959    /// Indicates we already have the connection with same remote addr.
960    #[error("conn with same remote addr already exists")]
961    ErrTcpRemoteAddrAlreadyExists,
962
963    /// Failed to send packet.
964    #[error("failed to send packet")]
965    ErrSendPacket,
966    /// Attribute not long enough to be ICE candidate.
967    #[error("attribute not long enough to be ICE candidate")]
968    ErrAttributeTooShortIceCandidate,
969    /// Could not parse component.
970    #[error("could not parse component")]
971    ErrParseComponent,
972    /// Could not parse priority.
973    #[error("could not parse priority")]
974    ErrParsePriority,
975    /// Could not parse port.
976    #[error("could not parse port")]
977    ErrParsePort,
978    /// Could not parse related addresses.
979    #[error("could not parse related addresses")]
980    ErrParseRelatedAddr,
981    /// Could not parse type.
982    #[error("could not parse type")]
983    ErrParseType,
984    /// Unknown candidate type.
985    #[error("unknown candidate type")]
986    ErrUnknownCandidateType,
987    /// Failed to get XOR-MAPPED-ADDRESS response.
988    #[error("failed to get XOR-MAPPED-ADDRESS response")]
989    ErrGetXorMappedAddrResponse,
990    /// Connection with same remote address already exists.
991    #[error("connection with same remote address already exists")]
992    ErrConnectionAddrAlreadyExist,
993    /// Error reading streaming packet.
994    #[error("error reading streaming packet")]
995    ErrReadingStreamingPacket,
996    /// Error writing to.
997    #[error("error writing to")]
998    ErrWriting,
999    /// Error closing connection.
1000    #[error("error closing connection")]
1001    ErrClosingConnection,
1002    /// Unable to determine networkType.
1003    #[error("unable to determine networkType")]
1004    ErrDetermineNetworkType,
1005    /// Missing protocol scheme.
1006    #[error("missing protocol scheme")]
1007    ErrMissingProtocolScheme,
1008    /// Too many colons in address.
1009    #[error("too many colons in address")]
1010    ErrTooManyColonsAddr,
1011    /// Unexpected error trying to read.
1012    #[error("unexpected error trying to read")]
1013    ErrRead,
1014    /// Unknown role.
1015    #[error("unknown role")]
1016    ErrUnknownRole,
1017    /// Username mismatch.
1018    #[error("username mismatch")]
1019    ErrMismatchUsername,
1020    /// The ICE conn can't write STUN messages.
1021    #[error("the ICE conn can't write STUN messages")]
1022    ErrIceWriteStunMessage,
1023    /// URL parse: relative URL without a base.
1024    #[error("url parse: relative URL without a base")]
1025    ErrUrlParse,
1026    /// Candidate IP could not be found.
1027    #[error("Candidate IP could not be found")]
1028    ErrCandidateIpNotFound,
1029
1030    // DTLS errors
1031    /// Conn is closed.
1032    #[error("conn is closed")]
1033    ErrConnClosed,
1034    /// Read/write timeout.
1035    #[error("read/write timeout")]
1036    ErrDeadlineExceeded,
1037    /// Context is not supported for export_keying_material.
1038    #[error("context is not supported for export_keying_material")]
1039    ErrContextUnsupported,
1040    /// Packet is too short.
1041    #[error("packet is too short")]
1042    ErrDtlspacketInvalidLength,
1043    /// Handshake is in progress.
1044    #[error("handshake is in progress")]
1045    ErrHandshakeInProgress,
1046    /// Invalid content type.
1047    #[error("invalid content type")]
1048    ErrInvalidContentType,
1049    /// Invalid mac.
1050    #[error("invalid mac")]
1051    ErrInvalidMac,
1052    /// Packet length and declared length do not match.
1053    #[error("packet length and declared length do not match")]
1054    ErrInvalidPacketLength,
1055    /// Export_keying_material can not be used with a reserved label.
1056    #[error("export_keying_material can not be used with a reserved label")]
1057    ErrReservedExportKeyingMaterial,
1058    /// Client sent certificate verify but we have no certificate to verify.
1059    #[error("client sent certificate verify but we have no certificate to verify")]
1060    ErrCertificateVerifyNoCertificate,
1061    /// Client+server do not support any shared cipher suites.
1062    #[error("client+server do not support any shared cipher suites")]
1063    ErrCipherSuiteNoIntersection,
1064    /// Server hello can not be created without a cipher suite.
1065    #[error("server hello can not be created without a cipher suite")]
1066    ErrCipherSuiteUnset,
1067    /// Client sent certificate but did not verify it.
1068    #[error("client sent certificate but did not verify it")]
1069    ErrClientCertificateNotVerified,
1070    /// Server required client verification, but got none.
1071    #[error("server required client verification, but got none")]
1072    ErrClientCertificateRequired,
1073    /// Server responded with SRTP Profile we do not support.
1074    #[error("server responded with SRTP Profile we do not support")]
1075    ErrClientNoMatchingSrtpProfile,
1076    /// Client required Extended Master Secret extension, but server does not support it.
1077    #[error("client required Extended Master Secret extension, but server does not support it")]
1078    ErrClientRequiredButNoServerEms,
1079    /// Server hello can not be created without a compression method.
1080    #[error("server hello can not be created without a compression method")]
1081    ErrCompressionMethodUnset,
1082    /// Client+server cookie does not match.
1083    #[error("client+server cookie does not match")]
1084    ErrCookieMismatch,
1085    /// Cookie must not be longer then 255 bytes.
1086    #[error("cookie must not be longer then 255 bytes")]
1087    ErrCookieTooLong,
1088    /// PSK Identity Hint provided but PSK is nil.
1089    #[error("PSK Identity Hint provided but PSK is nil")]
1090    ErrIdentityNoPsk,
1091    /// No certificate provided.
1092    #[error("no certificate provided")]
1093    ErrInvalidCertificate,
1094    /// Cipher spec invalid.
1095    #[error("cipher spec invalid")]
1096    ErrInvalidCipherSpec,
1097    /// Invalid or unknown cipher suite.
1098    #[error("invalid or unknown cipher suite")]
1099    ErrInvalidCipherSuite,
1100    /// Unable to determine if ClientKeyExchange is a public key or PSK Identity.
1101    #[error("unable to determine if ClientKeyExchange is a public key or PSK Identity")]
1102    ErrInvalidClientKeyExchange,
1103    /// Invalid or unknown compression method.
1104    #[error("invalid or unknown compression method")]
1105    ErrInvalidCompressionMethod,
1106    /// ECDSA signature contained zero or negative values.
1107    #[error("ECDSA signature contained zero or negative values")]
1108    ErrInvalidEcdsasignature,
1109    /// Invalid or unknown elliptic curve type.
1110    #[error("invalid or unknown elliptic curve type")]
1111    ErrInvalidEllipticCurveType,
1112    /// Invalid extension type.
1113    #[error("invalid extension type")]
1114    ErrInvalidExtensionType,
1115    /// Invalid hash algorithm.
1116    #[error("invalid hash algorithm")]
1117    ErrInvalidHashAlgorithm,
1118    /// Invalid named curve.
1119    #[error("invalid named curve")]
1120    ErrInvalidNamedCurve,
1121    /// Invalid private key type.
1122    #[error("invalid private key type")]
1123    ErrInvalidPrivateKey,
1124    /// Named curve and private key type does not match.
1125    #[error("named curve and private key type does not match")]
1126    ErrNamedCurveAndPrivateKeyMismatch,
1127    /// Invalid server name format.
1128    #[error("invalid server name format")]
1129    ErrInvalidSniFormat,
1130    /// Invalid signature algorithm.
1131    #[error("invalid signature algorithm")]
1132    ErrInvalidSignatureAlgorithm,
1133    /// Expected and actual key signature do not match.
1134    #[error("expected and actual key signature do not match")]
1135    ErrKeySignatureMismatch,
1136    /// Conn can not be created with a nil nextConn.
1137    #[error("Conn can not be created with a nil nextConn")]
1138    ErrNilNextConn,
1139    /// Connection can not be created, no CipherSuites satisfy this Config.
1140    #[error("connection can not be created, no CipherSuites satisfy this Config")]
1141    ErrNoAvailableCipherSuites,
1142    /// Connection can not be created, no SignatureScheme satisfy this Config.
1143    #[error("connection can not be created, no SignatureScheme satisfy this Config")]
1144    ErrNoAvailableSignatureSchemes,
1145    /// No certificates configured.
1146    #[error("no certificates configured")]
1147    ErrNoCertificates,
1148    /// No config provided.
1149    #[error("no config provided")]
1150    ErrNoConfigProvided,
1151    /// Client requested zero or more elliptic curves that are not supported by the server.
1152    #[error("client requested zero or more elliptic curves that are not supported by the server")]
1153    ErrNoSupportedEllipticCurves,
1154    /// Unsupported protocol version.
1155    #[error("unsupported protocol version")]
1156    ErrUnsupportedProtocolVersion,
1157    /// Certificate and PSK provided.
1158    #[error("Certificate and PSK provided")]
1159    ErrPskAndCertificate,
1160    /// PSK and PSK Identity Hint must both be set for client.
1161    #[error("PSK and PSK Identity Hint must both be set for client")]
1162    ErrPskAndIdentityMustBeSetForClient,
1163    /// SRTP support was requested but server did not respond with use_SRTP extension.
1164    #[error("SRTP support was requested but server did not respond with use_srtp extension")]
1165    ErrRequestedButNoSrtpExtension,
1166    /// Certificate is mandatory for server.
1167    #[error("Certificate is mandatory for server")]
1168    ErrServerMustHaveCertificate,
1169    /// Client requested SRTP but we have no matching profiles.
1170    #[error("client requested SRTP but we have no matching profiles")]
1171    ErrServerNoMatchingSrtpProfile,
1172    /// Server requires the Extended Master Secret extension, but the client does not support it.
1173    #[error(
1174        "server requires the Extended Master Secret extension, but the client does not support it"
1175    )]
1176    ErrServerRequiredButNoClientEms,
1177    /// Expected and actual verify data does not match.
1178    #[error("expected and actual verify data does not match")]
1179    ErrVerifyDataMismatch,
1180    /// Handshake message unset, unable to marshal.
1181    #[error("handshake message unset, unable to marshal")]
1182    ErrHandshakeMessageUnset,
1183    /// Invalid flight number.
1184    #[error("invalid flight number")]
1185    ErrInvalidFlight,
1186    /// Unable to generate key signature, unimplemented.
1187    #[error("unable to generate key signature, unimplemented")]
1188    ErrKeySignatureGenerateUnimplemented,
1189    /// Unable to verify key signature, unimplemented.
1190    #[error("unable to verify key signature, unimplemented")]
1191    ErrKeySignatureVerifyUnimplemented,
1192    /// Data length and declared length do not match.
1193    #[error("data length and declared length do not match")]
1194    ErrLengthMismatch,
1195    /// Buffer not long enough to contain nonce.
1196    #[error("buffer not long enough to contain nonce")]
1197    ErrNotEnoughRoomForNonce,
1198    /// Feature has not been implemented yet.
1199    #[error("feature has not been implemented yet")]
1200    ErrNotImplemented,
1201    /// Sequence number overflow.
1202    #[error("sequence number overflow")]
1203    ErrSequenceNumberOverflow,
1204    /// Unable to marshal fragmented handshakes.
1205    #[error("unable to marshal fragmented handshakes")]
1206    ErrUnableToMarshalFragmented,
1207    /// Invalid state machine transition.
1208    #[error("invalid state machine transition")]
1209    ErrInvalidFsmTransition,
1210    /// ApplicationData with epoch of 0.
1211    #[error("ApplicationData with epoch of 0")]
1212    ErrApplicationDataEpochZero,
1213    /// Unhandled contentType.
1214    #[error("unhandled contentType")]
1215    ErrUnhandledContextType,
1216    /// Context canceled.
1217    #[error("context canceled")]
1218    ErrContextCanceled,
1219    /// Empty fragment.
1220    #[error("empty fragment")]
1221    ErrEmptyFragment,
1222    /// Alert is Fatal or Close Notify.
1223    #[error("Alert is Fatal or Close Notify")]
1224    ErrAlertFatalOrClose,
1225    /// A hello's renegotiation_info was not empty in an initial handshake (RFC 5746 3.4, 3.6).
1226    #[error("renegotiation_info is not empty in an initial handshake")]
1227    ErrRenegotiationInfoNotEmpty,
1228    /// The ServerHello carried an extension the ClientHello did not offer (RFC 5246 7.4.1.4).
1229    #[error("server sent an extension the client did not offer")]
1230    ErrUnsolicitedExtension,
1231    /// The ServerHello selected a compression method the ClientHello did not offer.
1232    #[error("server selected a compression method the client did not offer")]
1233    ErrCompressionMethodNotOffered,
1234    /// The ClientHello did not offer the null compression method (RFC 5246 7.4.1.2).
1235    #[error("client did not offer the null compression method")]
1236    ErrNoNullCompressionMethod,
1237    /// The server's use_srtp held an MKI the client did not offer, or not exactly one profile
1238    /// (RFC 5764 4.1.1, 4.1.3).
1239    #[error("server's use_srtp extension is not a valid answer to the client's")]
1240    ErrInvalidUseSrtpAnswer,
1241    /// Key material was asked of a session without the extended master secret (RFC 7627 5.4).
1242    #[error("no keying material is exported without the extended master secret")]
1243    ErrExportWithoutExtendedMasterSecret,
1244    /// The handshake did not complete within the configured time.
1245    #[error("handshake did not complete in time")]
1246    ErrHandshakeTimeout,
1247    /// A record's payload is longer than the 2^14 bytes a record may carry (RFC 5246 6.2.1).
1248    #[error("record payload exceeds 2^14 bytes")]
1249    ErrRecordOverflow,
1250    /// A hello carried two extensions of one type (RFC 5246 7.4.1.4).
1251    #[error("hello carries an extension type twice")]
1252    ErrDuplicateExtension,
1253    /// Fragment buffer overflow. New size is greater than specified max.
1254    #[error(
1255        "Fragment buffer overflow. New size {new_size} is greater than specified max {max_size}"
1256    )]
1257    ErrFragmentBufferOverflow {
1258        /// The size the buffer would have grown to.
1259        new_size: usize,
1260        /// The configured maximum.
1261        max_size: usize,
1262    },
1263    /// Client transport is not set yet.
1264    #[error("Client transport is not set yet")]
1265    ErrClientTransportNotSet,
1266
1267    /// The endpoint can no longer create new connections
1268    ///
1269    /// Indicates that a necessary component of the endpoint has been dropped or otherwise disabled.
1270    #[error("endpoint stopping")]
1271    EndpointStopping,
1272    /// The number of active connections on the local endpoint is at the limit
1273    ///
1274    /// Try using longer connection IDs.
1275    #[error("too many connections")]
1276    TooManyConnections,
1277    /// The domain name supplied was malformed
1278    #[error("invalid DNS name: {0}")]
1279    InvalidDnsName(String),
1280    /// The remote [`SocketAddr`] supplied was malformed
1281    ///
1282    /// Examples include attempting to connect to port 0, or using an inappropriate address family.
1283    #[error("invalid remote address: {0}")]
1284    InvalidRemoteAddress(SocketAddr),
1285    /// No client configuration was set up
1286    #[error("no client config")]
1287    NoClientConfig,
1288    /// No server configuration was set up
1289    #[error("no server config")]
1290    NoServerConfig,
1291
1292    //SCTP errors
1293    /// Raw is too small for a SCTP chunk.
1294    #[error("raw is too small for a SCTP chunk")]
1295    ErrChunkHeaderTooSmall,
1296    /// Not enough data left in SCTP packet to satisfy requested length.
1297    #[error("not enough data left in SCTP packet to satisfy requested length")]
1298    ErrChunkHeaderNotEnoughSpace,
1299    /// Chunk PADDING is non-zero at offset.
1300    #[error("chunk PADDING is non-zero at offset")]
1301    ErrChunkHeaderPaddingNonZero,
1302    /// Chunk has invalid length.
1303    #[error("chunk has invalid length")]
1304    ErrChunkHeaderInvalidLength,
1305
1306    /// ChunkType is not of type ABORT.
1307    #[error("ChunkType is not of type ABORT")]
1308    ErrChunkTypeNotAbort,
1309    /// Failed build Abort Chunk.
1310    #[error("failed build Abort Chunk")]
1311    ErrBuildAbortChunkFailed,
1312    /// ChunkType is not of type COOKIEACK.
1313    #[error("ChunkType is not of type COOKIEACK")]
1314    ErrChunkTypeNotCookieAck,
1315    /// ChunkType is not of type COOKIEECHO.
1316    #[error("ChunkType is not of type COOKIEECHO")]
1317    ErrChunkTypeNotCookieEcho,
1318    /// ChunkType is not of type ctError.
1319    #[error("ChunkType is not of type ctError")]
1320    ErrChunkTypeNotCt,
1321    /// Failed build Error Chunk.
1322    #[error("failed build Error Chunk")]
1323    ErrBuildErrorChunkFailed,
1324    /// Failed to marshal stream.
1325    #[error("failed to marshal stream")]
1326    ErrMarshalStreamFailed,
1327    /// Chunk too short.
1328    #[error("chunk too short")]
1329    ErrChunkTooShort,
1330    /// ChunkType is not of type ForwardTsn.
1331    #[error("ChunkType is not of type ForwardTsn")]
1332    ErrChunkTypeNotForwardTsn,
1333    /// ChunkType is not of type HEARTBEAT.
1334    #[error("ChunkType is not of type HEARTBEAT")]
1335    ErrChunkTypeNotHeartbeat,
1336    /// ChunkType is not of type HEARTBEATACK.
1337    #[error("ChunkType is not of type HEARTBEATACK")]
1338    ErrChunkTypeNotHeartbeatAck,
1339    /// Heartbeat is not long enough to contain Heartbeat Info.
1340    #[error("heartbeat is not long enough to contain Heartbeat Info")]
1341    ErrHeartbeatNotLongEnoughInfo,
1342    /// Failed to parse param type.
1343    #[error("failed to parse param type")]
1344    ErrParseParamTypeFailed,
1345    /// Heartbeat should only have HEARTBEAT param.
1346    #[error("heartbeat should only have HEARTBEAT param")]
1347    ErrHeartbeatParam,
1348    /// Failed unmarshalling param in Heartbeat Chunk.
1349    #[error("failed unmarshalling param in Heartbeat Chunk")]
1350    ErrHeartbeatChunkUnmarshal,
1351    /// Unimplemented.
1352    #[error("unimplemented")]
1353    ErrUnimplemented,
1354    /// Heartbeat Ack must have one param.
1355    #[error("heartbeat Ack must have one param")]
1356    ErrHeartbeatAckParams,
1357    /// Heartbeat Ack must have one param, and it should be a HeartbeatInfo.
1358    #[error("heartbeat Ack must have one param, and it should be a HeartbeatInfo")]
1359    ErrHeartbeatAckNotHeartbeatInfo,
1360    /// Unable to marshal parameter for Heartbeat Ack.
1361    #[error("unable to marshal parameter for Heartbeat Ack")]
1362    ErrHeartbeatAckMarshalParam,
1363
1364    /// Raw is too small for error cause.
1365    #[error("raw is too small for error cause")]
1366    ErrErrorCauseTooSmall,
1367
1368    /// Unhandled ParamType.
1369    #[error("unhandled ParamType: {typ}")]
1370    ErrParamTypeUnhandled {
1371        /// The raw parameter type that was not recognised.
1372        typ: u16,
1373    },
1374
1375    /// Unexpected ParamType.
1376    #[error("unexpected ParamType")]
1377    ErrParamTypeUnexpected,
1378
1379    /// Param header too short.
1380    #[error("param header too short")]
1381    ErrParamHeaderTooShort,
1382    /// Param self reported length is shorter than header length.
1383    #[error("param self reported length is shorter than header length")]
1384    ErrParamHeaderSelfReportedLengthShorter,
1385    /// Param self reported length is longer than header length.
1386    #[error("param self reported length is longer than header length")]
1387    ErrParamHeaderSelfReportedLengthLonger,
1388    /// Failed to parse param type.
1389    #[error("failed to parse param type")]
1390    ErrParamHeaderParseFailed,
1391
1392    /// Packet to short.
1393    #[error("packet to short")]
1394    ErrParamPacketTooShort,
1395    /// Outgoing SSN reset request parameter too short.
1396    #[error("outgoing SSN reset request parameter too short")]
1397    ErrSsnResetRequestParamTooShort,
1398    /// Failed unmarshalling SSN reset request parameter in RE-CONFIG chunk.
1399    #[error("failed unmarshalling SSN reset request parameter in RE-CONFIG chunk")]
1400    ErrUnmarshalSsnResetRequestParam,
1401    /// Reconfig response parameter too short.
1402    #[error("reconfig response parameter too short")]
1403    ErrReconfigRespParamTooShort,
1404    /// Failed unmarshalling re-configuration response parameter in RE-CONFIG chunk.
1405    #[error("failed unmarshalling re-configuration response parameter in RE-CONFIG chunk")]
1406    ErrUnmarshalReconfigRespParam,
1407    /// Invalid algorithm type.
1408    #[error("invalid algorithm type")]
1409    ErrInvalidAlgorithmType,
1410
1411    /// Failed to parse param type.
1412    #[error("failed to parse param type")]
1413    ErrInitChunkParseParamTypeFailed,
1414    /// Failed unmarshalling param in Init Chunk.
1415    #[error("failed unmarshalling param in Init Chunk")]
1416    ErrInitChunkUnmarshalParam,
1417    /// Unable to marshal parameter for INIT/INITACK.
1418    #[error("unable to marshal parameter for INIT/INITACK")]
1419    ErrInitAckMarshalParam,
1420
1421    /// ChunkType is not of type INIT.
1422    #[error("ChunkType is not of type INIT")]
1423    ErrChunkTypeNotTypeInit,
1424    /// Chunk Value isn't long enough for mandatory parameters exp.
1425    #[error("chunk Value isn't long enough for mandatory parameters exp")]
1426    ErrChunkValueNotLongEnough,
1427    /// ChunkType of type INIT flags must be all 0.
1428    #[error("ChunkType of type INIT flags must be all 0")]
1429    ErrChunkTypeInitFlagZero,
1430    /// Failed to unmarshal INIT body.
1431    #[error("failed to unmarshal INIT body")]
1432    ErrChunkTypeInitUnmarshalFailed,
1433    /// Failed marshaling INIT common data.
1434    #[error("failed marshaling INIT common data")]
1435    ErrChunkTypeInitMarshalFailed,
1436    /// ChunkType of type INIT ACK InitiateTag must not be 0.
1437    #[error("ChunkType of type INIT ACK InitiateTag must not be 0")]
1438    ErrChunkTypeInitInitiateTagZero,
1439    /// INIT ACK inbound stream request must be > 0.
1440    #[error("INIT ACK inbound stream request must be > 0")]
1441    ErrInitInboundStreamRequestZero,
1442    /// INIT ACK outbound stream request must be > 0.
1443    #[error("INIT ACK outbound stream request must be > 0")]
1444    ErrInitOutboundStreamRequestZero,
1445    /// INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500.
1446    #[error("INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500")]
1447    ErrInitAdvertisedReceiver1500,
1448
1449    /// Packet is smaller than the header size.
1450    #[error("packet is smaller than the header size")]
1451    ErrChunkPayloadSmall,
1452    /// ChunkType is not of type PayloadData.
1453    #[error("ChunkType is not of type PayloadData")]
1454    ErrChunkTypeNotPayloadData,
1455    /// Failed unmarshalling payload data chunk.
1456    #[error("failed unmarshalling payload data chunk")]
1457    ErrChunkUnmarshalPayloadData,
1458    /// ChunkType is not of type Reconfig.
1459    #[error("ChunkType is not of type Reconfig")]
1460    ErrChunkTypeNotReconfig,
1461    /// ChunkReconfig has invalid ParamA.
1462    #[error("ChunkReconfig has invalid ParamA")]
1463    ErrChunkReconfigInvalidParamA,
1464
1465    /// Failed to parse param type.
1466    #[error("failed to parse param type")]
1467    ErrChunkParseParamTypeFailed,
1468    /// Unable to marshal parameter A for reconfig.
1469    #[error("unable to marshal parameter A for reconfig")]
1470    ErrChunkMarshalParamAReconfigFailed,
1471    /// Unable to marshal parameter B for reconfig.
1472    #[error("unable to marshal parameter B for reconfig")]
1473    ErrChunkMarshalParamBReconfigFailed,
1474
1475    /// ChunkType is not of type SACK.
1476    #[error("ChunkType is not of type SACK")]
1477    ErrChunkTypeNotSack,
1478    /// SACK Chunk size is not large enough to contain header.
1479    #[error("SACK Chunk size is not large enough to contain header")]
1480    ErrSackSizeNotLargeEnoughInfo,
1481    /// Failed unmarshalling SACK chunk.
1482    #[error("failed unmarshalling SACK chunk")]
1483    ErrChunkUnmarshalSack,
1484
1485    /// Invalid chunk size.
1486    #[error("invalid chunk size")]
1487    ErrInvalidChunkSize,
1488    /// ChunkType is not of type SHUTDOWN.
1489    #[error("ChunkType is not of type SHUTDOWN")]
1490    ErrChunkTypeNotShutdown,
1491    /// Failed unmarshalling shutdown chunk.
1492    #[error("failed unmarshalling shutdown chunk")]
1493    ErrChunkUnmarshalShutdown,
1494
1495    /// ChunkType is not of type SHUTDOWN-ACK.
1496    #[error("ChunkType is not of type SHUTDOWN-ACK")]
1497    ErrChunkTypeNotShutdownAck,
1498    /// ChunkType is not of type SHUTDOWN-COMPLETE.
1499    #[error("ChunkType is not of type SHUTDOWN-COMPLETE")]
1500    ErrChunkTypeNotShutdownComplete,
1501
1502    /// Raw is smaller than the minimum length for a SCTP packet.
1503    #[error("raw is smaller than the minimum length for a SCTP packet")]
1504    ErrPacketRawTooSmall,
1505    /// Unable to parse SCTP chunk, not enough data for complete header.
1506    #[error("unable to parse SCTP chunk, not enough data for complete header")]
1507    ErrParseSctpChunkNotEnoughData,
1508    /// Failed to unmarshal, contains unknown chunk type.
1509    #[error("failed to unmarshal, contains unknown chunk type")]
1510    ErrUnmarshalUnknownChunkType,
1511    /// Checksum mismatch theirs.
1512    #[error("checksum mismatch theirs")]
1513    ErrChecksumMismatch,
1514
1515    /// Unexpected chunk popped (unordered).
1516    #[error("unexpected chunk popped (unordered)")]
1517    ErrUnexpectedChuckPoppedUnordered,
1518    /// Unexpected chunk popped (ordered).
1519    #[error("unexpected chunk popped (ordered)")]
1520    ErrUnexpectedChuckPoppedOrdered,
1521    /// Unexpected q state (should've been selected).
1522    #[error("unexpected q state (should've been selected)")]
1523    ErrUnexpectedQState,
1524    /// Try again.
1525    #[error("try again")]
1526    ErrTryAgain,
1527
1528    /// Abort chunk, with following errors.
1529    #[error("abort chunk, with following errors: {0}")]
1530    ErrAbortChunk(String),
1531    /// Shutdown called in non-Established state.
1532    #[error("shutdown called in non-Established state")]
1533    ErrShutdownNonEstablished,
1534    /// Association closed before connecting.
1535    #[error("association closed before connecting")]
1536    ErrAssociationClosedBeforeConn,
1537    /// Association init failed.
1538    #[error("association init failed")]
1539    ErrAssociationInitFailed,
1540    /// Association handshake closed.
1541    #[error("association handshake closed")]
1542    ErrAssociationHandshakeClosed,
1543    /// Silently discard.
1544    #[error("silently discard")]
1545    ErrSilentlyDiscard,
1546    /// The init not stored to send.
1547    #[error("the init not stored to send")]
1548    ErrInitNotStoredToSend,
1549    /// CookieEcho not stored to send.
1550    #[error("cookieEcho not stored to send")]
1551    ErrCookieEchoNotStoredToSend,
1552    /// SCTP packet must not have a source port of 0.
1553    #[error("sctp packet must not have a source port of 0")]
1554    ErrSctpPacketSourcePortZero,
1555    /// SCTP packet must not have a destination port of 0.
1556    #[error("sctp packet must not have a destination port of 0")]
1557    ErrSctpPacketDestinationPortZero,
1558    /// Init chunk must not be bundled with any other chunk.
1559    #[error("init chunk must not be bundled with any other chunk")]
1560    ErrInitChunkBundled,
1561    /// Init chunk expects a verification tag of 0 on the packet when out-of-the-blue.
1562    #[error("init chunk expects a verification tag of 0 on the packet when out-of-the-blue")]
1563    ErrInitChunkVerifyTagNotZero,
1564    /// Todo: handle Init when in state.
1565    #[error("todo: handle Init when in state")]
1566    ErrHandleInitState,
1567    /// No cookie in InitAck.
1568    #[error("no cookie in InitAck")]
1569    ErrInitAckNoCookie,
1570    /// There already exists a stream with identifier.
1571    #[error("there already exists a stream with identifier")]
1572    ErrStreamAlreadyExist,
1573    /// Failed to create a stream with identifier.
1574    #[error("Failed to create a stream with identifier")]
1575    ErrStreamCreateFailed,
1576    /// Unable to be popped from inflight queue TSN.
1577    #[error("unable to be popped from inflight queue TSN")]
1578    ErrInflightQueueTsnPop,
1579    /// Requested non-existent TSN.
1580    #[error("requested non-existent TSN")]
1581    ErrTsnRequestNotExist,
1582    /// Sending reset packet in non-Established state.
1583    #[error("sending reset packet in non-Established state")]
1584    ErrResetPacketInStateNotExist,
1585    /// Unexpected parameter type.
1586    #[error("unexpected parameter type")]
1587    ErrParameterType,
1588    /// Sending payload data in non-Established state.
1589    #[error("sending payload data in non-Established state")]
1590    ErrPayloadDataStateNotExist,
1591    /// Unhandled chunk type.
1592    #[error("unhandled chunk type")]
1593    ErrChunkTypeUnhandled,
1594    /// Handshake failed (INIT ACK).
1595    #[error("handshake failed (INIT ACK)")]
1596    ErrHandshakeInitAck,
1597    /// Handshake failed (COOKIE ECHO).
1598    #[error("handshake failed (COOKIE ECHO)")]
1599    ErrHandshakeCookieEcho,
1600
1601    /// Outbound packet larger than maximum message size.
1602    #[error("outbound packet larger than maximum message size")]
1603    ErrOutboundPacketTooLarge,
1604    /// A data channel message over the 16 KB a sender keeps to on an SCTP association without
1605    /// user message interleaving (RFC 8831 section 6.6), which is every association with a
1606    /// peer that does not announce I-DATA (RFC 8260), current browsers among them.
1607    #[error(
1608        "a {size} byte message is over the {limit} byte limit of an SCTP association without \
1609         message interleaving (RFC 8831 section 6.6: the peer did not announce I-DATA); \
1610         SettingEngineBuilder::with_sctp_message_size_limit_without_interleaving(false) lifts it \
1611         up to the peer's max-message-size"
1612    )]
1613    ErrMessageTooLargeWithoutInterleaving {
1614        /// The size of the message refused.
1615        size: usize,
1616        /// The limit, `maxMessageSize` (16384).
1617        limit: u32,
1618    },
1619    /// Stream closed.
1620    #[error("Stream closed")]
1621    ErrStreamClosed,
1622    /// Stream not existed.
1623    #[error("Stream not existed")]
1624    ErrStreamNotExisted,
1625    /// Association not existed.
1626    #[error("Association not existed")]
1627    ErrAssociationNotExisted,
1628    /// Transport not existed.
1629    #[error("Transport not existed")]
1630    ErrTransportNoExisted,
1631    /// Io EOF.
1632    #[error("Io EOF")]
1633    ErrEof,
1634    /// Invalid SystemTime.
1635    #[error("Invalid SystemTime")]
1636    ErrInvalidSystemTime,
1637    /// Net Conn read error.
1638    #[error("Net Conn read error")]
1639    ErrNetConnRead,
1640    /// Max Data Channel ID.
1641    #[error("Max Data Channel ID")]
1642    ErrMaxDataChannelID,
1643
1644    //Data Channel
1645    /// DataChannel message is not long enough to determine type: (expected: , actual: ).
1646    #[error(
1647        "DataChannel message is not long enough to determine type: (expected: {expected}, actual: {actual})"
1648    )]
1649    UnexpectedEndOfBuffer {
1650        /// The number of bytes the parser required.
1651        expected: usize,
1652        /// The number of bytes actually available.
1653        actual: usize,
1654    },
1655    /// Unknown MessageType.
1656    #[error("Unknown MessageType {0}")]
1657    InvalidMessageType(u8),
1658    /// Unknown ChannelType.
1659    #[error("Unknown ChannelType {0}")]
1660    InvalidChannelType(u8),
1661    /// Unknown PayloadProtocolIdentifier.
1662    #[error("Unknown PayloadProtocolIdentifier {0}")]
1663    InvalidPayloadProtocolIdentifier(u8),
1664    /// Unknow Protocol.
1665    #[error("Unknow Protocol")]
1666    UnknownProtocol,
1667
1668    //Media
1669    /// Stream is nil.
1670    #[error("stream is nil")]
1671    ErrNilStream,
1672    /// Incomplete frame header.
1673    #[error("incomplete frame header")]
1674    ErrIncompleteFrameHeader,
1675    /// Incomplete frame data.
1676    #[error("incomplete frame data")]
1677    ErrIncompleteFrameData,
1678    /// Incomplete file header.
1679    #[error("incomplete file header")]
1680    ErrIncompleteFileHeader,
1681    /// IVF signature mismatch.
1682    #[error("IVF signature mismatch")]
1683    ErrSignatureMismatch,
1684    /// IVF version unknown, parser may not parse correctly.
1685    #[error("IVF version unknown, parser may not parse correctly")]
1686    ErrUnknownIVFVersion,
1687
1688    /// File not opened.
1689    #[error("file not opened")]
1690    ErrFileNotOpened,
1691    /// Invalid nil packet.
1692    #[error("invalid nil packet")]
1693    ErrInvalidNilPacket,
1694
1695    /// Bad header signature.
1696    #[error("bad header signature")]
1697    ErrBadIDPageSignature,
1698    /// Wrong header, expected beginning of stream.
1699    #[error("wrong header, expected beginning of stream")]
1700    ErrBadIDPageType,
1701    /// Payload for id page must be 19 bytes.
1702    #[error("payload for id page must be 19 bytes")]
1703    ErrBadIDPageLength,
1704    /// Bad payload signature.
1705    #[error("bad payload signature")]
1706    ErrBadIDPagePayloadSignature,
1707    /// Not enough data for payload header.
1708    #[error("not enough data for payload header")]
1709    ErrShortPageHeader,
1710    /// Bad OpusTags signature.
1711    #[error("bad OpusTags signature")]
1712    ErrBadOpusTagsSignature,
1713    /// Unsupported channel mapping family.
1714    #[error("unsupported channel mapping family")]
1715    ErrUnsupportedChannelMappingFamily,
1716
1717    /// Data is not a H264 bitstream.
1718    #[error("data is not a H264 bitstream")]
1719    ErrDataIsNotH264Stream,
1720    /// Data is not a H265 bitstream.
1721    #[error("data is not a H265 bitstream")]
1722    ErrDataIsNotH265Stream,
1723    /// Io EOF.
1724    #[error("Io EOF")]
1725    ErrIoEOF,
1726
1727    // mDNS
1728    /// MDNS: port not support, only 5353 is supported.
1729    #[error("mDNS: port not support, only 5353 is supported")]
1730    ErrMDNSPortNotSupported,
1731    /// MDNS: connection is closed.
1732    #[error("mDNS: connection is closed")]
1733    ErrMDNSConnectionClosed,
1734    /// MDNS: query not found.
1735    #[error("mDNS: query not found")]
1736    ErrMDNSQueryNotFound,
1737    /// MDNS: parsing/packing of this type isn't available yet.
1738    #[error("mDNS: parsing/packing of this type isn't available yet")]
1739    ErrNotStarted,
1740    /// MDNS: parsing/packing of this section has completed.
1741    #[error("mDNS: parsing/packing of this section has completed")]
1742    ErrSectionDone,
1743    /// MDNS: parsing/packing of this section is header.
1744    #[error("mDNS: parsing/packing of this section is header")]
1745    ErrSectionHeader,
1746    /// MDNS: insufficient data for base length type.
1747    #[error("mDNS: insufficient data for base length type")]
1748    ErrBaseLen,
1749    /// MDNS: insufficient data for calculated length type.
1750    #[error("mDNS: insufficient data for calculated length type")]
1751    ErrCalcLen,
1752    /// MDNS: segment prefix is reserved.
1753    #[error("mDNS: segment prefix is reserved")]
1754    ErrReserved,
1755    /// MDNS: too many pointers (>10).
1756    #[error("mDNS: too many pointers (>10)")]
1757    ErrTooManyPtr,
1758    /// MDNS: invalid pointer.
1759    #[error("mDNS: invalid pointer")]
1760    ErrInvalidPtr,
1761    /// MDNS: nil resource body.
1762    #[error("mDNS: nil resource body")]
1763    ErrNilResourceBody,
1764    /// MDNS: insufficient data for resource body length.
1765    #[error("mDNS: insufficient data for resource body length")]
1766    ErrResourceLen,
1767    /// MDNS: segment length too long.
1768    #[error("mDNS: segment length too long")]
1769    ErrSegTooLong,
1770    /// MDNS: zero length segment.
1771    #[error("mDNS: zero length segment")]
1772    ErrZeroSegLen,
1773    /// MDNS: resource length too long.
1774    #[error("mDNS: resource length too long")]
1775    ErrResTooLong,
1776    /// MDNS: too many Questions to pack (>65535).
1777    #[error("mDNS: too many Questions to pack (>65535)")]
1778    ErrTooManyQuestions,
1779    /// MDNS: too many Answers to pack (>65535).
1780    #[error("mDNS: too many Answers to pack (>65535)")]
1781    ErrTooManyAnswers,
1782    /// MDNS: too many Authorities to pack (>65535).
1783    #[error("mDNS: too many Authorities to pack (>65535)")]
1784    ErrTooManyAuthorities,
1785    /// MDNS: too many Additionals to pack (>65535).
1786    #[error("mDNS: too many Additionals to pack (>65535)")]
1787    ErrTooManyAdditionals,
1788    /// MDNS: name is not in canonical format (it must end with a .).
1789    #[error("mDNS: name is not in canonical format (it must end with a .)")]
1790    ErrNonCanonicalName,
1791    /// MDNS: character string exceeds maximum length (255).
1792    #[error("mDNS: character string exceeds maximum length (255)")]
1793    ErrStringTooLong,
1794    /// MDNS: compressed name in SRV resource data.
1795    #[error("mDNS: compressed name in SRV resource data")]
1796    ErrCompressedSrv,
1797    /// MDNS: empty builder msg.
1798    #[error("mDNS: empty builder msg")]
1799    ErrEmptyBuilderMsg,
1800
1801    //RTC
1802    /// ErrConnectionClosed indicates an operation executed after connection
1803    /// has already been closed.
1804    #[error("connection closed")]
1805    ErrConnectionClosed,
1806
1807    /// ErrDataChannelClosed indicates an operation executed when the data
1808    /// channel is not (yet) open or closed.
1809    #[error("data channel closed")]
1810    ErrDataChannelClosed,
1811
1812    /// ErrDataChannelNotOpen indicates a send was attempted on a data channel
1813    /// whose underlying SCTP stream has not been established yet — its
1814    /// `ready_state` is still `connecting`. Wait for the channel to open.
1815    #[error("data channel is not open yet")]
1816    ErrDataChannelNotOpen,
1817
1818    /// ErrDataChannelStreamIdNotAssigned indicates an operation that needs the channel's SCTP
1819    /// stream identifier ran before one was assigned.
1820    ///
1821    /// A data channel announced in-band has no stream identifier until the SCTP connected
1822    /// procedure assigns one, because RFC 8832 section 6 ties its parity to the DTLS role:
1823    /// even for the client, odd for the server. Until that role is resolved there is no
1824    /// correct identifier to pick, so the channel carries none rather than a guess.
1825    #[error("data channel stream identifier has not been assigned yet")]
1826    ErrDataChannelStreamIdNotAssigned,
1827
1828    /// ErrDataChannelNonExist indicates an operation executed when the data
1829    /// channel not existed.
1830    #[error("data channel not existed")]
1831    ErrDataChannelNotExisted,
1832
1833    /// ErrSendBufferFull indicates that a data-channel send was rejected because
1834    /// the channel's outstanding send buffer exceeded the configured hard ceiling
1835    /// (back-pressure). Retry after the buffer drains (e.g. on OnBufferedAmountLow).
1836    #[error("data channel send buffer full")]
1837    ErrSendBufferFull,
1838
1839    /// ErrCertificateExpired indicates that an x509 certificate has expired.
1840    #[error("x509Cert expired")]
1841    ErrCertificateExpired,
1842
1843    /// An ICE server with no url (W3C "set a configuration": "If urls is empty, throw a
1844    /// SyntaxError").
1845    #[error("an ICE server has no url")]
1846    ErrNoIceServerUrls,
1847
1848    /// ErrNoTurnCredentials indicates that a TURN server URL was provided
1849    /// without required credentials.
1850    #[error("turn server credentials required")]
1851    ErrNoTurnCredentials,
1852
1853    /// ErrTurnCredentials indicates that provided TURN credentials are partial
1854    /// or malformed.
1855    #[error("invalid turn server credentials")]
1856    ErrTurnCredentials,
1857
1858    /// ErrExistingTrack indicates that a track already exists.
1859    #[error("track already exists")]
1860    ErrExistingTrack,
1861
1862    /// ErrExistingTrack indicates that a track already exists.
1863    #[error("track not existed")]
1864    ErrTrackNotExisted,
1865
1866    /// ErrPrivateKeyType indicates that a particular private key encryption
1867    /// chosen to generate a certificate is not supported.
1868    #[error("private key type not supported")]
1869    ErrPrivateKeyType,
1870
1871    /// ErrModifyingPeerIdentity indicates that an attempt to modify
1872    /// PeerIdentity was made after PeerConnection has been initialized.
1873    #[error("peerIdentity cannot be modified")]
1874    ErrModifyingPeerIdentity,
1875
1876    /// ErrModifyingCertificates indicates that an attempt to modify
1877    /// Certificates was made after PeerConnection has been initialized.
1878    #[error("certificates cannot be modified")]
1879    ErrModifyingCertificates,
1880
1881    /// ErrNonCertificate indicates that there is no certificate
1882    #[error("no certificate")]
1883    ErrNonCertificate,
1884
1885    /// ErrModifyingBundlePolicy indicates that an attempt to modify
1886    /// BundlePolicy was made after PeerConnection has been initialized.
1887    #[error("bundle policy cannot be modified")]
1888    ErrModifyingBundlePolicy,
1889
1890    /// ErrModifyingRTCPMuxPolicy indicates that an attempt to modify
1891    /// RTCPMuxPolicy was made after PeerConnection has been initialized.
1892    #[error("rtcp mux policy cannot be modified")]
1893    ErrModifyingRTCPMuxPolicy,
1894
1895    /// ErrModifyingICECandidatePoolSize indicates that an attempt to modify
1896    /// ICECandidatePoolSize was made after PeerConnection has been initialized.
1897    #[error("ice candidate pool size cannot be modified")]
1898    ErrModifyingICECandidatePoolSize,
1899
1900    /// ErrStringSizeLimit indicates that the character size limit of string is
1901    /// exceeded. The limit is hardcoded to 65535 according to specifications.
1902    #[error("data channel label exceeds size limit")]
1903    ErrStringSizeLimit,
1904
1905    /// ErrNegotiatedWithoutID indicates that an attempt to create a data channel
1906    /// was made while setting the negotiated option to true without providing
1907    /// the negotiated channel ID.
1908    #[error("negotiated set without channel id")]
1909    ErrNegotiatedWithoutID,
1910
1911    /// ErrRetransmitsOrPacketLifeTime indicates that an attempt to create a data
1912    /// channel was made with both options max_packet_life_time and max_retransmits
1913    /// set together. Such configuration is not supported by the specification
1914    /// and is mutually exclusive.
1915    #[error("both max_packet_life_time and max_retransmits was set")]
1916    ErrRetransmitsOrPacketLifeTime,
1917
1918    /// ErrCodecNotFound is returned when a codec search to the Media Engine fails
1919    #[error("codec not found")]
1920    ErrCodecNotFound,
1921
1922    /// ErrNoRemoteDescription indicates that an operation was rejected because
1923    /// the remote description is not set
1924    #[error("remote description is not set")]
1925    ErrNoRemoteDescription,
1926
1927    /// ErrIceCandidateMediaSectionNotFound indicates that the sdpMid or sdpMLineIndex of a
1928    /// remote candidate names no media section of the remote description
1929    #[error(
1930        "no media section of the remote description matches the candidate's sdpMid or sdpMLineIndex"
1931    )]
1932    ErrIceCandidateMediaSectionNotFound,
1933
1934    /// ErrIceCandidateUsernameFragmentMismatch indicates that the usernameFragment of a remote
1935    /// candidate is not the ice-ufrag of its media section in the remote description
1936    #[error("the candidate's usernameFragment is not its media section's ice-ufrag")]
1937    ErrIceCandidateUsernameFragmentMismatch,
1938
1939    /// ErrSessionDescriptionInvalidIceCredentials indicates set_remote_description was called
1940    /// with an ice-ufrag or ice-pwd that is not RFC 8839 §5.4 syntax (4 to 256, or 22 to 256,
1941    /// ice-chars: ALPHA, DIGIT, "+" and "/")
1942    #[error(
1943        "set_remote_description called with an ice-ufrag or ice-pwd that isn't RFC 8839 syntax"
1944    )]
1945    ErrSessionDescriptionInvalidIceCredentials,
1946
1947    /// ErrIncorrectSDPSemantics indicates that the PeerConnection was configured to
1948    /// generate SDP Answers with different SDP Semantics than the received Offer
1949    #[error("offer SDP semantics does not match configuration")]
1950    ErrIncorrectSDPSemantics,
1951
1952    /// ErrIncorrectSignalingState indicates that the signaling state of PeerConnection is not correct
1953    #[error("operation can not be run in current signaling state")]
1954    ErrIncorrectSignalingState,
1955
1956    /// ErrProtocolTooLarge indicates that value given for a DataChannelInit protocol is
1957    /// longer then 65535 bytes
1958    #[error("protocol is larger then 65535 bytes")]
1959    ErrProtocolTooLarge,
1960
1961    /// ErrLabelTooLarge indicates that the label given for a data channel is longer than the
1962    /// 65535 bytes a DATA_CHANNEL_OPEN can carry (RFC 8832 section 5.1)
1963    #[error("label is larger than 65535 bytes")]
1964    ErrLabelTooLarge,
1965
1966    /// An SRTP or SRTCP replay window of 1 to 63 packets (RFC 3711 section 3.3.2: at least 64).
1967    #[error("the {0} replay window of {1} packets is below the 64 RFC 3711 requires")]
1968    ErrSrtpReplayWindowTooSmall(&'static str, usize),
1969
1970    /// W3C `OperationError`, with what failed.
1971    #[error("OperationError: {0}")]
1972    ErrOperationError(String),
1973
1974    /// A character `insertDTMF` does not take (W3C: an `InvalidCharacterError`).
1975    #[error("{0:?} is not a DTMF tone")]
1976    ErrDtmfInvalidCharacter(char),
1977
1978    /// A send would take a data channel's `bufferedAmount` above the SCTP transport's
1979    /// `[[MaxBufferSize]]` (W3C `send()`: an `OperationError`).
1980    #[error("the data channel's send buffer is full")]
1981    ErrDataChannelBufferFull,
1982
1983    /// A negotiated data channel id at or above the connected SCTP transport's `maxChannels`
1984    /// (W3C createDataChannel: an `OperationError`).
1985    #[error("the data channel id is not below the SCTP transport's maxChannels")]
1986    ErrDataChannelIdAboveMaxChannels,
1987
1988    /// ErrDataChannelIdInUse indicates that a data channel was created with a negotiated id
1989    /// whose SCTP stream already carries a data channel (RFC 8831 section 6.5)
1990    #[error("data channel id is already in use")]
1991    ErrDataChannelIdInUse,
1992
1993    /// ErrSenderNotCreatedByConnection indicates remove_track was called with a RtpSender not created
1994    /// by this PeerConnection
1995    #[error("RtpSender not created by this PeerConnection")]
1996    ErrSenderNotCreatedByConnection,
1997
1998    /// ErrSenderInitialTrackIdAlreadySet indicates a second call to
1999    /// RtpSender::set_initial_track_id which is not allowed.
2000    #[error("RtpSender's initial_track_id has already been set")]
2001    ErrSenderInitialTrackIdAlreadySet,
2002
2003    /// ErrSessionDescriptionNoFingerprint indicates set_remote_description was called with a SessionDescription that has no
2004    /// fingerprint
2005    #[error("set_remote_description called with no fingerprint")]
2006    ErrSessionDescriptionNoFingerprint,
2007
2008    /// ErrSessionDescriptionInvalidFingerprint indicates set_remote_description was called with a SessionDescription that
2009    /// has an invalid fingerprint
2010    #[error("set_remote_description called with an invalid fingerprint")]
2011    ErrSessionDescriptionInvalidFingerprint,
2012
2013    /// ErrSessionDescriptionConflictingFingerprints indicates set_remote_description was called with a SessionDescription that
2014    /// has an conflicting fingerprints
2015    #[error("set_remote_description called with multiple conflicting fingerprint")]
2016    ErrSessionDescriptionConflictingFingerprints,
2017
2018    /// ErrSessionDescriptionInvalidSetup indicates set_remote_description was called with a SessionDescription whose
2019    /// `a=setup` value is not `active`, `passive` or `actpass` (RFC 4145 section 4; RFC 8842 section 5.1 bars
2020    /// `holdconn` from DTLS), or whose sections give different values for the one transport
2021    #[error("set_remote_description called with an invalid setup attribute")]
2022    ErrSessionDescriptionInvalidSetup,
2023
2024    /// ErrSessionDescriptionInvalidTlsId indicates set_remote_description was called with a SessionDescription whose
2025    /// `a=tls-id` value is not 20 to 255 characters of the RFC 8842 section 4 alphabet, or whose sections give
2026    /// different values for the one transport
2027    #[error("set_remote_description called with an invalid tls-id attribute")]
2028    ErrSessionDescriptionInvalidTlsId,
2029
2030    /// ErrInvalidIdentityAssertion indicates an `a=identity` value that does not follow RFC 8827 section 5
2031    #[error("invalid identity assertion")]
2032    ErrInvalidIdentityAssertion,
2033
2034    /// ErrSessionDescriptionMissingIceUfrag indicates set_remote_description was called with a SessionDescription that
2035    /// is missing an ice-ufrag value
2036    #[error("set_remote_description called with no ice-ufrag")]
2037    ErrSessionDescriptionMissingIceUfrag,
2038
2039    /// ErrSessionDescriptionMissingIcePwd indicates set_remote_description was called with a SessionDescription that
2040    /// is missing an ice-pwd value
2041    #[error("set_remote_description called with no ice-pwd")]
2042    ErrSessionDescriptionMissingIcePwd,
2043
2044    /// ErrSessionDescriptionConflictingIceUfrag  indicates set_remote_description was called with a SessionDescription that
2045    /// contains multiple conflicting ice-ufrag values
2046    #[error("set_remote_description called with multiple conflicting ice-ufrag values")]
2047    ErrSessionDescriptionConflictingIceUfrag,
2048
2049    /// ErrSessionDescriptionConflictingIcePwd indicates set_remote_description was called with a SessionDescription that
2050    /// contains multiple conflicting ice-pwd values
2051    #[error("set_remote_description called with multiple conflicting ice-pwd values")]
2052    ErrSessionDescriptionConflictingIcePwd,
2053
2054    /// ErrSessionDescriptionMissingCryptex indicates set_remote_description was called, under
2055    /// the `Require` RTP header encryption policy, with a SessionDescription that has an RTP
2056    /// media section without Cryptex (RFC 9335 `a=cryptex`)
2057    #[error("set_remote_description called without a=cryptex while header encryption is required")]
2058    ErrSessionDescriptionMissingCryptex,
2059
2060    /// ErrNoSRTPProtectionProfile indicates that the DTLS handshake completed and no SRTP Protection Profile was chosen
2061    #[error("DTLS Handshake completed and no SRTP Protection Profile was chosen")]
2062    ErrNoSRTPProtectionProfile,
2063
2064    /// ErrFailedToGenerateCertificateFingerprint indicates that we failed to generate the fingerprint used for comparing certificates
2065    #[error("failed to generate certificate fingerprint")]
2066    ErrFailedToGenerateCertificateFingerprint,
2067
2068    /// ErrNoCodecsAvailable indicates that operation isn't possible because the MediaEngine has no codecs available
2069    #[error("operation failed no codecs are available")]
2070    ErrNoCodecsAvailable,
2071
2072    /// ErrUnsupportedCodec indicates the remote peer doesn't support the requested codec
2073    #[error("unable to start track, codec is not supported by remote")]
2074    ErrUnsupportedCodec,
2075
2076    /// Invalid state error.
2077    #[error("Invalid state error")]
2078    InvalidStateError,
2079
2080    /// Invalid modification error.
2081    #[error("Invalid modification error")]
2082    InvalidModificationError,
2083
2084    /// Not found error: an argument names an object the callee does not have (W3C
2085    /// `NotFoundError`), such as a candidate pair that is not on the ICE agent's list.
2086    #[error("Not found error")]
2087    NotFoundError,
2088
2089    /// Invalid access error: an argument names something that is not the object's (W3C
2090    /// `InvalidAccessError`), such as a statistics selector that is not a sender or receiver
2091    /// of the peer connection.
2092    #[error("Invalid access error")]
2093    InvalidAccessError,
2094
2095    /// Range error.
2096    #[error("Range error {0}")]
2097    RangeError(String),
2098
2099    /// Type error: an argument is not a value the operation takes (W3C / WebIDL `TypeError`).
2100    #[error("Type error {0}")]
2101    TypeError(String),
2102
2103    /// Media Capture `OverconstrainedError`: constraints that cannot be satisfied, naming the
2104    /// constraint (W3C mediacapture-main 4.3.3 applyConstraints; webrtc-pc 9.3.1: always for
2105    /// the video properties of a remote track).
2106    #[error("Overconstrained: {0}")]
2107    OverconstrainedError(String),
2108
2109    /// draft-ietf-avtcore-rtp-sframe-03 section 6: the section's SFrame offer was answered
2110    /// without `a=sframe`; its media is not sent (no unencrypted fallback).
2111    #[error("SFrame was offered and the answer refused it: no media is sent")]
2112    ErrSFrameRefused,
2113
2114    /// A session description that does not parse (W3C webrtc-pc section 11.1, an `RTCError`
2115    /// with `errorDetail` `sdp-syntax-error`): what the SDP parser found, and on which line.
2116    #[error("SDP syntax error{}: {error}", .line_number.map(|n| format!(" on line {n}")).unwrap_or_default())]
2117    SdpSyntaxError {
2118        /// The line the error is about, from 1; `None` when it is about the whole description.
2119        line_number: Option<usize>,
2120        /// The parser's error.
2121        error: Box<Error>,
2122    },
2123
2124    /// ErrSenderWithNoCodecs indicates that a RTPSender was created without any codecs. To send media the MediaEngine needs at
2125    /// least one configured codec.
2126    #[error("unable to populate media section, RTPSender created with no codecs")]
2127    ErrSenderWithNoCodecs,
2128
2129    /// ErrSenderWithNoSSRCs indicates that a RTPSender was created without any SSRRs. To send media the Sender needs at
2130    /// least one configured ssrc.
2131    #[error("unable to populate media section, RTPSender created with no ssrcs")]
2132    ErrSenderWithNoSSRCs,
2133
2134    /// ErrRTPSenderNewTrackHasIncorrectKind indicates that the new track is of a different kind than the previous/original
2135    #[error("new track must be of the same kind as previous")]
2136    ErrRTPSenderNewTrackHasIncorrectKind,
2137
2138    /// New track has incorrect envelope.
2139    #[error("new track has incorrect envelope")]
2140    ErrRTPSenderNewTrackHasIncorrectEnvelope,
2141
2142    /// ErrRTPSenderDataSent indicates that the sequence number transformer tries to be enabled after the data sending began
2143    #[error("Sequence number transformer must be enabled before sending data")]
2144    ErrRTPSenderDataSent,
2145
2146    /// ErrRTPSenderSeqTransEnabled indicates that the sequence number transformer has been already enabled
2147    #[error("Sequence number transformer has been already enabled")]
2148    ErrRTPSenderSeqTransEnabled,
2149
2150    /// ErrUnbindFailed indicates that a TrackLocal was not able to be unbind
2151    #[error("failed to unbind TrackLocal from PeerConnection")]
2152    ErrUnbindFailed,
2153
2154    /// ErrNoPayloaderForCodec indicates that the requested codec does not have a payloader
2155    #[error("the requested codec does not have a payloader")]
2156    ErrNoPayloaderForCodec,
2157
2158    /// ErrRegisterHeaderExtensionInvalidDirection indicates that a extension was registered with different
2159    /// directions for two different calls.
2160    #[error("a header extension must be registered with the same direction each time")]
2161    ErrRegisterHeaderExtensionInvalidDirection,
2162
2163    /// Invalid direction.
2164    #[error("invalid direction")]
2165    ErrInvalidDirection,
2166
2167    /// ErrRegisterHeaderExtensionNoFreeID indicates that there was no extension ID available which
2168    /// in turn means that all 254 ids an RTP header can carry (1 to 14, and 16 to 255 in the
2169    /// two-byte form, RFC 8285) have been used.
2170    #[error(
2171        "no header extension ID was free to use (the maximum of 254 extensions have been registered)"
2172    )]
2173    ErrRegisterHeaderExtensionNoFreeID,
2174
2175    /// ErrSimulcastProbeOverflow indicates that too many Simulcast probe streams are in flight and the requested SSRC was ignored
2176    #[error("simulcast probe limit has been reached, new SSRC has been discarded")]
2177    ErrSimulcastProbeOverflow,
2178
2179    /// Enable detaching by calling webrtc.DetachDataChannels.
2180    #[error("enable detaching by calling webrtc.DetachDataChannels()")]
2181    ErrDetachNotEnabled,
2182    /// Datachannel not opened yet, try calling Detach from OnOpen.
2183    #[error("datachannel not opened yet, try calling Detach from OnOpen")]
2184    ErrDetachBeforeOpened,
2185    /// The DTLS transport has not started yet.
2186    #[error("the DTLS transport has not started yet")]
2187    ErrDtlsTransportNotStarted,
2188    /// Failed extracting keys from DTLS for SRTP.
2189    #[error("failed extracting keys from DTLS for SRTP")]
2190    ErrDtlsKeyExtractionFailed,
2191    /// Failed to start SRTP.
2192    #[error("failed to start SRTP")]
2193    ErrFailedToStartSRTP,
2194    /// Failed to start SRTCP.
2195    #[error("failed to start SRTCP")]
2196    ErrFailedToStartSRTCP,
2197    /// Attempted to start DTLSTransport that is not in new state.
2198    #[error("attempted to start DTLSTransport that is not in new state")]
2199    ErrInvalidDTLSStart,
2200    /// Peer didn't provide certificate via DTLS.
2201    #[error("peer didn't provide certificate via DTLS")]
2202    ErrNoRemoteCertificate,
2203    /// Identity provider is not implemented.
2204    #[error("identity provider is not implemented")]
2205    ErrIdentityProviderNotImplemented,
2206    /// Remote certificate does not match any fingerprint.
2207    #[error("remote certificate does not match any fingerprint")]
2208    ErrNoMatchingCertificateFingerprint,
2209    /// Unsupported fingerprint algorithm.
2210    #[error("unsupported fingerprint algorithm")]
2211    ErrUnsupportedFingerprintAlgorithm,
2212    /// ICE connection not started.
2213    #[error("ICE connection not started")]
2214    ErrICEConnectionNotStarted,
2215    /// Unknown candidate type.
2216    #[error("unknown candidate type")]
2217    ErrICECandidateTypeUnknown,
2218    /// Cannot convert ICE.CandidateType into webrtc.ICECandidateType, invalid type.
2219    #[error("cannot convert ice.CandidateType into webrtc.ICECandidateType, invalid type")]
2220    ErrICEInvalidConvertCandidateType,
2221    /// ICEAgent does not exist.
2222    #[error("ICEAgent does not exist")]
2223    ErrICEAgentNotExist,
2224    /// Unable to convert ICE candidates to ICECandidates.
2225    #[error("unable to convert ICE candidates to ICECandidates")]
2226    ErrICECandidatesConversionFailed,
2227    /// Unknown ICE Role.
2228    #[error("unknown ICE Role")]
2229    ErrICERoleUnknown,
2230    /// Unknown protocol.
2231    #[error("unknown protocol")]
2232    ErrICEProtocolUnknown,
2233    /// Gatherer not started.
2234    #[error("gatherer not started")]
2235    ErrICEGathererNotStarted,
2236    /// Unknown network type.
2237    #[error("unknown network type")]
2238    ErrNetworkTypeUnknown,
2239    /// New SDP does not match previous offer.
2240    #[error("new sdp does not match previous offer")]
2241    ErrSDPDoesNotMatchOffer,
2242    /// New SDP does not match previous answer.
2243    #[error("new sdp does not match previous answer")]
2244    ErrSDPDoesNotMatchAnswer,
2245    /// A remote answer does not answer the pending local offer (RFC 3264 section 6, RFC 9429
2246    /// section 5.8.3): the text names the media section and what differs.
2247    #[error("the answer does not match the offer: {0}")]
2248    ErrAnswerDoesNotMatchOffer(String),
2249    /// Provided value is not a valid enum value of type SDPType.
2250    #[error("provided value is not a valid enum value of type SDPType")]
2251    ErrPeerConnSDPTypeInvalidValue,
2252    /// Invalid state change op.
2253    #[error("invalid state change op")]
2254    ErrPeerConnStateChangeInvalid,
2255    /// Unhandled state change op.
2256    #[error("unhandled state change op")]
2257    ErrPeerConnStateChangeUnhandled,
2258    /// Invalid SDP type supplied to SetLocalDescription.
2259    #[error("invalid SDP type supplied to SetLocalDescription()")]
2260    ErrPeerConnSDPTypeInvalidValueSetLocalDescription,
2261    /// RemoteDescription contained media section without mid value.
2262    #[error("remoteDescription contained media section without mid value")]
2263    ErrPeerConnRemoteDescriptionWithoutMidValue,
2264    /// LocalDescription contained media section without mid value.
2265    #[error("localDescription contained media section without mid value")]
2266    ErrPeerConnLocalDescriptionWithoutMidValue,
2267    /// RemoteDescription has not been set yet.
2268    #[error("remoteDescription has not been set yet")]
2269    ErrPeerConnRemoteDescriptionNil,
2270    /// LocalDescription has not been set yet.
2271    #[error("localDescription has not been set yet")]
2272    ErrPeerConnLocalDescriptionNil,
2273    /// Single media section has an explicit SSRC.
2274    #[error("single media section has an explicit SSRC")]
2275    ErrPeerConnSingleMediaSectionHasExplicitSSRC,
2276    /// Could not add transceiver for remote SSRC.
2277    #[error("could not add transceiver for remote SSRC")]
2278    ErrPeerConnRemoteSSRCAddTransceiver,
2279    /// Mid RTP Extensions required for Simulcast.
2280    #[error("mid RTP Extensions required for Simulcast")]
2281    ErrPeerConnSimulcastMidRTPExtensionRequired,
2282    /// Stream id RTP Extensions required for Simulcast.
2283    #[error("stream id RTP Extensions required for Simulcast")]
2284    ErrPeerConnSimulcastStreamIDRTPExtensionRequired,
2285    /// Incoming SSRC failed Simulcast probing.
2286    #[error("incoming SSRC failed Simulcast probing")]
2287    ErrPeerConnSimulcastIncomingSSRCFailed,
2288    /// Failed collecting stats.
2289    #[error("failed collecting stats")]
2290    ErrPeerConnStatsCollectionFailed,
2291    /// Add_transceiver_from_kind only accepts one RTPTransceiverInit.
2292    #[error("add_transceiver_from_kind only accepts one RTPTransceiverInit")]
2293    ErrPeerConnAddTransceiverFromKindOnlyAcceptsOne,
2294    /// Add_transceiver_from_track only accepts one RTPTransceiverInit.
2295    #[error("add_transceiver_from_track only accepts one RTPTransceiverInit")]
2296    ErrPeerConnAddTransceiverFromTrackOnlyAcceptsOne,
2297    /// Add_transceiver_from_kind currently only supports recvonly.
2298    #[error("add_transceiver_from_kind currently only supports recvonly")]
2299    ErrPeerConnAddTransceiverFromKindSupport,
2300    /// Add_transceiver_from_track currently only supports sendonly and sendrecv.
2301    #[error("add_transceiver_from_track currently only supports sendonly and sendrecv")]
2302    ErrPeerConnAddTransceiverFromTrackSupport,
2303    /// TODO set_identity_provider.
2304    #[error("TODO set_identity_provider")]
2305    ErrPeerConnSetIdentityProviderNotImplemented,
2306    /// Write_RTCP failed to open write_stream.
2307    #[error("write_rtcp failed to open write_stream")]
2308    ErrPeerConnWriteRTCPOpenWriteStream,
2309    /// Cannot find transceiver with mid.
2310    #[error("cannot find transceiver with mid")]
2311    ErrPeerConnTransceiverMidNil,
2312    /// DTLSTransport must not be nil.
2313    #[error("DTLSTransport must not be nil")]
2314    ErrRTPReceiverDTLSTransportNil,
2315    /// Receive has already been called.
2316    #[error("Receive has already been called")]
2317    ErrRTPReceiverReceiveAlreadyCalled,
2318    /// Unable to find stream for Track with SSRC.
2319    #[error("unable to find stream for Track with SSRC")]
2320    ErrRTPReceiverWithSSRCTrackStreamNotFound,
2321    /// No trackStreams found for SSRC.
2322    #[error("no trackStreams found for SSRC")]
2323    ErrRTPReceiverForSSRCTrackStreamNotFound,
2324    /// No trackStreams found for RID.
2325    #[error("no trackStreams found for RID")]
2326    ErrRTPReceiverForRIDTrackStreamNotFound,
2327    /// Invalid RTP Receiver transition.
2328    #[error("invalid RTP Receiver transition")]
2329    ErrRTPReceiverStateChangeInvalid,
2330    /// Track must not be nil.
2331    #[error("Track must not be nil")]
2332    ErrRTPSenderTrackNil,
2333    /// RTPSender not existed.
2334    #[error("RTPSender not existed")]
2335    ErrRTPSenderNotExisted,
2336    /// Sender Track has been removed or replaced to nil.
2337    #[error("Sender Track has been removed or replaced to nil")]
2338    ErrRTPSenderTrackRemoved,
2339    /// Sender cannot add encoding as rid is empty.
2340    #[error("Sender cannot add encoding as rid is empty")]
2341    ErrRTPSenderRidNil,
2342    /// No `a=imageattr recv` line of the remote description can be satisfied for the
2343    /// resolution the encoder produces (RFC 9429 section 3.6.2): the encoding is not to be
2344    /// sent.
2345    #[error("no a=imageattr line of the remote description can be satisfied")]
2346    ErrImageAttrUnsatisfiable,
2347    /// Sender cannot add encoding as there is no base track.
2348    #[error("Sender cannot add encoding as there is no base track")]
2349    ErrRTPSenderNoBaseEncoding,
2350    /// Sender cannot add encoding as provided track does not match base track.
2351    #[error("Sender cannot add encoding as provided track does not match base track")]
2352    ErrRTPSenderBaseEncodingMismatch,
2353    /// Sender cannot encoding due to RID collision.
2354    #[error("Sender cannot encoding due to RID collision")]
2355    ErrRTPSenderRIDCollision,
2356    /// Two streams of a sender's encodings (a media, RTX or FEC SSRC) name the same SSRC: RFC
2357    /// 4588 section 4, "the original and retransmission streams ... MUST use two different
2358    /// SSRC values"; RFC 3550 section 8, one SSRC per source.
2359    #[error("sender encodings name SSRC {0} for more than one stream")]
2360    ErrRTPSenderSsrcCollision(u32),
2361    /// The application wrote RTCP feedback its section did not negotiate (RFC 4585 section
2362    /// 4.2, RFC 5104 section 7.2): the `a=rtcp-fb` type and parameter it needs.
2363    #[error("RTCP feedback `{0} {1}` was not negotiated for the stream")]
2364    ErrRTCPFeedbackNotNegotiated(String, String),
2365    /// An encoding's rid is not 1 to 255 alphanumeric characters (RFC 8852 section 3.1, the
2366    /// RtpStreamId the rid is sent as; RFC 8851 section 10).
2367    #[error("Sender cannot add encoding as its rid is not 1 to 255 alphanumeric characters")]
2368    ErrRTPSenderRidInvalid,
2369    /// An encoding names an SSRC another local stream of the connection has, or names one
2370    /// twice: every local stream is protected under the one SRTP master key, and two with the
2371    /// same SSRC would share a keystream (RFC 3711 sections 8 and 9.1, RFC 5764 section 3).
2372    #[error("Sender cannot use SSRC {0}: another local stream has it")]
2373    ErrRTPSenderSsrcTaken(u32),
2374    /// `RTCPeerConnection::set_peer_identity` without a remote description that carries an
2375    /// identity assertion (RFC 8827 section 5).
2376    #[error("the remote description carries no identity assertion")]
2377    ErrNoRemoteIdentityAssertion,
2378    /// The fingerprints an identity provider verified do not cover every fingerprint of the
2379    /// remote description (RFC 8827 section 7.4).
2380    #[error("the verified identity does not cover every fingerprint of the remote description")]
2381    ErrIdentityFingerprintsNotCovered,
2382    /// The certificate the DTLS association authenticated is not among the fingerprints an
2383    /// identity provider verified (RFC 8827 section 7.4).
2384    #[error("the certificate in use is not among the fingerprints of the verified identity")]
2385    ErrIdentityCertificateNotCovered,
2386    /// Sender does not have track for RID.
2387    #[error("Sender does not have track for RID")]
2388    ErrRTPSenderNoTrackForRID,
2389    /// RTPReceiver not existed.
2390    #[error("RTPReceiver not existed")]
2391    ErrRTPReceiverNotExisted,
2392    /// DTLSTransport must not be nil.
2393    #[error("DTLSTransport must not be nil")]
2394    ErrRTPSenderDTLSTransportNil,
2395    /// Send has already been called.
2396    #[error("Send has already been called")]
2397    ErrRTPSenderSendAlreadyCalled,
2398    /// RTPTransceiver not existed.
2399    #[error("RTPTransceiver not existed")]
2400    ErrRTPTransceiverNotExisted,
2401    /// SCTPTransport not existed.
2402    #[error("SCTPTransport not existed")]
2403    ErrSCTPTransportNotExisted,
2404    /// DTLSTransport not existed.
2405    #[error("DTLSTransport not existed")]
2406    ErrDTLSTransportNotExisted,
2407    /// ErrRTPSenderTrackNil.
2408    #[error("errRTPSenderTrackNil")]
2409    ErrRTPTransceiverCannotChangeMid,
2410    /// Invalid state change in RTPTransceiver.setSending.
2411    #[error("invalid state change in RTPTransceiver.setSending")]
2412    ErrRTPTransceiverSetSendingInvalidState,
2413    /// Unsupported codec type by this transceiver.
2414    #[error("unsupported codec type by this transceiver")]
2415    ErrRTPTransceiverCodecUnsupported,
2416    /// DTLS not established.
2417    #[error("DTLS not established")]
2418    ErrSCTPTransportDTLS,
2419    /// Add_transceiver_SDP called with 0 transceivers.
2420    #[error("add_transceiver_sdp() called with 0 transceivers")]
2421    ErrSDPZeroTransceivers,
2422    /// A data channel m= section without a valid `a=sctp-port` (RFC 8841 section 5).
2423    #[error("invalid Media Section. Data channel section without a valid a=sctp-port")]
2424    ErrSDPSctpPortInvalid,
2425    /// Invalid Media Section. Media + DataChannel both enabled.
2426    #[error("invalid Media Section. Media + DataChannel both enabled")]
2427    ErrSDPMediaSectionMediaDataChanInvalid,
2428    /// Invalid Media Section Track Index.
2429    #[error("invalid Media Section Track Index")]
2430    ErrSDPMediaSectionTrackInvalid,
2431    /// Can't rollback from stable state.
2432    #[error("can't rollback from stable state")]
2433    ErrSignalingStateCannotRollback,
2434    /// Invalid proposed signaling state transition.
2435    #[error("invalid proposed signaling state transition: {0}")]
2436    ErrSignalingStateProposedTransitionInvalid(String),
2437    /// Cannot convert to StatsICECandidatePairStateSucceeded invalid ICE candidate state.
2438    #[error("cannot convert to StatsICECandidatePairStateSucceeded invalid ice candidate state")]
2439    ErrStatsICECandidateStateInvalid,
2440    /// ICETransport can only be called in ICETransportStateNew.
2441    #[error("ICETransport can only be called in ICETransportStateNew")]
2442    ErrICETransportNotInNew,
2443    /// A local UDP candidate on a transport address the previous DTLS association used, given
2444    /// for the new association that replaces it (RFC 8842 sections 5.1 and 6: a new 3-tuple).
2445    #[error(
2446        "local candidate on {0}, a transport address of the previous DTLS association: a new DTLS association needs a new local address or port (RFC 8842 section 5.1)"
2447    )]
2448    ErrICECandidateAddressOfPreviousDtlsAssociation(std::net::SocketAddr),
2449    /// Bad Certificate PEM format.
2450    #[error("bad Certificate PEM format")]
2451    ErrCertificatePEMFormatError,
2452    /// SCTP is not established.
2453    #[error("SCTP is not established")]
2454    ErrSCTPNotEstablished,
2455
2456    /// DataChannel is not opened.
2457    #[error("DataChannel is not opened")]
2458    ErrClosedPipe,
2459    /// Interceptor is not bind.
2460    #[error("Interceptor is not bind")]
2461    ErrInterceptorNotBind,
2462    /// Excessive retries in CreateOffer.
2463    #[error("excessive retries in CreateOffer")]
2464    ErrExcessiveRetries,
2465
2466    /// Not long enough to be a RTP Packet.
2467    #[error("not long enough to be a RTP Packet")]
2468    ErrRTPTooShort,
2469
2470    /// SyntaxIdDirSplit indicates rid-syntax could not be parsed.
2471    #[error("RFC8851 mandates rid-syntax        = %s\"a=rid:\" rid-id SP rid-dir")]
2472    SimulcastRidParseErrorSyntaxIdDirSplit,
2473    /// UnknownDirection indicates rid-dir was not parsed. Should be "send" or "recv".
2474    #[error("RFC8851 mandates rid-dir           = %s\"send\" / %s\"recv\"")]
2475    SimulcastRidParseErrorUnknownDirection,
2476
2477    //SDP
2478    /// Codec not found.
2479    #[error("codec not found")]
2480    CodecNotFound,
2481    /// Missing whitespace.
2482    #[error("missing whitespace")]
2483    MissingWhitespace,
2484    /// Missing colon.
2485    #[error("missing colon")]
2486    MissingColon,
2487    /// Payload type not found.
2488    #[error("payload type not found")]
2489    PayloadTypeNotFound,
2490    /// SdpInvalidSyntax.
2491    #[error("SdpInvalidSyntax: {0}")]
2492    SdpInvalidSyntax(String),
2493    /// SdpInvalidValue.
2494    #[error("SdpInvalidValue: {0}")]
2495    SdpInvalidValue(String),
2496    /// SDP: empty time_descriptions.
2497    #[error("sdp: empty time_descriptions")]
2498    SdpEmptyTimeDescription,
2499    /// Parse extmap.
2500    #[error("parse extmap: {0}")]
2501    ParseExtMap(String),
2502    /// A syntax error at a known offset in the input, rendered with the offending character marked.
2503    #[error("{} --> {} <-- {}", .s.substring(0,*.p), .s.substring(*.p, *.p+1), .s.substring(*.p+1, .s.len())
2504    )]
2505    SyntaxError {
2506        /// The input being parsed.
2507        s: String,
2508        /// The byte offset of the offending character in `s`.
2509        p: usize,
2510    },
2511
2512    //Third Party Error
2513    /// Invalid PEM.
2514    #[error("invalid PEM: {0}")]
2515    InvalidPEM(String),
2516    /// Parse ip.
2517    #[error("parse ip: {0}")]
2518    ParseIp(#[from] net::AddrParseError),
2519    /// Parse int.
2520    #[error("parse int: {0}")]
2521    ParseInt(#[from] ParseIntError),
2522    /// An underlying I/O error.
2523    #[error("{0}")]
2524    Io(#[source] IoError),
2525    /// URL parse.
2526    #[error("url parse: {0}")]
2527    Url(#[from] url::ParseError),
2528    /// UTF-8.
2529    #[error("utf8: {0}")]
2530    Utf8(#[from] FromUtf8Error),
2531    /// An error from the standard library or another boxed source.
2532    #[error("{0}")]
2533    Std(#[source] StdError),
2534    //Other Errors
2535    /// Other RTCP Err.
2536    #[error("Other RTCP Err: {0}")]
2537    OtherRtcpErr(String),
2538    /// Other RTP Err.
2539    #[error("Other RTP Err: {0}")]
2540    OtherRtpErr(String),
2541    /// Other SRTP Err.
2542    #[error("Other SRTP Err: {0}")]
2543    OtherSrtpErr(String),
2544    /// Other STUN Err.
2545    #[error("Other STUN Err: {0}")]
2546    OtherStunErr(String),
2547    /// Other TURN Err.
2548    #[error("Other TURN Err: {0}")]
2549    OtherTurnErr(String),
2550    /// Other ICE Err.
2551    #[error("Other ICE Err: {0}")]
2552    OtherIceErr(String),
2553    /// Other DTLS Err.
2554    #[error("Other DTLS Err: {0}")]
2555    OtherDtlsErr(String),
2556    /// Other SCTP Err.
2557    #[error("Other SCTP Err: {0}")]
2558    OtherSctpErr(String),
2559    /// Other DataChannel Err.
2560    #[error("Other DataChannel Err: {0}")]
2561    OtherDataChannelErr(String),
2562    /// Other Interceptor Err.
2563    #[error("Other Interceptor Err: {0}")]
2564    OtherInterceptorErr(String),
2565    /// Other Media Err.
2566    #[error("Other Media Err: {0}")]
2567    OtherMediaErr(String),
2568    /// Other mDNS Err.
2569    #[error("Other mDNS Err: {0}")]
2570    OtherMdnsErr(String),
2571    /// Other SDP Err.
2572    #[error("Other SDP Err: {0}")]
2573    OtherSdpErr(String),
2574    /// Other PeerConnection Err.
2575    #[error("Other PeerConnection Err: {0}")]
2576    OtherPeerConnectionErr(String),
2577    /// A provider-neutral cryptographic operation failed.
2578    #[error("crypto: {0}")]
2579    Crypto(String),
2580    /// Stream transport: no connection or listener has this id (it was never opened, or it
2581    /// is closed).
2582    #[error("stream: unknown connection or listener")]
2583    ErrUnknownStream,
2584    /// Stream transport: the connection is closing or closed and takes no more data.
2585    #[error("stream: connection closed")]
2586    ErrStreamConnectionClosed,
2587    /// Stream transport: a message too long for the connection's framing (RFC 4571: 65535
2588    /// bytes).
2589    #[error("stream: message too long for its framing")]
2590    ErrStreamMessageTooLong,
2591    #[error("{0}")]
2592    /// An error that does not fit any other variant, carrying a description.
2593    Other(String),
2594}
2595
2596impl Error {
2597    /// Wraps any `std::error::Error` implementation as [`Error::Std`],
2598    /// preserving the original error and its stack trace.
2599    pub fn from_std<T>(error: T) -> Self
2600    where
2601        T: std::error::Error + Send + Sync + 'static,
2602    {
2603        Error::Std(StdError(Box::new(error)))
2604    }
2605
2606    /// The name of the W3C error a JavaScript API over this engine raises for this error, as
2607    /// webrtc-pc names them, where the engine knows it: `"InvalidAccessError"`,
2608    /// `"InvalidStateError"`, `"InvalidModificationError"`, `"NotFoundError"`, `"OperationError"` (an `RTCError`,
2609    /// see [`rtc_error_detail`](Self::rtc_error_detail)), `"RangeError"`, `"TypeError"`,
2610    /// `"OverconstrainedError"`. `None` for the others.
2611    ///
2612    /// W3C webrtc-pc section 4.4.1.5 ("set the session description"): a description that does
2613    /// not parse (RFC 9429 sections 5.8.1 and 5.8.2) rejects with an `RTCError` whose
2614    /// `errorDetail` is `"sdp-syntax-error"` ([`Error::SdpSyntaxError`], with its line, and the
2615    /// attribute grammar errors); one that fails the semantic checks of RFC 9429 section 5.8.3
2616    /// (credentials, fingerprints, mids, rtcp-mux, the answer against its offer, ...) rejects
2617    /// with an `InvalidAccessError`; one invalid for the signaling state with an
2618    /// `InvalidStateError`.
2619    pub fn dom_exception_name(&self) -> Option<&'static str> {
2620        match self {
2621            Error::SdpSyntaxError { .. } | Error::SdpInvalidSyntax(_) => Some("OperationError"),
2622            Error::InvalidAccessError
2623            | Error::SdpInvalidValue(_)
2624            | Error::ErrPeerConnRemoteDescriptionWithoutMidValue
2625            | Error::ErrSessionDescriptionInvalidIceCredentials
2626            | Error::ErrSessionDescriptionNoFingerprint
2627            | Error::ErrSessionDescriptionInvalidFingerprint
2628            | Error::ErrSessionDescriptionConflictingFingerprints
2629            | Error::ErrSessionDescriptionInvalidSetup
2630            | Error::ErrSessionDescriptionInvalidTlsId
2631            | Error::ErrSessionDescriptionMissingIceUfrag
2632            | Error::ErrSessionDescriptionMissingIcePwd
2633            | Error::ErrSessionDescriptionConflictingIceUfrag
2634            | Error::ErrSessionDescriptionConflictingIcePwd
2635            | Error::ErrSessionDescriptionMissingCryptex => Some("InvalidAccessError"),
2636            Error::InvalidStateError
2637            | Error::ErrConnectionClosed
2638            | Error::ErrIncorrectSignalingState
2639            | Error::ErrSignalingStateCannotRollback
2640            | Error::ErrSignalingStateProposedTransitionInvalid(_) => Some("InvalidStateError"),
2641            Error::InvalidModificationError => Some("InvalidModificationError"),
2642            Error::NotFoundError => Some("NotFoundError"),
2643            Error::RangeError(_) => Some("RangeError"),
2644            Error::TypeError(_) => Some("TypeError"),
2645            Error::OverconstrainedError(_) => Some("OverconstrainedError"),
2646            _ => None,
2647        }
2648    }
2649
2650    /// The `errorDetail` of the W3C `RTCError` (webrtc-pc section 11.1) this error is, when it
2651    /// is one: `"sdp-syntax-error"` for a description that does not parse.
2652    pub fn rtc_error_detail(&self) -> Option<&'static str> {
2653        match self {
2654            Error::SdpSyntaxError { .. } | Error::SdpInvalidSyntax(_) => Some("sdp-syntax-error"),
2655            _ => None,
2656        }
2657    }
2658
2659    /// Attempts to downcast an [`Error::Std`] variant to a concrete error type.
2660    ///
2661    /// Returns `None` if this error is not `Error::Std` or if the inner error
2662    /// is not of type `T`.
2663    pub fn downcast_ref<T: std::error::Error + 'static>(&self) -> Option<&T> {
2664        if let Error::Std(s) = self {
2665            return s.0.downcast_ref();
2666        }
2667
2668        None
2669    }
2670}
2671
2672/// Wrapper around [`std::io::Error`] that implements [`PartialEq`].
2673///
2674/// `io::Error` does not implement `PartialEq`, which is required by the
2675/// top-level [`enum@Error`] enum. This newtype delegates equality to
2676/// [`io::ErrorKind`], so two `IoError` values are equal when their kinds match.
2677#[derive(Debug, Error)]
2678#[error("io error: {0}")]
2679pub struct IoError(#[from] pub io::Error);
2680
2681// Workaround for wanting PartialEq for io::Error.
2682impl PartialEq for IoError {
2683    fn eq(&self, other: &Self) -> bool {
2684        self.0.kind() == other.0.kind()
2685    }
2686}
2687
2688impl From<io::Error> for Error {
2689    fn from(e: io::Error) -> Self {
2690        Error::Io(IoError(e))
2691    }
2692}
2693
2694/// An escape hatch to preserve stack traces for errors whose concrete type is unknown.
2695///
2696/// Some traits exported by this crate (e.g. `Conn`, `Listener`) return `Error`.
2697/// When those traits are used in higher-level crates that have their own error
2698/// types, callers are forced to handle foreign errors. `StdError` boxes any
2699/// `std::error::Error` implementation and wraps it in `Error::Std`, preserving
2700/// the original error's message and — where supported — its stack trace.
2701///
2702/// Use [`Error::from_std`] to construct this variant.
2703#[derive(Debug, Error)]
2704#[error("{0}")]
2705pub struct StdError(pub Box<dyn std::error::Error + Send + Sync>);
2706
2707impl PartialEq for StdError {
2708    fn eq(&self, _: &Self) -> bool {
2709        false
2710    }
2711}
2712
2713impl<T> From<std::sync::PoisonError<T>> for Error {
2714    fn from(e: std::sync::PoisonError<T>) -> Self {
2715        Error::PoisonError(e.to_string())
2716    }
2717}
2718
2719impl From<SystemTimeError> for Error {
2720    fn from(e: SystemTimeError) -> Self {
2721        Error::Other(e.to_string())
2722    }
2723}
2724
2725/// Flattens a list of errors into a single [`enum@Error`], joining their messages with newlines.
2726///
2727/// Returns `Ok(())` if `errs` is empty.
2728pub fn flatten_errs(errs: Vec<impl Into<Error>>) -> Result<()> {
2729    if errs.is_empty() {
2730        Ok(())
2731    } else {
2732        let errs_strs: Vec<String> = errs.into_iter().map(|e| e.into().to_string()).collect();
2733        Err(Error::Other(errs_strs.join("\n")))
2734    }
2735}