Skip to main content

rtc_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    /// Reason is too long.
244    #[error("Reason must be < 255 octets long")]
245    ReasonTooLong,
246    /// Invalid packet version.
247    #[error("Invalid packet version")]
248    BadVersion,
249    /// Invalid padding value.
250    #[error("Invalid padding value")]
251    WrongPadding,
252    /// Wrong feedback message type.
253    #[error("Wrong feedback message type")]
254    WrongFeedbackType,
255    /// Wrong payload type.
256    #[error("Wrong payload type")]
257    WrongPayloadType,
258    /// Header length is too small.
259    #[error("Header length is too small")]
260    HeaderTooSmall,
261    /// Media ssrc was defined as zero.
262    #[error("Media SSRC must be 0")]
263    SsrcMustBeZero,
264    /// Missing REMB identifier.
265    #[error("Missing REMB identifier")]
266    MissingRembIdentifier,
267    /// SSRC number and length mismatches.
268    #[error("SSRC num and length do not match")]
269    SsrcNumAndLengthMismatch,
270    /// Invalid size or start index.
271    #[error("Invalid size or startIndex")]
272    InvalidSizeOrStartIndex,
273    /// Delta exceeds limit.
274    #[error("Delta exceed limit")]
275    DeltaExceedLimit,
276    /// Packet status chunk is not 2 bytes.
277    #[error("Packet status chunk must be 2 bytes")]
278    PacketStatusChunkLength,
279    /// Invalid bitrate.
280    #[error("Invalid bitrate")]
281    InvalidBitrate,
282    /// Wrong chunk type.
283    #[error("Wrong chunk type")]
284    WrongChunkType,
285    /// Struct contains unexpected member type.
286    #[error("Struct contains unexpected member type")]
287    BadStructMemberType,
288    /// Cannot read into non-pointer.
289    #[error("Cannot read into non-pointer")]
290    BadReadParameter,
291    /// Invalid block size.
292    #[error("Invalid block size")]
293    InvalidBlockSize,
294
295    //RTP errors
296    /// RTP header size insufficient.
297    #[error("RTP header size insufficient")]
298    ErrHeaderSizeInsufficient,
299    /// RTP header size insufficient for extension.
300    #[error("RTP header size insufficient for extension")]
301    ErrHeaderSizeInsufficientForExtension,
302    /// Buffer too small.
303    #[error("buffer too small")]
304    ErrBufferTooSmall,
305    /// Extension not enabled.
306    #[error("extension not enabled")]
307    ErrHeaderExtensionsNotEnabled,
308    /// Extension not found.
309    #[error("extension not found")]
310    ErrHeaderExtensionNotFound,
311
312    /// Header extension id must be between 1 and 14 for RFC 5285 extensions.
313    #[error("header extension id must be between 1 and 14 for RFC 5285 extensions")]
314    ErrRfc8285oneByteHeaderIdrange,
315    /// Header extension payload must be 16bytes or less for RFC 5285 one byte extensions.
316    #[error("header extension payload must be 16bytes or less for RFC 5285 one byte extensions")]
317    ErrRfc8285oneByteHeaderSize,
318
319    /// Header extension id must be between 1 and 255 for RFC 5285 extensions.
320    #[error("header extension id must be between 1 and 255 for RFC 5285 extensions")]
321    ErrRfc8285twoByteHeaderIdrange,
322    /// Header extension payload must be 255bytes or less for RFC 5285 two byte extensions.
323    #[error("header extension payload must be 255bytes or less for RFC 5285 two byte extensions")]
324    ErrRfc8285twoByteHeaderSize,
325
326    /// Header extension id must be 0 for none RFC 5285 extensions.
327    #[error("header extension id must be 0 for none RFC 5285 extensions")]
328    ErrRfc3550headerIdrange,
329
330    /// Packet is not large enough.
331    #[error("packet is not large enough")]
332    ErrShortPacket,
333    /// Invalid nil packet.
334    #[error("invalid nil packet")]
335    ErrNilPacket,
336    /// Too many PDiff.
337    #[error("too many PDiff")]
338    ErrTooManyPDiff,
339    /// Too many spatial layers.
340    #[error("too many spatial layers")]
341    ErrTooManySpatialLayers,
342    /// NALU Type is unhandled.
343    #[error("NALU Type is unhandled")]
344    ErrUnhandledNaluType,
345
346    /// Corrupted H265 packet.
347    #[error("corrupted h265 packet")]
348    ErrH265CorruptedPacket,
349    /// Invalid H265 packet type.
350    #[error("invalid h265 packet type")]
351    ErrInvalidH265PacketType,
352
353    /// Payload is too small for OBU extension header.
354    #[error("payload is too small for OBU extension header")]
355    ErrPayloadTooSmallForObuExtensionHeader,
356    /// Payload is too small for OBU payload size.
357    #[error("payload is too small for OBU payload size")]
358    ErrPayloadTooSmallForObuPayloadSize,
359
360    /// Extension_payload must be in 32-bit words.
361    #[error("extension_payload must be in 32-bit words")]
362    HeaderExtensionPayloadNot32BitWords,
363    /// Audio level overflow.
364    #[error("audio level overflow")]
365    AudioLevelOverflow,
366    /// Playout delay overflow.
367    #[error("playout delay overflow")]
368    PlayoutDelayOverflow,
369    /// Payload is not large enough.
370    #[error("payload is not large enough")]
371    PayloadIsNotLargeEnough,
372    /// STAP-A declared size is larger than buffer.
373    #[error("STAP-A declared size({0}) is larger than buffer({1})")]
374    StapASizeLargerThanBuffer(usize, usize),
375    /// NALU type is currently not handled.
376    #[error("nalu type {0} is currently not handled")]
377    NaluTypeIsNotHandled(u8),
378
379    //SRTP
380    /// Duplicated packet.
381    #[error("duplicated packet")]
382    ErrDuplicated,
383    /// SRTP master key is not long enough.
384    #[error("SRTP master key is not long enough")]
385    ErrShortSrtpMasterKey,
386    /// SRTP master salt is not long enough.
387    #[error("SRTP master salt is not long enough")]
388    ErrShortSrtpMasterSalt,
389    /// No such SRTP Profile.
390    #[error("no such SRTP Profile")]
391    ErrNoSuchSrtpProfile,
392    /// IndexOverKdr > 0 is not supported yet.
393    #[error("indexOverKdr > 0 is not supported yet")]
394    ErrNonZeroKdrNotSupported,
395    /// Exporter called with wrong label.
396    #[error("exporter called with wrong label")]
397    ErrExporterWrongLabel,
398    /// No config provided.
399    #[error("no config provided")]
400    ErrNoConfig,
401    /// No conn provided.
402    #[error("no conn provided")]
403    ErrNoConn,
404    /// Failed to verify auth tag.
405    #[error("failed to verify auth tag")]
406    ErrFailedToVerifyAuthTag,
407    /// Packet is too short to be RTP packet.
408    #[error("packet is too short to be RTP packet")]
409    ErrTooShortRtp,
410    /// Packet is too short to be RTCP packet.
411    #[error("packet is too short to be RTCP packet")]
412    ErrTooShortRtcp,
413    /// Payload differs.
414    #[error("payload differs")]
415    ErrPayloadDiffers,
416    /// Started channel used incorrectly, should only be closed.
417    #[error("started channel used incorrectly, should only be closed")]
418    ErrStartedChannelUsedIncorrectly,
419    /// Stream has not been inited, unable to close.
420    #[error("stream has not been inited, unable to close")]
421    ErrStreamNotInited,
422    /// Stream is already closed.
423    #[error("stream is already closed")]
424    ErrStreamAlreadyClosed,
425    /// Stream is already inited.
426    #[error("stream is already inited")]
427    ErrStreamAlreadyInited,
428    /// Failed to cast child.
429    #[error("failed to cast child")]
430    ErrFailedTypeAssertion,
431    /// Exceeded the maximum number of packets.
432    #[error("exceeded the maximum number of packets")]
433    ErrExceededMaxPackets,
434
435    /// Index_over_kdr > 0 is not supported yet.
436    #[error("index_over_kdr > 0 is not supported yet")]
437    UnsupportedIndexOverKdr,
438    /// Invalid master key length for AES_256_cm.
439    #[error("invalid master key length for aes_256_cm")]
440    InvalidMasterKeyLength,
441    /// Invalid master salt length for AES_256_cm.
442    #[error("invalid master salt length for aes_256_cm")]
443    InvalidMasterSaltLength,
444    /// Out_len > 32 is not supported for AES_256_cm.
445    #[error("out_len > 32 is not supported for aes_256_cm")]
446    UnsupportedOutLength,
447    /// SRTP Master Key must be len , got.
448    #[error("SRTP Master Key must be len {0}, got {1}")]
449    SrtpMasterKeyLength(usize, usize),
450    /// SRTP Salt must be len , got.
451    #[error("SRTP Salt must be len {0}, got {1}")]
452    SrtpSaltLength(usize, usize),
453    /// SyntaxError.
454    #[error("SyntaxError: {0}")]
455    ExtMapParse(String),
456    /// SSRC not exist in SRTP_SSRC_state.
457    #[error("ssrc {0} not exist in srtp_ssrc_state")]
458    SsrcMissingFromSrtp(u32),
459    /// SRTP SSRC= index=: duplicated.
460    #[error("srtp ssrc={0} index={1}: duplicated")]
461    SrtpSsrcDuplicated(u32, u16),
462    /// Srtcp SSRC= index=: duplicated.
463    #[error("srtcp ssrc={0} index={1}: duplicated")]
464    SrtcpSsrcDuplicated(u32, usize),
465    /// SSRC not exist in srtcp_SSRC_state.
466    #[error("ssrc {0} not exist in srtcp_ssrc_state")]
467    SsrcMissingFromSrtcp(u32),
468    /// Stream with SSRC exists.
469    #[error("Stream with ssrc {0} exists")]
470    StreamWithSsrcExists(u32),
471    /// Session RTP/RTCP type must be same as input buffer.
472    #[error("Session RTP/RTCP type must be same as input buffer")]
473    SessionRtpRtcpTypeMismatch,
474    /// Session EOF.
475    #[error("Session EOF")]
476    SessionEof,
477    /// Too short SRTP packet: only bytes, expected > bytes.
478    #[error("too short SRTP packet: only {0} bytes, expected > {1} bytes")]
479    SrtpTooSmall(usize, usize),
480    /// Too short SRTCP packet: only bytes, expected > bytes.
481    #[error("too short SRTCP packet: only {0} bytes, expected > {1} bytes")]
482    SrtcpTooSmall(usize, usize),
483    /// Failed to verify RTP auth tag.
484    #[error("failed to verify rtp auth tag")]
485    RtpFailedToVerifyAuthTag,
486    /// Too short auth tag: only bytes, expected > bytes.
487    #[error("too short auth tag: only {0} bytes, expected > {1} bytes")]
488    RtcpInvalidLengthAuthTag(usize, usize),
489    /// Failed to verify RTCP auth tag.
490    #[error("failed to verify rtcp auth tag")]
491    RtcpFailedToVerifyAuthTag,
492    /// SessionSRTP has been closed.
493    #[error("SessionSRTP has been closed")]
494    SessionSrtpAlreadyClosed,
495    /// This stream is not a RTPStream.
496    #[error("this stream is not a RTPStream")]
497    InvalidRtpStream,
498    /// This stream is not a RTCPStream.
499    #[error("this stream is not a RTCPStream")]
500    InvalidRtcpStream,
501
502    //STUN errors
503    /// Attribute not found.
504    #[error("attribute not found")]
505    ErrAttributeNotFound,
506    /// Transaction is stopped.
507    #[error("transaction is stopped")]
508    ErrTransactionStopped,
509    /// Transaction not exists.
510    #[error("transaction not exists")]
511    ErrTransactionNotExists,
512    /// Transaction exists with same id.
513    #[error("transaction exists with same id")]
514    ErrTransactionExists,
515    /// Agent is closed.
516    #[error("agent is closed")]
517    ErrAgentClosed,
518    /// Transaction is timed out.
519    #[error("transaction is timed out")]
520    ErrTransactionTimeOut,
521    /// No default reason for ErrorCode.
522    #[error("no default reason for ErrorCode")]
523    ErrNoDefaultReason,
524    /// Unexpected EOF.
525    #[error("unexpected EOF")]
526    ErrUnexpectedEof,
527    /// Attribute size is invalid.
528    #[error("attribute size is invalid")]
529    ErrAttributeSizeInvalid,
530    /// Attribute size overflow.
531    #[error("attribute size overflow")]
532    ErrAttributeSizeOverflow,
533    /// Attempt to decode to nil message.
534    #[error("attempt to decode to nil message")]
535    ErrDecodeToNil,
536    /// Unexpected EOF: not enough bytes to read header.
537    #[error("unexpected EOF: not enough bytes to read header")]
538    ErrUnexpectedHeaderEof,
539    /// Integrity check failed.
540    #[error("integrity check failed")]
541    ErrIntegrityMismatch,
542    /// Fingerprint check failed.
543    #[error("fingerprint check failed")]
544    ErrFingerprintMismatch,
545    /// FINGERPRINT before MESSAGE-INTEGRITY attribute.
546    #[error("FINGERPRINT before MESSAGE-INTEGRITY attribute")]
547    ErrFingerprintBeforeIntegrity,
548    /// Bad UNKNOWN-ATTRIBUTES size.
549    #[error("bad UNKNOWN-ATTRIBUTES size")]
550    ErrBadUnknownAttrsSize,
551    /// Invalid length of IP value.
552    #[error("invalid length of IP value")]
553    ErrBadIpLength,
554    /// No connection provided.
555    #[error("no connection provided")]
556    ErrNoConnection,
557    /// Client is closed.
558    #[error("client is closed")]
559    ErrClientClosed,
560    /// No agent is set.
561    #[error("no agent is set")]
562    ErrNoAgent,
563    /// Collector is closed.
564    #[error("collector is closed")]
565    ErrCollectorClosed,
566    /// Unsupported network.
567    #[error("unsupported network")]
568    ErrUnsupportedNetwork,
569    /// Invalid URL.
570    #[error("invalid url")]
571    ErrInvalidUrl,
572    /// Unknown scheme type.
573    #[error("unknown scheme type")]
574    ErrSchemeType,
575    /// Invalid hostname.
576    #[error("invalid hostname")]
577    ErrHost,
578
579    // TURN errors
580    /// TURN: RelayAddress must be valid IP to use RelayAddressGeneratorStatic.
581    #[error("turn: RelayAddress must be valid IP to use RelayAddressGeneratorStatic")]
582    ErrRelayAddressInvalid,
583    /// TURN: PacketConnConfigs and ConnConfigs are empty, unable to proceed.
584    #[error("turn: PacketConnConfigs and ConnConfigs are empty, unable to proceed")]
585    ErrNoAvailableConns,
586    /// TURN: PacketConnConfig must have a non-nil Conn.
587    #[error("turn: PacketConnConfig must have a non-nil Conn")]
588    ErrConnUnset,
589    /// TURN: ListenerConfig must have a non-nil Listener.
590    #[error("turn: ListenerConfig must have a non-nil Listener")]
591    ErrListenerUnset,
592    /// TURN: RelayAddressGenerator has invalid ListeningAddress.
593    #[error("turn: RelayAddressGenerator has invalid ListeningAddress")]
594    ErrListeningAddressInvalid,
595    /// TURN: RelayAddressGenerator in RelayConfig is unset.
596    #[error("turn: RelayAddressGenerator in RelayConfig is unset")]
597    ErrRelayAddressGeneratorUnset,
598    /// TURN: max retries exceeded.
599    #[error("turn: max retries exceeded")]
600    ErrMaxRetriesExceeded,
601    /// TURN: MaxPort must be not 0.
602    #[error("turn: MaxPort must be not 0")]
603    ErrMaxPortNotZero,
604    /// TURN: MaxPort must be not 0.
605    #[error("turn: MaxPort must be not 0")]
606    ErrMinPortNotZero,
607    /// TURN: MaxPort less than MinPort.
608    #[error("turn: MaxPort less than MinPort")]
609    ErrMaxPortLessThanMinPort,
610    /// TURN: relay_conn cannot not be nil.
611    #[error("turn: relay_conn cannot not be nil")]
612    ErrNilConn,
613    /// TURN: TODO.
614    #[error("turn: TODO")]
615    ErrTodo,
616    /// TURN: already listening.
617    #[error("turn: already listening")]
618    ErrAlreadyListening,
619    /// TURN: Server failed to close.
620    #[error("turn: Server failed to close")]
621    ErrFailedToClose,
622    /// TURN: failed to retransmit transaction.
623    #[error("turn: failed to retransmit transaction")]
624    ErrFailedToRetransmitTransaction,
625    /// All retransmissions failed.
626    #[error("all retransmissions failed")]
627    ErrAllRetransmissionsFailed,
628    /// No binding found for channel.
629    #[error("no binding found for channel")]
630    ErrChannelBindNotFound,
631    /// STUN server address is not set for the client.
632    #[error("STUN server address is not set for the client")]
633    ErrStunserverAddressNotSet,
634    /// Only one Allocate caller is allowed.
635    #[error("only one Allocate() caller is allowed")]
636    ErrOneAllocateOnly,
637    /// Already allocated.
638    #[error("already allocated")]
639    ErrAlreadyAllocated,
640    /// Non-STUN message from STUN server.
641    #[error("non-STUN message from STUN server")]
642    ErrNonStunmessage,
643    /// Failed to decode STUN message.
644    #[error("failed to decode STUN message")]
645    ErrFailedToDecodeStun,
646    /// Unexpected STUN request message.
647    #[error("unexpected STUN request message")]
648    ErrUnexpectedStunrequestMessage,
649    /// Channel number not in [0x4000, 0x7FFF].
650    #[error("channel number not in [0x4000, 0x7FFF]")]
651    ErrInvalidChannelNumber,
652    /// ChannelData length != len(Data).
653    #[error("channelData length != len(Data)")]
654    ErrBadChannelDataLength,
655    /// Invalid value for requested family attribute.
656    #[error("invalid value for requested family attribute")]
657    ErrInvalidRequestedFamilyValue,
658    /// Fake error.
659    #[error("fake error")]
660    ErrFakeErr,
661    /// Use of closed network connection.
662    #[error("use of closed network connection")]
663    ErrClosed,
664    /// Addr is not a net.UDPAddr.
665    #[error("addr is not a net.UDPAddr")]
666    ErrUdpaddrCast,
667    /// Try-lock is already locked.
668    #[error("try-lock is already locked")]
669    ErrDoubleLock,
670    /// Transaction closed.
671    #[error("transaction closed")]
672    ErrTransactionClosed,
673    /// Wait_for_result called on non-result transaction.
674    #[error("wait_for_result called on non-result transaction")]
675    ErrWaitForResultOnNonResultTransaction,
676    /// Failed to build refresh request.
677    #[error("failed to build refresh request")]
678    ErrFailedToBuildRefreshRequest,
679    /// Failed to refresh allocation.
680    #[error("failed to refresh allocation")]
681    ErrFailedToRefreshAllocation,
682    /// Failed to get lifetime from refresh response.
683    #[error("failed to get lifetime from refresh response")]
684    ErrFailedToGetLifetime,
685    /// Too short buffer.
686    #[error("too short buffer")]
687    ErrShortBuffer,
688    /// Unexpected response type.
689    #[error("unexpected response type")]
690    ErrUnexpectedResponse,
691    /// AllocatePacketConn must be set.
692    #[error("AllocatePacketConn must be set")]
693    ErrAllocatePacketConnMustBeSet,
694    /// AllocateConn must be set.
695    #[error("AllocateConn must be set")]
696    ErrAllocateConnMustBeSet,
697    /// LeveledLogger must be set.
698    #[error("LeveledLogger must be set")]
699    ErrLeveledLoggerMustBeSet,
700    /// You cannot use the same channel number with different peer.
701    #[error("you cannot use the same channel number with different peer")]
702    ErrSameChannelDifferentPeer,
703    /// Allocations must not be created with nil FivTuple.
704    #[error("allocations must not be created with nil FivTuple")]
705    ErrNilFiveTuple,
706    /// Allocations must not be created with nil FiveTuple.src_addr.
707    #[error("allocations must not be created with nil FiveTuple.src_addr")]
708    ErrNilFiveTupleSrcAddr,
709    /// Allocations must not be created with nil FiveTuple.dst_addr.
710    #[error("allocations must not be created with nil FiveTuple.dst_addr")]
711    ErrNilFiveTupleDstAddr,
712    /// Allocations must not be created with nil turnSocket.
713    #[error("allocations must not be created with nil turnSocket")]
714    ErrNilTurnSocket,
715    /// Allocations must not be created with a lifetime of 0.
716    #[error("allocations must not be created with a lifetime of 0")]
717    ErrLifetimeZero,
718    /// Allocation attempt created with duplicate FiveTuple.
719    #[error("allocation attempt created with duplicate FiveTuple")]
720    ErrDupeFiveTuple,
721    /// Failed to cast net.Addr to *net.UDPAddr.
722    #[error("failed to cast net.Addr to *net.UDPAddr")]
723    ErrFailedToCastUdpaddr,
724    /// Failed to generate nonce.
725    #[error("failed to generate nonce")]
726    ErrFailedToGenerateNonce,
727    /// Failed to send error message.
728    #[error("failed to send error message")]
729    ErrFailedToSendError,
730    /// Duplicated Nonce generated, discarding request.
731    #[error("duplicated Nonce generated, discarding request")]
732    ErrDuplicatedNonce,
733    /// No such user exists.
734    #[error("no such user exists")]
735    ErrNoSuchUser,
736    /// Unexpected class.
737    #[error("unexpected class")]
738    ErrUnexpectedClass,
739    /// Unexpected method.
740    #[error("unexpected method")]
741    ErrUnexpectedMethod,
742    /// Failed to handle.
743    #[error("failed to handle")]
744    ErrFailedToHandle,
745    /// Unhandled STUN packet.
746    #[error("unhandled STUN packet")]
747    ErrUnhandledStunpacket,
748    /// Unable to handle ChannelData.
749    #[error("unable to handle ChannelData")]
750    ErrUnableToHandleChannelData,
751    /// Failed to create STUN message from packet.
752    #[error("failed to create stun message from packet")]
753    ErrFailedToCreateStunpacket,
754    /// Failed to create channel data from packet.
755    #[error("failed to create channel data from packet")]
756    ErrFailedToCreateChannelData,
757    /// Relay already allocated for 5-TUPLE.
758    #[error("relay already allocated for 5-TUPLE")]
759    ErrRelayAlreadyAllocatedForFiveTuple,
760    /// RequestedTransport must be UDP.
761    #[error("RequestedTransport must be UDP")]
762    ErrRequestedTransportMustBeUdp,
763    /// No support for DONT-FRAGMENT.
764    #[error("no support for DONT-FRAGMENT")]
765    ErrNoDontFragmentSupport,
766    /// Request must not contain RESERVATION-TOKEN and EVEN-PORT.
767    #[error("Request must not contain RESERVATION-TOKEN and EVEN-PORT")]
768    ErrRequestWithReservationTokenAndEvenPort,
769    /// No allocation found.
770    #[error("no allocation found")]
771    ErrNoAllocationFound,
772    /// Unable to handle send-indication, no permission added.
773    #[error("unable to handle send-indication, no permission added")]
774    ErrNoPermission,
775    /// Packet write smaller than packet.
776    #[error("packet write smaller than packet")]
777    ErrShortWrite,
778    /// No such channel bind.
779    #[error("no such channel bind")]
780    ErrNoSuchChannelBind,
781    /// Failed writing to socket.
782    #[error("failed writing to socket")]
783    ErrFailedWriteSocket,
784
785    // ICE errors
786    /// Indicates an error with Unknown info.
787    #[error("Unknown type")]
788    ErrUnknownType,
789
790    /// Indicates query arguments are provided in a STUN URL.
791    #[error("queries not supported in stun address")]
792    ErrStunQuery,
793
794    /// Indicates an malformed query is provided.
795    #[error("invalid query")]
796    ErrInvalidQuery,
797
798    /// Indicates malformed port is provided.
799    #[error("url parse: invalid port number")]
800    ErrPort,
801
802    /// Indicates local username fragment insufficient bits are provided.
803    /// Have to be at least 24 bits long.
804    #[error("local username fragment is less than 24 bits long")]
805    ErrLocalUfragInsufficientBits,
806
807    /// Indicates local passoword insufficient bits are provided.
808    /// Have to be at least 128 bits long.
809    #[error("local password is less than 128 bits long")]
810    ErrLocalPwdInsufficientBits,
811
812    /// Indicates an unsupported transport type was provided.
813    #[error("invalid transport protocol type")]
814    ErrProtoType,
815
816    /// Indicates agent does not have a valid candidate pair.
817    #[error("no candidate pairs available")]
818    ErrNoCandidatePairs,
819
820    /// Indicates agent connection was canceled by the caller.
821    #[error("connecting canceled by caller")]
822    ErrCanceledByCaller,
823
824    /// Indicates agent was started twice.
825    #[error("attempted to start agent twice")]
826    ErrMultipleStart,
827
828    /// Indicates agent was started with an empty remote ufrag.
829    #[error("remote ufrag is empty")]
830    ErrRemoteUfragEmpty,
831
832    /// Indicates agent was started with an empty remote pwd.
833    #[error("remote pwd is empty")]
834    ErrRemotePwdEmpty,
835
836    /// Indicates agent was started without on_candidate.
837    #[error("no on_candidate provided")]
838    ErrNoOnCandidateHandler,
839
840    /// Indicates GatherCandidates has been called multiple times.
841    #[error("attempting to gather candidates during gathering state")]
842    ErrMultipleGatherAttempted,
843
844    /// Indicates agent was give TURN URL with an empty Username.
845    #[error("username is empty")]
846    ErrUsernameEmpty,
847
848    /// Indicates agent was give TURN URL with an empty Password.
849    #[error("password is empty")]
850    ErrPasswordEmpty,
851
852    /// Indicates we were unable to parse a candidate address.
853    #[error("failed to parse address")]
854    ErrAddressParseFailed,
855
856    /// Indicates that non host candidates were selected for a lite agent.
857    #[error("lite agents must only use host candidates")]
858    ErrLiteUsingNonHostCandidates,
859
860    /// Indicates that current ice agent supports Lite only
861    #[error("lite support only")]
862    ErrLiteSupportOnly,
863
864    /// Indicates that one or more URL was provided to the agent but no host candidate required them.
865    #[error("agent does not need URL with selected candidate types")]
866    ErrUselessUrlsProvided,
867
868    /// Indicates that the specified NAT1To1IPCandidateType is unsupported.
869    #[error("unsupported 1:1 NAT IP candidate type")]
870    ErrUnsupportedNat1to1IpCandidateType,
871
872    /// Indicates that the given 1:1 NAT IP mapping is invalid.
873    #[error("invalid 1:1 NAT IP mapping")]
874    ErrInvalidNat1to1IpMapping,
875
876    /// IPNotFound in NAT1To1IPMapping.
877    #[error("external mapped IP not found")]
878    ErrExternalMappedIpNotFound,
879
880    /// Indicates that the mDNS gathering cannot be used along with 1:1 NAT IP mapping for host
881    /// candidate.
882    #[error("mDNS gathering cannot be used with 1:1 NAT IP mapping for host candidate")]
883    ErrMulticastDnsWithNat1to1IpMapping,
884
885    /// Indicates that 1:1 NAT IP mapping for host candidate is requested, but the host candidate
886    /// type is disabled.
887    #[error("1:1 NAT IP mapping for host candidate ineffective")]
888    ErrIneffectiveNat1to1IpMappingHost,
889
890    /// Indicates that 1:1 NAT IP mapping for srflx candidate is requested, but the srflx candidate
891    /// type is disabled.
892    #[error("1:1 NAT IP mapping for srflx candidate ineffective")]
893    ErrIneffectiveNat1to1IpMappingSrflx,
894
895    /// Indicates an invalid MulticastDNSHostName.
896    #[error("invalid mDNS HostName, must end with .local and can only contain a single '.'")]
897    ErrInvalidMulticastDnshostName,
898
899    /// Indicates mdns is not supported.
900    #[error("mdns is not supported")]
901    ErrMulticastDnsNotSupported,
902
903    /// Indicates Restart was called when Agent is in GatheringStateGathering.
904    #[error("ICE Agent can not be restarted when gathering")]
905    ErrRestartWhenGathering,
906
907    /// Indicates a run operation was canceled by its individual done.
908    #[error("run was canceled by done")]
909    ErrRunCanceled,
910
911    /// Initialized Indicates TCPMux is not initialized and that invalidTCPMux is used.
912    #[error("TCPMux is not initialized")]
913    ErrTcpMuxNotInitialized,
914
915    /// Indicates we already have the connection with same remote addr.
916    #[error("conn with same remote addr already exists")]
917    ErrTcpRemoteAddrAlreadyExists,
918
919    /// Failed to send packet.
920    #[error("failed to send packet")]
921    ErrSendPacket,
922    /// Attribute not long enough to be ICE candidate.
923    #[error("attribute not long enough to be ICE candidate")]
924    ErrAttributeTooShortIceCandidate,
925    /// Could not parse component.
926    #[error("could not parse component")]
927    ErrParseComponent,
928    /// Could not parse priority.
929    #[error("could not parse priority")]
930    ErrParsePriority,
931    /// Could not parse port.
932    #[error("could not parse port")]
933    ErrParsePort,
934    /// Could not parse related addresses.
935    #[error("could not parse related addresses")]
936    ErrParseRelatedAddr,
937    /// Could not parse type.
938    #[error("could not parse type")]
939    ErrParseType,
940    /// Unknown candidate type.
941    #[error("unknown candidate type")]
942    ErrUnknownCandidateType,
943    /// Failed to get XOR-MAPPED-ADDRESS response.
944    #[error("failed to get XOR-MAPPED-ADDRESS response")]
945    ErrGetXorMappedAddrResponse,
946    /// Connection with same remote address already exists.
947    #[error("connection with same remote address already exists")]
948    ErrConnectionAddrAlreadyExist,
949    /// Error reading streaming packet.
950    #[error("error reading streaming packet")]
951    ErrReadingStreamingPacket,
952    /// Error writing to.
953    #[error("error writing to")]
954    ErrWriting,
955    /// Error closing connection.
956    #[error("error closing connection")]
957    ErrClosingConnection,
958    /// Unable to determine networkType.
959    #[error("unable to determine networkType")]
960    ErrDetermineNetworkType,
961    /// Missing protocol scheme.
962    #[error("missing protocol scheme")]
963    ErrMissingProtocolScheme,
964    /// Too many colons in address.
965    #[error("too many colons in address")]
966    ErrTooManyColonsAddr,
967    /// Unexpected error trying to read.
968    #[error("unexpected error trying to read")]
969    ErrRead,
970    /// Unknown role.
971    #[error("unknown role")]
972    ErrUnknownRole,
973    /// Username mismatch.
974    #[error("username mismatch")]
975    ErrMismatchUsername,
976    /// The ICE conn can't write STUN messages.
977    #[error("the ICE conn can't write STUN messages")]
978    ErrIceWriteStunMessage,
979    /// URL parse: relative URL without a base.
980    #[error("url parse: relative URL without a base")]
981    ErrUrlParse,
982    /// Candidate IP could not be found.
983    #[error("Candidate IP could not be found")]
984    ErrCandidateIpNotFound,
985
986    // DTLS errors
987    /// Conn is closed.
988    #[error("conn is closed")]
989    ErrConnClosed,
990    /// Read/write timeout.
991    #[error("read/write timeout")]
992    ErrDeadlineExceeded,
993    /// Context is not supported for export_keying_material.
994    #[error("context is not supported for export_keying_material")]
995    ErrContextUnsupported,
996    /// Packet is too short.
997    #[error("packet is too short")]
998    ErrDtlspacketInvalidLength,
999    /// Handshake is in progress.
1000    #[error("handshake is in progress")]
1001    ErrHandshakeInProgress,
1002    /// Invalid content type.
1003    #[error("invalid content type")]
1004    ErrInvalidContentType,
1005    /// Invalid mac.
1006    #[error("invalid mac")]
1007    ErrInvalidMac,
1008    /// Packet length and declared length do not match.
1009    #[error("packet length and declared length do not match")]
1010    ErrInvalidPacketLength,
1011    /// Export_keying_material can not be used with a reserved label.
1012    #[error("export_keying_material can not be used with a reserved label")]
1013    ErrReservedExportKeyingMaterial,
1014    /// Client sent certificate verify but we have no certificate to verify.
1015    #[error("client sent certificate verify but we have no certificate to verify")]
1016    ErrCertificateVerifyNoCertificate,
1017    /// Client+server do not support any shared cipher suites.
1018    #[error("client+server do not support any shared cipher suites")]
1019    ErrCipherSuiteNoIntersection,
1020    /// Server hello can not be created without a cipher suite.
1021    #[error("server hello can not be created without a cipher suite")]
1022    ErrCipherSuiteUnset,
1023    /// Client sent certificate but did not verify it.
1024    #[error("client sent certificate but did not verify it")]
1025    ErrClientCertificateNotVerified,
1026    /// Server required client verification, but got none.
1027    #[error("server required client verification, but got none")]
1028    ErrClientCertificateRequired,
1029    /// Server responded with SRTP Profile we do not support.
1030    #[error("server responded with SRTP Profile we do not support")]
1031    ErrClientNoMatchingSrtpProfile,
1032    /// Client required Extended Master Secret extension, but server does not support it.
1033    #[error("client required Extended Master Secret extension, but server does not support it")]
1034    ErrClientRequiredButNoServerEms,
1035    /// Server hello can not be created without a compression method.
1036    #[error("server hello can not be created without a compression method")]
1037    ErrCompressionMethodUnset,
1038    /// Client+server cookie does not match.
1039    #[error("client+server cookie does not match")]
1040    ErrCookieMismatch,
1041    /// Cookie must not be longer then 255 bytes.
1042    #[error("cookie must not be longer then 255 bytes")]
1043    ErrCookieTooLong,
1044    /// PSK Identity Hint provided but PSK is nil.
1045    #[error("PSK Identity Hint provided but PSK is nil")]
1046    ErrIdentityNoPsk,
1047    /// No certificate provided.
1048    #[error("no certificate provided")]
1049    ErrInvalidCertificate,
1050    /// Cipher spec invalid.
1051    #[error("cipher spec invalid")]
1052    ErrInvalidCipherSpec,
1053    /// Invalid or unknown cipher suite.
1054    #[error("invalid or unknown cipher suite")]
1055    ErrInvalidCipherSuite,
1056    /// Unable to determine if ClientKeyExchange is a public key or PSK Identity.
1057    #[error("unable to determine if ClientKeyExchange is a public key or PSK Identity")]
1058    ErrInvalidClientKeyExchange,
1059    /// Invalid or unknown compression method.
1060    #[error("invalid or unknown compression method")]
1061    ErrInvalidCompressionMethod,
1062    /// ECDSA signature contained zero or negative values.
1063    #[error("ECDSA signature contained zero or negative values")]
1064    ErrInvalidEcdsasignature,
1065    /// Invalid or unknown elliptic curve type.
1066    #[error("invalid or unknown elliptic curve type")]
1067    ErrInvalidEllipticCurveType,
1068    /// Invalid extension type.
1069    #[error("invalid extension type")]
1070    ErrInvalidExtensionType,
1071    /// Invalid hash algorithm.
1072    #[error("invalid hash algorithm")]
1073    ErrInvalidHashAlgorithm,
1074    /// Invalid named curve.
1075    #[error("invalid named curve")]
1076    ErrInvalidNamedCurve,
1077    /// Invalid private key type.
1078    #[error("invalid private key type")]
1079    ErrInvalidPrivateKey,
1080    /// Named curve and private key type does not match.
1081    #[error("named curve and private key type does not match")]
1082    ErrNamedCurveAndPrivateKeyMismatch,
1083    /// Invalid server name format.
1084    #[error("invalid server name format")]
1085    ErrInvalidSniFormat,
1086    /// Invalid signature algorithm.
1087    #[error("invalid signature algorithm")]
1088    ErrInvalidSignatureAlgorithm,
1089    /// Expected and actual key signature do not match.
1090    #[error("expected and actual key signature do not match")]
1091    ErrKeySignatureMismatch,
1092    /// Conn can not be created with a nil nextConn.
1093    #[error("Conn can not be created with a nil nextConn")]
1094    ErrNilNextConn,
1095    /// Connection can not be created, no CipherSuites satisfy this Config.
1096    #[error("connection can not be created, no CipherSuites satisfy this Config")]
1097    ErrNoAvailableCipherSuites,
1098    /// Connection can not be created, no SignatureScheme satisfy this Config.
1099    #[error("connection can not be created, no SignatureScheme satisfy this Config")]
1100    ErrNoAvailableSignatureSchemes,
1101    /// No certificates configured.
1102    #[error("no certificates configured")]
1103    ErrNoCertificates,
1104    /// No config provided.
1105    #[error("no config provided")]
1106    ErrNoConfigProvided,
1107    /// Client requested zero or more elliptic curves that are not supported by the server.
1108    #[error("client requested zero or more elliptic curves that are not supported by the server")]
1109    ErrNoSupportedEllipticCurves,
1110    /// Unsupported protocol version.
1111    #[error("unsupported protocol version")]
1112    ErrUnsupportedProtocolVersion,
1113    /// Certificate and PSK provided.
1114    #[error("Certificate and PSK provided")]
1115    ErrPskAndCertificate,
1116    /// PSK and PSK Identity Hint must both be set for client.
1117    #[error("PSK and PSK Identity Hint must both be set for client")]
1118    ErrPskAndIdentityMustBeSetForClient,
1119    /// SRTP support was requested but server did not respond with use_SRTP extension.
1120    #[error("SRTP support was requested but server did not respond with use_srtp extension")]
1121    ErrRequestedButNoSrtpExtension,
1122    /// Certificate is mandatory for server.
1123    #[error("Certificate is mandatory for server")]
1124    ErrServerMustHaveCertificate,
1125    /// Client requested SRTP but we have no matching profiles.
1126    #[error("client requested SRTP but we have no matching profiles")]
1127    ErrServerNoMatchingSrtpProfile,
1128    /// Server requires the Extended Master Secret extension, but the client does not support it.
1129    #[error(
1130        "server requires the Extended Master Secret extension, but the client does not support it"
1131    )]
1132    ErrServerRequiredButNoClientEms,
1133    /// Expected and actual verify data does not match.
1134    #[error("expected and actual verify data does not match")]
1135    ErrVerifyDataMismatch,
1136    /// Handshake message unset, unable to marshal.
1137    #[error("handshake message unset, unable to marshal")]
1138    ErrHandshakeMessageUnset,
1139    /// Invalid flight number.
1140    #[error("invalid flight number")]
1141    ErrInvalidFlight,
1142    /// Unable to generate key signature, unimplemented.
1143    #[error("unable to generate key signature, unimplemented")]
1144    ErrKeySignatureGenerateUnimplemented,
1145    /// Unable to verify key signature, unimplemented.
1146    #[error("unable to verify key signature, unimplemented")]
1147    ErrKeySignatureVerifyUnimplemented,
1148    /// Data length and declared length do not match.
1149    #[error("data length and declared length do not match")]
1150    ErrLengthMismatch,
1151    /// Buffer not long enough to contain nonce.
1152    #[error("buffer not long enough to contain nonce")]
1153    ErrNotEnoughRoomForNonce,
1154    /// Feature has not been implemented yet.
1155    #[error("feature has not been implemented yet")]
1156    ErrNotImplemented,
1157    /// Sequence number overflow.
1158    #[error("sequence number overflow")]
1159    ErrSequenceNumberOverflow,
1160    /// Unable to marshal fragmented handshakes.
1161    #[error("unable to marshal fragmented handshakes")]
1162    ErrUnableToMarshalFragmented,
1163    /// Invalid state machine transition.
1164    #[error("invalid state machine transition")]
1165    ErrInvalidFsmTransition,
1166    /// ApplicationData with epoch of 0.
1167    #[error("ApplicationData with epoch of 0")]
1168    ErrApplicationDataEpochZero,
1169    /// Unhandled contentType.
1170    #[error("unhandled contentType")]
1171    ErrUnhandledContextType,
1172    /// Context canceled.
1173    #[error("context canceled")]
1174    ErrContextCanceled,
1175    /// Empty fragment.
1176    #[error("empty fragment")]
1177    ErrEmptyFragment,
1178    /// Alert is Fatal or Close Notify.
1179    #[error("Alert is Fatal or Close Notify")]
1180    ErrAlertFatalOrClose,
1181    /// Fragment buffer overflow. New size is greater than specified max.
1182    #[error(
1183        "Fragment buffer overflow. New size {new_size} is greater than specified max {max_size}"
1184    )]
1185    ErrFragmentBufferOverflow {
1186        /// The size the buffer would have grown to.
1187        new_size: usize,
1188        /// The configured maximum.
1189        max_size: usize,
1190    },
1191    /// Client transport is not set yet.
1192    #[error("Client transport is not set yet")]
1193    ErrClientTransportNotSet,
1194
1195    /// The endpoint can no longer create new connections
1196    ///
1197    /// Indicates that a necessary component of the endpoint has been dropped or otherwise disabled.
1198    #[error("endpoint stopping")]
1199    EndpointStopping,
1200    /// The number of active connections on the local endpoint is at the limit
1201    ///
1202    /// Try using longer connection IDs.
1203    #[error("too many connections")]
1204    TooManyConnections,
1205    /// The domain name supplied was malformed
1206    #[error("invalid DNS name: {0}")]
1207    InvalidDnsName(String),
1208    /// The remote [`SocketAddr`] supplied was malformed
1209    ///
1210    /// Examples include attempting to connect to port 0, or using an inappropriate address family.
1211    #[error("invalid remote address: {0}")]
1212    InvalidRemoteAddress(SocketAddr),
1213    /// No client configuration was set up
1214    #[error("no client config")]
1215    NoClientConfig,
1216    /// No server configuration was set up
1217    #[error("no server config")]
1218    NoServerConfig,
1219
1220    //SCTP errors
1221    /// Raw is too small for a SCTP chunk.
1222    #[error("raw is too small for a SCTP chunk")]
1223    ErrChunkHeaderTooSmall,
1224    /// Not enough data left in SCTP packet to satisfy requested length.
1225    #[error("not enough data left in SCTP packet to satisfy requested length")]
1226    ErrChunkHeaderNotEnoughSpace,
1227    /// Chunk PADDING is non-zero at offset.
1228    #[error("chunk PADDING is non-zero at offset")]
1229    ErrChunkHeaderPaddingNonZero,
1230    /// Chunk has invalid length.
1231    #[error("chunk has invalid length")]
1232    ErrChunkHeaderInvalidLength,
1233
1234    /// ChunkType is not of type ABORT.
1235    #[error("ChunkType is not of type ABORT")]
1236    ErrChunkTypeNotAbort,
1237    /// Failed build Abort Chunk.
1238    #[error("failed build Abort Chunk")]
1239    ErrBuildAbortChunkFailed,
1240    /// ChunkType is not of type COOKIEACK.
1241    #[error("ChunkType is not of type COOKIEACK")]
1242    ErrChunkTypeNotCookieAck,
1243    /// ChunkType is not of type COOKIEECHO.
1244    #[error("ChunkType is not of type COOKIEECHO")]
1245    ErrChunkTypeNotCookieEcho,
1246    /// ChunkType is not of type ctError.
1247    #[error("ChunkType is not of type ctError")]
1248    ErrChunkTypeNotCt,
1249    /// Failed build Error Chunk.
1250    #[error("failed build Error Chunk")]
1251    ErrBuildErrorChunkFailed,
1252    /// Failed to marshal stream.
1253    #[error("failed to marshal stream")]
1254    ErrMarshalStreamFailed,
1255    /// Chunk too short.
1256    #[error("chunk too short")]
1257    ErrChunkTooShort,
1258    /// ChunkType is not of type ForwardTsn.
1259    #[error("ChunkType is not of type ForwardTsn")]
1260    ErrChunkTypeNotForwardTsn,
1261    /// ChunkType is not of type HEARTBEAT.
1262    #[error("ChunkType is not of type HEARTBEAT")]
1263    ErrChunkTypeNotHeartbeat,
1264    /// ChunkType is not of type HEARTBEATACK.
1265    #[error("ChunkType is not of type HEARTBEATACK")]
1266    ErrChunkTypeNotHeartbeatAck,
1267    /// Heartbeat is not long enough to contain Heartbeat Info.
1268    #[error("heartbeat is not long enough to contain Heartbeat Info")]
1269    ErrHeartbeatNotLongEnoughInfo,
1270    /// Failed to parse param type.
1271    #[error("failed to parse param type")]
1272    ErrParseParamTypeFailed,
1273    /// Heartbeat should only have HEARTBEAT param.
1274    #[error("heartbeat should only have HEARTBEAT param")]
1275    ErrHeartbeatParam,
1276    /// Failed unmarshalling param in Heartbeat Chunk.
1277    #[error("failed unmarshalling param in Heartbeat Chunk")]
1278    ErrHeartbeatChunkUnmarshal,
1279    /// Unimplemented.
1280    #[error("unimplemented")]
1281    ErrUnimplemented,
1282    /// Heartbeat Ack must have one param.
1283    #[error("heartbeat Ack must have one param")]
1284    ErrHeartbeatAckParams,
1285    /// Heartbeat Ack must have one param, and it should be a HeartbeatInfo.
1286    #[error("heartbeat Ack must have one param, and it should be a HeartbeatInfo")]
1287    ErrHeartbeatAckNotHeartbeatInfo,
1288    /// Unable to marshal parameter for Heartbeat Ack.
1289    #[error("unable to marshal parameter for Heartbeat Ack")]
1290    ErrHeartbeatAckMarshalParam,
1291
1292    /// Raw is too small for error cause.
1293    #[error("raw is too small for error cause")]
1294    ErrErrorCauseTooSmall,
1295
1296    /// Unhandled ParamType.
1297    #[error("unhandled ParamType: {typ}")]
1298    ErrParamTypeUnhandled {
1299        /// The raw parameter type that was not recognised.
1300        typ: u16,
1301    },
1302
1303    /// Unexpected ParamType.
1304    #[error("unexpected ParamType")]
1305    ErrParamTypeUnexpected,
1306
1307    /// Param header too short.
1308    #[error("param header too short")]
1309    ErrParamHeaderTooShort,
1310    /// Param self reported length is shorter than header length.
1311    #[error("param self reported length is shorter than header length")]
1312    ErrParamHeaderSelfReportedLengthShorter,
1313    /// Param self reported length is longer than header length.
1314    #[error("param self reported length is longer than header length")]
1315    ErrParamHeaderSelfReportedLengthLonger,
1316    /// Failed to parse param type.
1317    #[error("failed to parse param type")]
1318    ErrParamHeaderParseFailed,
1319
1320    /// Packet to short.
1321    #[error("packet to short")]
1322    ErrParamPacketTooShort,
1323    /// Outgoing SSN reset request parameter too short.
1324    #[error("outgoing SSN reset request parameter too short")]
1325    ErrSsnResetRequestParamTooShort,
1326    /// Failed unmarshalling SSN reset request parameter in RE-CONFIG chunk.
1327    #[error("failed unmarshalling SSN reset request parameter in RE-CONFIG chunk")]
1328    ErrUnmarshalSsnResetRequestParam,
1329    /// Reconfig response parameter too short.
1330    #[error("reconfig response parameter too short")]
1331    ErrReconfigRespParamTooShort,
1332    /// Failed unmarshalling re-configuration response parameter in RE-CONFIG chunk.
1333    #[error("failed unmarshalling re-configuration response parameter in RE-CONFIG chunk")]
1334    ErrUnmarshalReconfigRespParam,
1335    /// Invalid algorithm type.
1336    #[error("invalid algorithm type")]
1337    ErrInvalidAlgorithmType,
1338
1339    /// Failed to parse param type.
1340    #[error("failed to parse param type")]
1341    ErrInitChunkParseParamTypeFailed,
1342    /// Failed unmarshalling param in Init Chunk.
1343    #[error("failed unmarshalling param in Init Chunk")]
1344    ErrInitChunkUnmarshalParam,
1345    /// Unable to marshal parameter for INIT/INITACK.
1346    #[error("unable to marshal parameter for INIT/INITACK")]
1347    ErrInitAckMarshalParam,
1348
1349    /// ChunkType is not of type INIT.
1350    #[error("ChunkType is not of type INIT")]
1351    ErrChunkTypeNotTypeInit,
1352    /// Chunk Value isn't long enough for mandatory parameters exp.
1353    #[error("chunk Value isn't long enough for mandatory parameters exp")]
1354    ErrChunkValueNotLongEnough,
1355    /// ChunkType of type INIT flags must be all 0.
1356    #[error("ChunkType of type INIT flags must be all 0")]
1357    ErrChunkTypeInitFlagZero,
1358    /// Failed to unmarshal INIT body.
1359    #[error("failed to unmarshal INIT body")]
1360    ErrChunkTypeInitUnmarshalFailed,
1361    /// Failed marshaling INIT common data.
1362    #[error("failed marshaling INIT common data")]
1363    ErrChunkTypeInitMarshalFailed,
1364    /// ChunkType of type INIT ACK InitiateTag must not be 0.
1365    #[error("ChunkType of type INIT ACK InitiateTag must not be 0")]
1366    ErrChunkTypeInitInitiateTagZero,
1367    /// INIT ACK inbound stream request must be > 0.
1368    #[error("INIT ACK inbound stream request must be > 0")]
1369    ErrInitInboundStreamRequestZero,
1370    /// INIT ACK outbound stream request must be > 0.
1371    #[error("INIT ACK outbound stream request must be > 0")]
1372    ErrInitOutboundStreamRequestZero,
1373    /// INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500.
1374    #[error("INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500")]
1375    ErrInitAdvertisedReceiver1500,
1376
1377    /// Packet is smaller than the header size.
1378    #[error("packet is smaller than the header size")]
1379    ErrChunkPayloadSmall,
1380    /// ChunkType is not of type PayloadData.
1381    #[error("ChunkType is not of type PayloadData")]
1382    ErrChunkTypeNotPayloadData,
1383    /// Failed unmarshalling payload data chunk.
1384    #[error("failed unmarshalling payload data chunk")]
1385    ErrChunkUnmarshalPayloadData,
1386    /// ChunkType is not of type Reconfig.
1387    #[error("ChunkType is not of type Reconfig")]
1388    ErrChunkTypeNotReconfig,
1389    /// ChunkReconfig has invalid ParamA.
1390    #[error("ChunkReconfig has invalid ParamA")]
1391    ErrChunkReconfigInvalidParamA,
1392
1393    /// Failed to parse param type.
1394    #[error("failed to parse param type")]
1395    ErrChunkParseParamTypeFailed,
1396    /// Unable to marshal parameter A for reconfig.
1397    #[error("unable to marshal parameter A for reconfig")]
1398    ErrChunkMarshalParamAReconfigFailed,
1399    /// Unable to marshal parameter B for reconfig.
1400    #[error("unable to marshal parameter B for reconfig")]
1401    ErrChunkMarshalParamBReconfigFailed,
1402
1403    /// ChunkType is not of type SACK.
1404    #[error("ChunkType is not of type SACK")]
1405    ErrChunkTypeNotSack,
1406    /// SACK Chunk size is not large enough to contain header.
1407    #[error("SACK Chunk size is not large enough to contain header")]
1408    ErrSackSizeNotLargeEnoughInfo,
1409    /// Failed unmarshalling SACK chunk.
1410    #[error("failed unmarshalling SACK chunk")]
1411    ErrChunkUnmarshalSack,
1412
1413    /// Invalid chunk size.
1414    #[error("invalid chunk size")]
1415    ErrInvalidChunkSize,
1416    /// ChunkType is not of type SHUTDOWN.
1417    #[error("ChunkType is not of type SHUTDOWN")]
1418    ErrChunkTypeNotShutdown,
1419    /// Failed unmarshalling shutdown chunk.
1420    #[error("failed unmarshalling shutdown chunk")]
1421    ErrChunkUnmarshalShutdown,
1422
1423    /// ChunkType is not of type SHUTDOWN-ACK.
1424    #[error("ChunkType is not of type SHUTDOWN-ACK")]
1425    ErrChunkTypeNotShutdownAck,
1426    /// ChunkType is not of type SHUTDOWN-COMPLETE.
1427    #[error("ChunkType is not of type SHUTDOWN-COMPLETE")]
1428    ErrChunkTypeNotShutdownComplete,
1429
1430    /// Raw is smaller than the minimum length for a SCTP packet.
1431    #[error("raw is smaller than the minimum length for a SCTP packet")]
1432    ErrPacketRawTooSmall,
1433    /// Unable to parse SCTP chunk, not enough data for complete header.
1434    #[error("unable to parse SCTP chunk, not enough data for complete header")]
1435    ErrParseSctpChunkNotEnoughData,
1436    /// Failed to unmarshal, contains unknown chunk type.
1437    #[error("failed to unmarshal, contains unknown chunk type")]
1438    ErrUnmarshalUnknownChunkType,
1439    /// Checksum mismatch theirs.
1440    #[error("checksum mismatch theirs")]
1441    ErrChecksumMismatch,
1442
1443    /// Unexpected chunk popped (unordered).
1444    #[error("unexpected chunk popped (unordered)")]
1445    ErrUnexpectedChuckPoppedUnordered,
1446    /// Unexpected chunk popped (ordered).
1447    #[error("unexpected chunk popped (ordered)")]
1448    ErrUnexpectedChuckPoppedOrdered,
1449    /// Unexpected q state (should've been selected).
1450    #[error("unexpected q state (should've been selected)")]
1451    ErrUnexpectedQState,
1452    /// Try again.
1453    #[error("try again")]
1454    ErrTryAgain,
1455
1456    /// Abort chunk, with following errors.
1457    #[error("abort chunk, with following errors: {0}")]
1458    ErrAbortChunk(String),
1459    /// Shutdown called in non-Established state.
1460    #[error("shutdown called in non-Established state")]
1461    ErrShutdownNonEstablished,
1462    /// Association closed before connecting.
1463    #[error("association closed before connecting")]
1464    ErrAssociationClosedBeforeConn,
1465    /// Association init failed.
1466    #[error("association init failed")]
1467    ErrAssociationInitFailed,
1468    /// Association handshake closed.
1469    #[error("association handshake closed")]
1470    ErrAssociationHandshakeClosed,
1471    /// Silently discard.
1472    #[error("silently discard")]
1473    ErrSilentlyDiscard,
1474    /// The init not stored to send.
1475    #[error("the init not stored to send")]
1476    ErrInitNotStoredToSend,
1477    /// CookieEcho not stored to send.
1478    #[error("cookieEcho not stored to send")]
1479    ErrCookieEchoNotStoredToSend,
1480    /// SCTP packet must not have a source port of 0.
1481    #[error("sctp packet must not have a source port of 0")]
1482    ErrSctpPacketSourcePortZero,
1483    /// SCTP packet must not have a destination port of 0.
1484    #[error("sctp packet must not have a destination port of 0")]
1485    ErrSctpPacketDestinationPortZero,
1486    /// Init chunk must not be bundled with any other chunk.
1487    #[error("init chunk must not be bundled with any other chunk")]
1488    ErrInitChunkBundled,
1489    /// Init chunk expects a verification tag of 0 on the packet when out-of-the-blue.
1490    #[error("init chunk expects a verification tag of 0 on the packet when out-of-the-blue")]
1491    ErrInitChunkVerifyTagNotZero,
1492    /// Todo: handle Init when in state.
1493    #[error("todo: handle Init when in state")]
1494    ErrHandleInitState,
1495    /// No cookie in InitAck.
1496    #[error("no cookie in InitAck")]
1497    ErrInitAckNoCookie,
1498    /// There already exists a stream with identifier.
1499    #[error("there already exists a stream with identifier")]
1500    ErrStreamAlreadyExist,
1501    /// Failed to create a stream with identifier.
1502    #[error("Failed to create a stream with identifier")]
1503    ErrStreamCreateFailed,
1504    /// Unable to be popped from inflight queue TSN.
1505    #[error("unable to be popped from inflight queue TSN")]
1506    ErrInflightQueueTsnPop,
1507    /// Requested non-existent TSN.
1508    #[error("requested non-existent TSN")]
1509    ErrTsnRequestNotExist,
1510    /// Sending reset packet in non-Established state.
1511    #[error("sending reset packet in non-Established state")]
1512    ErrResetPacketInStateNotExist,
1513    /// Unexpected parameter type.
1514    #[error("unexpected parameter type")]
1515    ErrParameterType,
1516    /// Sending payload data in non-Established state.
1517    #[error("sending payload data in non-Established state")]
1518    ErrPayloadDataStateNotExist,
1519    /// Unhandled chunk type.
1520    #[error("unhandled chunk type")]
1521    ErrChunkTypeUnhandled,
1522    /// Handshake failed (INIT ACK).
1523    #[error("handshake failed (INIT ACK)")]
1524    ErrHandshakeInitAck,
1525    /// Handshake failed (COOKIE ECHO).
1526    #[error("handshake failed (COOKIE ECHO)")]
1527    ErrHandshakeCookieEcho,
1528
1529    /// Outbound packet larger than maximum message size.
1530    #[error("outbound packet larger than maximum message size")]
1531    ErrOutboundPacketTooLarge,
1532    /// Stream closed.
1533    #[error("Stream closed")]
1534    ErrStreamClosed,
1535    /// Stream not existed.
1536    #[error("Stream not existed")]
1537    ErrStreamNotExisted,
1538    /// Association not existed.
1539    #[error("Association not existed")]
1540    ErrAssociationNotExisted,
1541    /// Transport not existed.
1542    #[error("Transport not existed")]
1543    ErrTransportNoExisted,
1544    /// Io EOF.
1545    #[error("Io EOF")]
1546    ErrEof,
1547    /// Invalid SystemTime.
1548    #[error("Invalid SystemTime")]
1549    ErrInvalidSystemTime,
1550    /// Net Conn read error.
1551    #[error("Net Conn read error")]
1552    ErrNetConnRead,
1553    /// Max Data Channel ID.
1554    #[error("Max Data Channel ID")]
1555    ErrMaxDataChannelID,
1556
1557    //Data Channel
1558    /// DataChannel message is not long enough to determine type: (expected: , actual: ).
1559    #[error(
1560        "DataChannel message is not long enough to determine type: (expected: {expected}, actual: {actual})"
1561    )]
1562    UnexpectedEndOfBuffer {
1563        /// The number of bytes the parser required.
1564        expected: usize,
1565        /// The number of bytes actually available.
1566        actual: usize,
1567    },
1568    /// Unknown MessageType.
1569    #[error("Unknown MessageType {0}")]
1570    InvalidMessageType(u8),
1571    /// Unknown ChannelType.
1572    #[error("Unknown ChannelType {0}")]
1573    InvalidChannelType(u8),
1574    /// Unknown PayloadProtocolIdentifier.
1575    #[error("Unknown PayloadProtocolIdentifier {0}")]
1576    InvalidPayloadProtocolIdentifier(u8),
1577    /// Unknow Protocol.
1578    #[error("Unknow Protocol")]
1579    UnknownProtocol,
1580
1581    //Media
1582    /// Stream is nil.
1583    #[error("stream is nil")]
1584    ErrNilStream,
1585    /// Incomplete frame header.
1586    #[error("incomplete frame header")]
1587    ErrIncompleteFrameHeader,
1588    /// Incomplete frame data.
1589    #[error("incomplete frame data")]
1590    ErrIncompleteFrameData,
1591    /// Incomplete file header.
1592    #[error("incomplete file header")]
1593    ErrIncompleteFileHeader,
1594    /// IVF signature mismatch.
1595    #[error("IVF signature mismatch")]
1596    ErrSignatureMismatch,
1597    /// IVF version unknown, parser may not parse correctly.
1598    #[error("IVF version unknown, parser may not parse correctly")]
1599    ErrUnknownIVFVersion,
1600
1601    /// File not opened.
1602    #[error("file not opened")]
1603    ErrFileNotOpened,
1604    /// Invalid nil packet.
1605    #[error("invalid nil packet")]
1606    ErrInvalidNilPacket,
1607
1608    /// Bad header signature.
1609    #[error("bad header signature")]
1610    ErrBadIDPageSignature,
1611    /// Wrong header, expected beginning of stream.
1612    #[error("wrong header, expected beginning of stream")]
1613    ErrBadIDPageType,
1614    /// Payload for id page must be 19 bytes.
1615    #[error("payload for id page must be 19 bytes")]
1616    ErrBadIDPageLength,
1617    /// Bad payload signature.
1618    #[error("bad payload signature")]
1619    ErrBadIDPagePayloadSignature,
1620    /// Not enough data for payload header.
1621    #[error("not enough data for payload header")]
1622    ErrShortPageHeader,
1623    /// Bad OpusTags signature.
1624    #[error("bad OpusTags signature")]
1625    ErrBadOpusTagsSignature,
1626    /// Unsupported channel mapping family.
1627    #[error("unsupported channel mapping family")]
1628    ErrUnsupportedChannelMappingFamily,
1629
1630    /// Data is not a H264 bitstream.
1631    #[error("data is not a H264 bitstream")]
1632    ErrDataIsNotH264Stream,
1633    /// Data is not a H265 bitstream.
1634    #[error("data is not a H265 bitstream")]
1635    ErrDataIsNotH265Stream,
1636    /// Io EOF.
1637    #[error("Io EOF")]
1638    ErrIoEOF,
1639
1640    // mDNS
1641    /// MDNS: port not support, only 5353 is supported.
1642    #[error("mDNS: port not support, only 5353 is supported")]
1643    ErrMDNSPortNotSupported,
1644    /// MDNS: connection is closed.
1645    #[error("mDNS: connection is closed")]
1646    ErrMDNSConnectionClosed,
1647    /// MDNS: query not found.
1648    #[error("mDNS: query not found")]
1649    ErrMDNSQueryNotFound,
1650    /// MDNS: parsing/packing of this type isn't available yet.
1651    #[error("mDNS: parsing/packing of this type isn't available yet")]
1652    ErrNotStarted,
1653    /// MDNS: parsing/packing of this section has completed.
1654    #[error("mDNS: parsing/packing of this section has completed")]
1655    ErrSectionDone,
1656    /// MDNS: parsing/packing of this section is header.
1657    #[error("mDNS: parsing/packing of this section is header")]
1658    ErrSectionHeader,
1659    /// MDNS: insufficient data for base length type.
1660    #[error("mDNS: insufficient data for base length type")]
1661    ErrBaseLen,
1662    /// MDNS: insufficient data for calculated length type.
1663    #[error("mDNS: insufficient data for calculated length type")]
1664    ErrCalcLen,
1665    /// MDNS: segment prefix is reserved.
1666    #[error("mDNS: segment prefix is reserved")]
1667    ErrReserved,
1668    /// MDNS: too many pointers (>10).
1669    #[error("mDNS: too many pointers (>10)")]
1670    ErrTooManyPtr,
1671    /// MDNS: invalid pointer.
1672    #[error("mDNS: invalid pointer")]
1673    ErrInvalidPtr,
1674    /// MDNS: nil resource body.
1675    #[error("mDNS: nil resource body")]
1676    ErrNilResourceBody,
1677    /// MDNS: insufficient data for resource body length.
1678    #[error("mDNS: insufficient data for resource body length")]
1679    ErrResourceLen,
1680    /// MDNS: segment length too long.
1681    #[error("mDNS: segment length too long")]
1682    ErrSegTooLong,
1683    /// MDNS: zero length segment.
1684    #[error("mDNS: zero length segment")]
1685    ErrZeroSegLen,
1686    /// MDNS: resource length too long.
1687    #[error("mDNS: resource length too long")]
1688    ErrResTooLong,
1689    /// MDNS: too many Questions to pack (>65535).
1690    #[error("mDNS: too many Questions to pack (>65535)")]
1691    ErrTooManyQuestions,
1692    /// MDNS: too many Answers to pack (>65535).
1693    #[error("mDNS: too many Answers to pack (>65535)")]
1694    ErrTooManyAnswers,
1695    /// MDNS: too many Authorities to pack (>65535).
1696    #[error("mDNS: too many Authorities to pack (>65535)")]
1697    ErrTooManyAuthorities,
1698    /// MDNS: too many Additionals to pack (>65535).
1699    #[error("mDNS: too many Additionals to pack (>65535)")]
1700    ErrTooManyAdditionals,
1701    /// MDNS: name is not in canonical format (it must end with a .).
1702    #[error("mDNS: name is not in canonical format (it must end with a .)")]
1703    ErrNonCanonicalName,
1704    /// MDNS: character string exceeds maximum length (255).
1705    #[error("mDNS: character string exceeds maximum length (255)")]
1706    ErrStringTooLong,
1707    /// MDNS: compressed name in SRV resource data.
1708    #[error("mDNS: compressed name in SRV resource data")]
1709    ErrCompressedSrv,
1710    /// MDNS: empty builder msg.
1711    #[error("mDNS: empty builder msg")]
1712    ErrEmptyBuilderMsg,
1713
1714    //RTC
1715    /// ErrConnectionClosed indicates an operation executed after connection
1716    /// has already been closed.
1717    #[error("connection closed")]
1718    ErrConnectionClosed,
1719
1720    /// ErrDataChannelClosed indicates an operation executed when the data
1721    /// channel is not (yet) open or closed.
1722    #[error("data channel closed")]
1723    ErrDataChannelClosed,
1724
1725    /// ErrDataChannelNotOpen indicates a send was attempted on a data channel
1726    /// whose underlying SCTP stream has not been established yet — its
1727    /// `ready_state` is still `connecting`. Wait for the channel to open.
1728    #[error("data channel is not open yet")]
1729    ErrDataChannelNotOpen,
1730
1731    /// ErrDataChannelNonExist indicates an operation executed when the data
1732    /// channel not existed.
1733    #[error("data channel not existed")]
1734    ErrDataChannelNotExisted,
1735
1736    /// ErrSendBufferFull indicates that a data-channel send was rejected because
1737    /// the channel's outstanding send buffer exceeded the configured hard ceiling
1738    /// (back-pressure). Retry after the buffer drains (e.g. on OnBufferedAmountLow).
1739    #[error("data channel send buffer full")]
1740    ErrSendBufferFull,
1741
1742    /// ErrCertificateExpired indicates that an x509 certificate has expired.
1743    #[error("x509Cert expired")]
1744    ErrCertificateExpired,
1745
1746    /// ErrNoTurnCredentials indicates that a TURN server URL was provided
1747    /// without required credentials.
1748    #[error("turn server credentials required")]
1749    ErrNoTurnCredentials,
1750
1751    /// ErrTurnCredentials indicates that provided TURN credentials are partial
1752    /// or malformed.
1753    #[error("invalid turn server credentials")]
1754    ErrTurnCredentials,
1755
1756    /// ErrExistingTrack indicates that a track already exists.
1757    #[error("track already exists")]
1758    ErrExistingTrack,
1759
1760    /// ErrExistingTrack indicates that a track already exists.
1761    #[error("track not existed")]
1762    ErrTrackNotExisted,
1763
1764    /// ErrPrivateKeyType indicates that a particular private key encryption
1765    /// chosen to generate a certificate is not supported.
1766    #[error("private key type not supported")]
1767    ErrPrivateKeyType,
1768
1769    /// ErrModifyingPeerIdentity indicates that an attempt to modify
1770    /// PeerIdentity was made after PeerConnection has been initialized.
1771    #[error("peerIdentity cannot be modified")]
1772    ErrModifyingPeerIdentity,
1773
1774    /// ErrModifyingCertificates indicates that an attempt to modify
1775    /// Certificates was made after PeerConnection has been initialized.
1776    #[error("certificates cannot be modified")]
1777    ErrModifyingCertificates,
1778
1779    /// ErrNonCertificate indicates that there is no certificate
1780    #[error("no certificate")]
1781    ErrNonCertificate,
1782
1783    /// ErrModifyingBundlePolicy indicates that an attempt to modify
1784    /// BundlePolicy was made after PeerConnection has been initialized.
1785    #[error("bundle policy cannot be modified")]
1786    ErrModifyingBundlePolicy,
1787
1788    /// ErrModifyingRTCPMuxPolicy indicates that an attempt to modify
1789    /// RTCPMuxPolicy was made after PeerConnection has been initialized.
1790    #[error("rtcp mux policy cannot be modified")]
1791    ErrModifyingRTCPMuxPolicy,
1792
1793    /// ErrModifyingICECandidatePoolSize indicates that an attempt to modify
1794    /// ICECandidatePoolSize was made after PeerConnection has been initialized.
1795    #[error("ice candidate pool size cannot be modified")]
1796    ErrModifyingICECandidatePoolSize,
1797
1798    /// ErrStringSizeLimit indicates that the character size limit of string is
1799    /// exceeded. The limit is hardcoded to 65535 according to specifications.
1800    #[error("data channel label exceeds size limit")]
1801    ErrStringSizeLimit,
1802
1803    /// ErrNegotiatedWithoutID indicates that an attempt to create a data channel
1804    /// was made while setting the negotiated option to true without providing
1805    /// the negotiated channel ID.
1806    #[error("negotiated set without channel id")]
1807    ErrNegotiatedWithoutID,
1808
1809    /// ErrRetransmitsOrPacketLifeTime indicates that an attempt to create a data
1810    /// channel was made with both options max_packet_life_time and max_retransmits
1811    /// set together. Such configuration is not supported by the specification
1812    /// and is mutually exclusive.
1813    #[error("both max_packet_life_time and max_retransmits was set")]
1814    ErrRetransmitsOrPacketLifeTime,
1815
1816    /// ErrCodecNotFound is returned when a codec search to the Media Engine fails
1817    #[error("codec not found")]
1818    ErrCodecNotFound,
1819
1820    /// ErrNoRemoteDescription indicates that an operation was rejected because
1821    /// the remote description is not set
1822    #[error("remote description is not set")]
1823    ErrNoRemoteDescription,
1824
1825    /// ErrIncorrectSDPSemantics indicates that the PeerConnection was configured to
1826    /// generate SDP Answers with different SDP Semantics than the received Offer
1827    #[error("offer SDP semantics does not match configuration")]
1828    ErrIncorrectSDPSemantics,
1829
1830    /// ErrIncorrectSignalingState indicates that the signaling state of PeerConnection is not correct
1831    #[error("operation can not be run in current signaling state")]
1832    ErrIncorrectSignalingState,
1833
1834    /// ErrProtocolTooLarge indicates that value given for a DataChannelInit protocol is
1835    /// longer then 65535 bytes
1836    #[error("protocol is larger then 65535 bytes")]
1837    ErrProtocolTooLarge,
1838
1839    /// ErrSenderNotCreatedByConnection indicates remove_track was called with a RtpSender not created
1840    /// by this PeerConnection
1841    #[error("RtpSender not created by this PeerConnection")]
1842    ErrSenderNotCreatedByConnection,
1843
1844    /// ErrSenderInitialTrackIdAlreadySet indicates a second call to
1845    /// RtpSender::set_initial_track_id which is not allowed.
1846    #[error("RtpSender's initial_track_id has already been set")]
1847    ErrSenderInitialTrackIdAlreadySet,
1848
1849    /// ErrSessionDescriptionNoFingerprint indicates set_remote_description was called with a SessionDescription that has no
1850    /// fingerprint
1851    #[error("set_remote_description called with no fingerprint")]
1852    ErrSessionDescriptionNoFingerprint,
1853
1854    /// ErrSessionDescriptionInvalidFingerprint indicates set_remote_description was called with a SessionDescription that
1855    /// has an invalid fingerprint
1856    #[error("set_remote_description called with an invalid fingerprint")]
1857    ErrSessionDescriptionInvalidFingerprint,
1858
1859    /// ErrSessionDescriptionConflictingFingerprints indicates set_remote_description was called with a SessionDescription that
1860    /// has an conflicting fingerprints
1861    #[error("set_remote_description called with multiple conflicting fingerprint")]
1862    ErrSessionDescriptionConflictingFingerprints,
1863
1864    /// ErrSessionDescriptionMissingIceUfrag indicates set_remote_description was called with a SessionDescription that
1865    /// is missing an ice-ufrag value
1866    #[error("set_remote_description called with no ice-ufrag")]
1867    ErrSessionDescriptionMissingIceUfrag,
1868
1869    /// ErrSessionDescriptionMissingIcePwd indicates set_remote_description was called with a SessionDescription that
1870    /// is missing an ice-pwd value
1871    #[error("set_remote_description called with no ice-pwd")]
1872    ErrSessionDescriptionMissingIcePwd,
1873
1874    /// ErrSessionDescriptionConflictingIceUfrag  indicates set_remote_description was called with a SessionDescription that
1875    /// contains multiple conflicting ice-ufrag values
1876    #[error("set_remote_description called with multiple conflicting ice-ufrag values")]
1877    ErrSessionDescriptionConflictingIceUfrag,
1878
1879    /// ErrSessionDescriptionConflictingIcePwd indicates set_remote_description was called with a SessionDescription that
1880    /// contains multiple conflicting ice-pwd values
1881    #[error("set_remote_description called with multiple conflicting ice-pwd values")]
1882    ErrSessionDescriptionConflictingIcePwd,
1883
1884    /// ErrNoSRTPProtectionProfile indicates that the DTLS handshake completed and no SRTP Protection Profile was chosen
1885    #[error("DTLS Handshake completed and no SRTP Protection Profile was chosen")]
1886    ErrNoSRTPProtectionProfile,
1887
1888    /// ErrFailedToGenerateCertificateFingerprint indicates that we failed to generate the fingerprint used for comparing certificates
1889    #[error("failed to generate certificate fingerprint")]
1890    ErrFailedToGenerateCertificateFingerprint,
1891
1892    /// ErrNoCodecsAvailable indicates that operation isn't possible because the MediaEngine has no codecs available
1893    #[error("operation failed no codecs are available")]
1894    ErrNoCodecsAvailable,
1895
1896    /// ErrUnsupportedCodec indicates the remote peer doesn't support the requested codec
1897    #[error("unable to start track, codec is not supported by remote")]
1898    ErrUnsupportedCodec,
1899
1900    /// Invalid state error.
1901    #[error("Invalid state error")]
1902    InvalidStateError,
1903
1904    /// Invalid modification error.
1905    #[error("Invalid modification error")]
1906    InvalidModificationError,
1907
1908    /// Range error.
1909    #[error("Range error {0}")]
1910    RangeError(String),
1911
1912    /// ErrSenderWithNoCodecs indicates that a RTPSender was created without any codecs. To send media the MediaEngine needs at
1913    /// least one configured codec.
1914    #[error("unable to populate media section, RTPSender created with no codecs")]
1915    ErrSenderWithNoCodecs,
1916
1917    /// ErrSenderWithNoSSRCs indicates that a RTPSender was created without any SSRRs. To send media the Sender needs at
1918    /// least one configured ssrc.
1919    #[error("unable to populate media section, RTPSender created with no ssrcs")]
1920    ErrSenderWithNoSSRCs,
1921
1922    /// ErrRTPSenderNewTrackHasIncorrectKind indicates that the new track is of a different kind than the previous/original
1923    #[error("new track must be of the same kind as previous")]
1924    ErrRTPSenderNewTrackHasIncorrectKind,
1925
1926    /// New track has incorrect envelope.
1927    #[error("new track has incorrect envelope")]
1928    ErrRTPSenderNewTrackHasIncorrectEnvelope,
1929
1930    /// ErrRTPSenderDataSent indicates that the sequence number transformer tries to be enabled after the data sending began
1931    #[error("Sequence number transformer must be enabled before sending data")]
1932    ErrRTPSenderDataSent,
1933
1934    /// ErrRTPSenderSeqTransEnabled indicates that the sequence number transformer has been already enabled
1935    #[error("Sequence number transformer has been already enabled")]
1936    ErrRTPSenderSeqTransEnabled,
1937
1938    /// ErrUnbindFailed indicates that a TrackLocal was not able to be unbind
1939    #[error("failed to unbind TrackLocal from PeerConnection")]
1940    ErrUnbindFailed,
1941
1942    /// ErrNoPayloaderForCodec indicates that the requested codec does not have a payloader
1943    #[error("the requested codec does not have a payloader")]
1944    ErrNoPayloaderForCodec,
1945
1946    /// ErrRegisterHeaderExtensionInvalidDirection indicates that a extension was registered with different
1947    /// directions for two different calls.
1948    #[error("a header extension must be registered with the same direction each time")]
1949    ErrRegisterHeaderExtensionInvalidDirection,
1950
1951    /// Invalid direction.
1952    #[error("invalid direction")]
1953    ErrInvalidDirection,
1954
1955    /// ErrRegisterHeaderExtensionNoFreeID indicates that there was no extension ID available which
1956    /// in turn means that all 15 available id(1 through 14) have been used.
1957    #[error(
1958        "no header extension ID was free to use(this means the maximum of 15 extensions have been registered)"
1959    )]
1960    ErrRegisterHeaderExtensionNoFreeID,
1961
1962    /// ErrSimulcastProbeOverflow indicates that too many Simulcast probe streams are in flight and the requested SSRC was ignored
1963    #[error("simulcast probe limit has been reached, new SSRC has been discarded")]
1964    ErrSimulcastProbeOverflow,
1965
1966    /// Enable detaching by calling webrtc.DetachDataChannels.
1967    #[error("enable detaching by calling webrtc.DetachDataChannels()")]
1968    ErrDetachNotEnabled,
1969    /// Datachannel not opened yet, try calling Detach from OnOpen.
1970    #[error("datachannel not opened yet, try calling Detach from OnOpen")]
1971    ErrDetachBeforeOpened,
1972    /// The DTLS transport has not started yet.
1973    #[error("the DTLS transport has not started yet")]
1974    ErrDtlsTransportNotStarted,
1975    /// Failed extracting keys from DTLS for SRTP.
1976    #[error("failed extracting keys from DTLS for SRTP")]
1977    ErrDtlsKeyExtractionFailed,
1978    /// Failed to start SRTP.
1979    #[error("failed to start SRTP")]
1980    ErrFailedToStartSRTP,
1981    /// Failed to start SRTCP.
1982    #[error("failed to start SRTCP")]
1983    ErrFailedToStartSRTCP,
1984    /// Attempted to start DTLSTransport that is not in new state.
1985    #[error("attempted to start DTLSTransport that is not in new state")]
1986    ErrInvalidDTLSStart,
1987    /// Peer didn't provide certificate via DTLS.
1988    #[error("peer didn't provide certificate via DTLS")]
1989    ErrNoRemoteCertificate,
1990    /// Identity provider is not implemented.
1991    #[error("identity provider is not implemented")]
1992    ErrIdentityProviderNotImplemented,
1993    /// Remote certificate does not match any fingerprint.
1994    #[error("remote certificate does not match any fingerprint")]
1995    ErrNoMatchingCertificateFingerprint,
1996    /// Unsupported fingerprint algorithm.
1997    #[error("unsupported fingerprint algorithm")]
1998    ErrUnsupportedFingerprintAlgorithm,
1999    /// ICE connection not started.
2000    #[error("ICE connection not started")]
2001    ErrICEConnectionNotStarted,
2002    /// Unknown candidate type.
2003    #[error("unknown candidate type")]
2004    ErrICECandidateTypeUnknown,
2005    /// Cannot convert ICE.CandidateType into webrtc.ICECandidateType, invalid type.
2006    #[error("cannot convert ice.CandidateType into webrtc.ICECandidateType, invalid type")]
2007    ErrICEInvalidConvertCandidateType,
2008    /// ICEAgent does not exist.
2009    #[error("ICEAgent does not exist")]
2010    ErrICEAgentNotExist,
2011    /// Unable to convert ICE candidates to ICECandidates.
2012    #[error("unable to convert ICE candidates to ICECandidates")]
2013    ErrICECandidatesConversionFailed,
2014    /// Unknown ICE Role.
2015    #[error("unknown ICE Role")]
2016    ErrICERoleUnknown,
2017    /// Unknown protocol.
2018    #[error("unknown protocol")]
2019    ErrICEProtocolUnknown,
2020    /// Gatherer not started.
2021    #[error("gatherer not started")]
2022    ErrICEGathererNotStarted,
2023    /// Unknown network type.
2024    #[error("unknown network type")]
2025    ErrNetworkTypeUnknown,
2026    /// New SDP does not match previous offer.
2027    #[error("new sdp does not match previous offer")]
2028    ErrSDPDoesNotMatchOffer,
2029    /// New SDP does not match previous answer.
2030    #[error("new sdp does not match previous answer")]
2031    ErrSDPDoesNotMatchAnswer,
2032    /// Provided value is not a valid enum value of type SDPType.
2033    #[error("provided value is not a valid enum value of type SDPType")]
2034    ErrPeerConnSDPTypeInvalidValue,
2035    /// Invalid state change op.
2036    #[error("invalid state change op")]
2037    ErrPeerConnStateChangeInvalid,
2038    /// Unhandled state change op.
2039    #[error("unhandled state change op")]
2040    ErrPeerConnStateChangeUnhandled,
2041    /// Invalid SDP type supplied to SetLocalDescription.
2042    #[error("invalid SDP type supplied to SetLocalDescription()")]
2043    ErrPeerConnSDPTypeInvalidValueSetLocalDescription,
2044    /// RemoteDescription contained media section without mid value.
2045    #[error("remoteDescription contained media section without mid value")]
2046    ErrPeerConnRemoteDescriptionWithoutMidValue,
2047    /// LocalDescription contained media section without mid value.
2048    #[error("localDescription contained media section without mid value")]
2049    ErrPeerConnLocalDescriptionWithoutMidValue,
2050    /// RemoteDescription has not been set yet.
2051    #[error("remoteDescription has not been set yet")]
2052    ErrPeerConnRemoteDescriptionNil,
2053    /// LocalDescription has not been set yet.
2054    #[error("localDescription has not been set yet")]
2055    ErrPeerConnLocalDescriptionNil,
2056    /// Single media section has an explicit SSRC.
2057    #[error("single media section has an explicit SSRC")]
2058    ErrPeerConnSingleMediaSectionHasExplicitSSRC,
2059    /// Could not add transceiver for remote SSRC.
2060    #[error("could not add transceiver for remote SSRC")]
2061    ErrPeerConnRemoteSSRCAddTransceiver,
2062    /// Mid RTP Extensions required for Simulcast.
2063    #[error("mid RTP Extensions required for Simulcast")]
2064    ErrPeerConnSimulcastMidRTPExtensionRequired,
2065    /// Stream id RTP Extensions required for Simulcast.
2066    #[error("stream id RTP Extensions required for Simulcast")]
2067    ErrPeerConnSimulcastStreamIDRTPExtensionRequired,
2068    /// Incoming SSRC failed Simulcast probing.
2069    #[error("incoming SSRC failed Simulcast probing")]
2070    ErrPeerConnSimulcastIncomingSSRCFailed,
2071    /// Failed collecting stats.
2072    #[error("failed collecting stats")]
2073    ErrPeerConnStatsCollectionFailed,
2074    /// Add_transceiver_from_kind only accepts one RTPTransceiverInit.
2075    #[error("add_transceiver_from_kind only accepts one RTPTransceiverInit")]
2076    ErrPeerConnAddTransceiverFromKindOnlyAcceptsOne,
2077    /// Add_transceiver_from_track only accepts one RTPTransceiverInit.
2078    #[error("add_transceiver_from_track only accepts one RTPTransceiverInit")]
2079    ErrPeerConnAddTransceiverFromTrackOnlyAcceptsOne,
2080    /// Add_transceiver_from_kind currently only supports recvonly.
2081    #[error("add_transceiver_from_kind currently only supports recvonly")]
2082    ErrPeerConnAddTransceiverFromKindSupport,
2083    /// Add_transceiver_from_track currently only supports sendonly and sendrecv.
2084    #[error("add_transceiver_from_track currently only supports sendonly and sendrecv")]
2085    ErrPeerConnAddTransceiverFromTrackSupport,
2086    /// TODO set_identity_provider.
2087    #[error("TODO set_identity_provider")]
2088    ErrPeerConnSetIdentityProviderNotImplemented,
2089    /// Write_RTCP failed to open write_stream.
2090    #[error("write_rtcp failed to open write_stream")]
2091    ErrPeerConnWriteRTCPOpenWriteStream,
2092    /// Cannot find transceiver with mid.
2093    #[error("cannot find transceiver with mid")]
2094    ErrPeerConnTransceiverMidNil,
2095    /// DTLSTransport must not be nil.
2096    #[error("DTLSTransport must not be nil")]
2097    ErrRTPReceiverDTLSTransportNil,
2098    /// Receive has already been called.
2099    #[error("Receive has already been called")]
2100    ErrRTPReceiverReceiveAlreadyCalled,
2101    /// Unable to find stream for Track with SSRC.
2102    #[error("unable to find stream for Track with SSRC")]
2103    ErrRTPReceiverWithSSRCTrackStreamNotFound,
2104    /// No trackStreams found for SSRC.
2105    #[error("no trackStreams found for SSRC")]
2106    ErrRTPReceiverForSSRCTrackStreamNotFound,
2107    /// No trackStreams found for RID.
2108    #[error("no trackStreams found for RID")]
2109    ErrRTPReceiverForRIDTrackStreamNotFound,
2110    /// Invalid RTP Receiver transition.
2111    #[error("invalid RTP Receiver transition")]
2112    ErrRTPReceiverStateChangeInvalid,
2113    /// Track must not be nil.
2114    #[error("Track must not be nil")]
2115    ErrRTPSenderTrackNil,
2116    /// RTPSender not existed.
2117    #[error("RTPSender not existed")]
2118    ErrRTPSenderNotExisted,
2119    /// Sender Track has been removed or replaced to nil.
2120    #[error("Sender Track has been removed or replaced to nil")]
2121    ErrRTPSenderTrackRemoved,
2122    /// Sender cannot add encoding as rid is empty.
2123    #[error("Sender cannot add encoding as rid is empty")]
2124    ErrRTPSenderRidNil,
2125    /// Sender cannot add encoding as there is no base track.
2126    #[error("Sender cannot add encoding as there is no base track")]
2127    ErrRTPSenderNoBaseEncoding,
2128    /// Sender cannot add encoding as provided track does not match base track.
2129    #[error("Sender cannot add encoding as provided track does not match base track")]
2130    ErrRTPSenderBaseEncodingMismatch,
2131    /// Sender cannot encoding due to RID collision.
2132    #[error("Sender cannot encoding due to RID collision")]
2133    ErrRTPSenderRIDCollision,
2134    /// Sender does not have track for RID.
2135    #[error("Sender does not have track for RID")]
2136    ErrRTPSenderNoTrackForRID,
2137    /// RTPReceiver not existed.
2138    #[error("RTPReceiver not existed")]
2139    ErrRTPReceiverNotExisted,
2140    /// DTLSTransport must not be nil.
2141    #[error("DTLSTransport must not be nil")]
2142    ErrRTPSenderDTLSTransportNil,
2143    /// Send has already been called.
2144    #[error("Send has already been called")]
2145    ErrRTPSenderSendAlreadyCalled,
2146    /// RTPTransceiver not existed.
2147    #[error("RTPTransceiver not existed")]
2148    ErrRTPTransceiverNotExisted,
2149    /// ErrRTPSenderTrackNil.
2150    #[error("errRTPSenderTrackNil")]
2151    ErrRTPTransceiverCannotChangeMid,
2152    /// Invalid state change in RTPTransceiver.setSending.
2153    #[error("invalid state change in RTPTransceiver.setSending")]
2154    ErrRTPTransceiverSetSendingInvalidState,
2155    /// Unsupported codec type by this transceiver.
2156    #[error("unsupported codec type by this transceiver")]
2157    ErrRTPTransceiverCodecUnsupported,
2158    /// DTLS not established.
2159    #[error("DTLS not established")]
2160    ErrSCTPTransportDTLS,
2161    /// Add_transceiver_SDP called with 0 transceivers.
2162    #[error("add_transceiver_sdp() called with 0 transceivers")]
2163    ErrSDPZeroTransceivers,
2164    /// Invalid Media Section. Media + DataChannel both enabled.
2165    #[error("invalid Media Section. Media + DataChannel both enabled")]
2166    ErrSDPMediaSectionMediaDataChanInvalid,
2167    /// Invalid Media Section Track Index.
2168    #[error("invalid Media Section Track Index")]
2169    ErrSDPMediaSectionTrackInvalid,
2170    /// Set_answering_dtlsrole must DTLSRoleClient or DTLSRoleServer.
2171    #[error("set_answering_dtlsrole must DTLSRoleClient or DTLSRoleServer")]
2172    ErrSettingEngineSetAnsweringDTLSRole,
2173    /// Can't rollback from stable state.
2174    #[error("can't rollback from stable state")]
2175    ErrSignalingStateCannotRollback,
2176    /// Invalid proposed signaling state transition.
2177    #[error("invalid proposed signaling state transition: {0}")]
2178    ErrSignalingStateProposedTransitionInvalid(String),
2179    /// Cannot convert to StatsICECandidatePairStateSucceeded invalid ICE candidate state.
2180    #[error("cannot convert to StatsICECandidatePairStateSucceeded invalid ice candidate state")]
2181    ErrStatsICECandidateStateInvalid,
2182    /// ICETransport can only be called in ICETransportStateNew.
2183    #[error("ICETransport can only be called in ICETransportStateNew")]
2184    ErrICETransportNotInNew,
2185    /// Bad Certificate PEM format.
2186    #[error("bad Certificate PEM format")]
2187    ErrCertificatePEMFormatError,
2188    /// SCTP is not established.
2189    #[error("SCTP is not established")]
2190    ErrSCTPNotEstablished,
2191
2192    /// DataChannel is not opened.
2193    #[error("DataChannel is not opened")]
2194    ErrClosedPipe,
2195    /// Interceptor is not bind.
2196    #[error("Interceptor is not bind")]
2197    ErrInterceptorNotBind,
2198    /// Excessive retries in CreateOffer.
2199    #[error("excessive retries in CreateOffer")]
2200    ErrExcessiveRetries,
2201
2202    /// Not long enough to be a RTP Packet.
2203    #[error("not long enough to be a RTP Packet")]
2204    ErrRTPTooShort,
2205
2206    /// SyntaxIdDirSplit indicates rid-syntax could not be parsed.
2207    #[error("RFC8851 mandates rid-syntax        = %s\"a=rid:\" rid-id SP rid-dir")]
2208    SimulcastRidParseErrorSyntaxIdDirSplit,
2209    /// UnknownDirection indicates rid-dir was not parsed. Should be "send" or "recv".
2210    #[error("RFC8851 mandates rid-dir           = %s\"send\" / %s\"recv\"")]
2211    SimulcastRidParseErrorUnknownDirection,
2212
2213    //SDP
2214    /// Codec not found.
2215    #[error("codec not found")]
2216    CodecNotFound,
2217    /// Missing whitespace.
2218    #[error("missing whitespace")]
2219    MissingWhitespace,
2220    /// Missing colon.
2221    #[error("missing colon")]
2222    MissingColon,
2223    /// Payload type not found.
2224    #[error("payload type not found")]
2225    PayloadTypeNotFound,
2226    /// SdpInvalidSyntax.
2227    #[error("SdpInvalidSyntax: {0}")]
2228    SdpInvalidSyntax(String),
2229    /// SdpInvalidValue.
2230    #[error("SdpInvalidValue: {0}")]
2231    SdpInvalidValue(String),
2232    /// SDP: empty time_descriptions.
2233    #[error("sdp: empty time_descriptions")]
2234    SdpEmptyTimeDescription,
2235    /// Parse extmap.
2236    #[error("parse extmap: {0}")]
2237    ParseExtMap(String),
2238    /// A syntax error at a known offset in the input, rendered with the offending character marked.
2239    #[error("{} --> {} <-- {}", .s.substring(0,*.p), .s.substring(*.p, *.p+1), .s.substring(*.p+1, .s.len())
2240    )]
2241    SyntaxError {
2242        /// The input being parsed.
2243        s: String,
2244        /// The byte offset of the offending character in `s`.
2245        p: usize,
2246    },
2247
2248    //Third Party Error
2249    /// An error from the `sec1` crate while handling EC key encodings.
2250    #[error("{0}")]
2251    Sec1(#[source] sec1::Error),
2252    /// An error from the `p256` crate during NIST P-256 elliptic-curve operations.
2253    #[error("{0}")]
2254    P256(#[source] P256Error),
2255    /// An error from the `rcgen` crate while generating a self-signed certificate.
2256    #[error("{0}")]
2257    RcGen(#[from] rcgen::Error),
2258    /// Invalid PEM.
2259    #[error("invalid PEM: {0}")]
2260    InvalidPEM(String),
2261    /// AES GCM.
2262    #[error("aes gcm: {0}")]
2263    AesGcm(#[from] aes_gcm::Error),
2264    /// Parse ip.
2265    #[error("parse ip: {0}")]
2266    ParseIp(#[from] net::AddrParseError),
2267    /// Parse int.
2268    #[error("parse int: {0}")]
2269    ParseInt(#[from] ParseIntError),
2270    /// An underlying I/O error.
2271    #[error("{0}")]
2272    Io(#[source] IoError),
2273    /// URL parse.
2274    #[error("url parse: {0}")]
2275    Url(#[from] url::ParseError),
2276    /// UTF-8.
2277    #[error("utf8: {0}")]
2278    Utf8(#[from] FromUtf8Error),
2279    /// An error from the standard library or another boxed source.
2280    #[error("{0}")]
2281    Std(#[source] StdError),
2282    /// An error from the `aes` crate during block-cipher setup.
2283    #[error("{0}")]
2284    Aes(#[from] aes::cipher::InvalidLength),
2285
2286    //Other Errors
2287    /// Other RTCP Err.
2288    #[error("Other RTCP Err: {0}")]
2289    OtherRtcpErr(String),
2290    /// Other RTP Err.
2291    #[error("Other RTP Err: {0}")]
2292    OtherRtpErr(String),
2293    /// Other SRTP Err.
2294    #[error("Other SRTP Err: {0}")]
2295    OtherSrtpErr(String),
2296    /// Other STUN Err.
2297    #[error("Other STUN Err: {0}")]
2298    OtherStunErr(String),
2299    /// Other TURN Err.
2300    #[error("Other TURN Err: {0}")]
2301    OtherTurnErr(String),
2302    /// Other ICE Err.
2303    #[error("Other ICE Err: {0}")]
2304    OtherIceErr(String),
2305    /// Other DTLS Err.
2306    #[error("Other DTLS Err: {0}")]
2307    OtherDtlsErr(String),
2308    /// Other SCTP Err.
2309    #[error("Other SCTP Err: {0}")]
2310    OtherSctpErr(String),
2311    /// Other DataChannel Err.
2312    #[error("Other DataChannel Err: {0}")]
2313    OtherDataChannelErr(String),
2314    /// Other Interceptor Err.
2315    #[error("Other Interceptor Err: {0}")]
2316    OtherInterceptorErr(String),
2317    /// Other Media Err.
2318    #[error("Other Media Err: {0}")]
2319    OtherMediaErr(String),
2320    /// Other mDNS Err.
2321    #[error("Other mDNS Err: {0}")]
2322    OtherMdnsErr(String),
2323    /// Other SDP Err.
2324    #[error("Other SDP Err: {0}")]
2325    OtherSdpErr(String),
2326    /// Other PeerConnection Err.
2327    #[error("Other PeerConnection Err: {0}")]
2328    OtherPeerConnectionErr(String),
2329    #[error("{0}")]
2330    /// An error that does not fit any other variant, carrying a description.
2331    Other(String),
2332}
2333
2334impl Error {
2335    /// Wraps any `std::error::Error` implementation as [`Error::Std`],
2336    /// preserving the original error and its stack trace.
2337    pub fn from_std<T>(error: T) -> Self
2338    where
2339        T: std::error::Error + Send + Sync + 'static,
2340    {
2341        Error::Std(StdError(Box::new(error)))
2342    }
2343
2344    /// Attempts to downcast an [`Error::Std`] variant to a concrete error type.
2345    ///
2346    /// Returns `None` if this error is not `Error::Std` or if the inner error
2347    /// is not of type `T`.
2348    pub fn downcast_ref<T: std::error::Error + 'static>(&self) -> Option<&T> {
2349        if let Error::Std(s) = self {
2350            return s.0.downcast_ref();
2351        }
2352
2353        None
2354    }
2355}
2356
2357/// Wrapper around [`std::io::Error`] that implements [`PartialEq`].
2358///
2359/// `io::Error` does not implement `PartialEq`, which is required by the
2360/// top-level [`enum@Error`] enum. This newtype delegates equality to
2361/// [`io::ErrorKind`], so two `IoError` values are equal when their kinds match.
2362#[derive(Debug, Error)]
2363#[error("io error: {0}")]
2364pub struct IoError(#[from] pub io::Error);
2365
2366// Workaround for wanting PartialEq for io::Error.
2367impl PartialEq for IoError {
2368    fn eq(&self, other: &Self) -> bool {
2369        self.0.kind() == other.0.kind()
2370    }
2371}
2372
2373impl From<io::Error> for Error {
2374    fn from(e: io::Error) -> Self {
2375        Error::Io(IoError(e))
2376    }
2377}
2378
2379/// An escape hatch to preserve stack traces for errors whose concrete type is unknown.
2380///
2381/// Some traits exported by this crate (e.g. `Conn`, `Listener`) return `Error`.
2382/// When those traits are used in higher-level crates that have their own error
2383/// types, callers are forced to handle foreign errors. `StdError` boxes any
2384/// `std::error::Error` implementation and wraps it in `Error::Std`, preserving
2385/// the original error's message and — where supported — its stack trace.
2386///
2387/// Use [`Error::from_std`] to construct this variant.
2388#[derive(Debug, Error)]
2389#[error("{0}")]
2390pub struct StdError(pub Box<dyn std::error::Error + Send + Sync>);
2391
2392impl PartialEq for StdError {
2393    fn eq(&self, _: &Self) -> bool {
2394        false
2395    }
2396}
2397
2398impl<T> From<std::sync::PoisonError<T>> for Error {
2399    fn from(e: std::sync::PoisonError<T>) -> Self {
2400        Error::PoisonError(e.to_string())
2401    }
2402}
2403
2404impl From<sec1::Error> for Error {
2405    fn from(e: sec1::Error) -> Self {
2406        Error::Sec1(e)
2407    }
2408}
2409
2410/// Wrapper around [`p256::elliptic_curve::Error`] that implements [`PartialEq`].
2411///
2412/// `p256::elliptic_curve::Error` does not implement `PartialEq`, which is
2413/// required by the top-level [`enum@Error`] enum. This newtype always returns
2414/// `false` for equality comparisons, which is the safe conservative choice
2415/// for opaque cryptographic errors.
2416#[derive(Debug, Error)]
2417#[error("{0}")]
2418pub struct P256Error(#[source] p256::elliptic_curve::Error);
2419
2420impl PartialEq for P256Error {
2421    fn eq(&self, _: &Self) -> bool {
2422        false
2423    }
2424}
2425
2426impl From<p256::elliptic_curve::Error> for Error {
2427    fn from(e: p256::elliptic_curve::Error) -> Self {
2428        Error::P256(P256Error(e))
2429    }
2430}
2431
2432impl From<SystemTimeError> for Error {
2433    fn from(e: SystemTimeError) -> Self {
2434        Error::Other(e.to_string())
2435    }
2436}
2437
2438/// Flattens a list of errors into a single [`enum@Error`], joining their messages with newlines.
2439///
2440/// Returns `Ok(())` if `errs` is empty.
2441pub fn flatten_errs(errs: Vec<impl Into<Error>>) -> Result<()> {
2442    if errs.is_empty() {
2443        Ok(())
2444    } else {
2445        let errs_strs: Vec<String> = errs.into_iter().map(|e| e.into().to_string()).collect();
2446        Err(Error::Other(errs_strs.join("\n")))
2447    }
2448}