Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

86.0 KB
Raw Blame
// Adapted from Serein (https://github.com/ViceVerse-cz/Serein) at commit a0e72cc,
// file `crates/discord-voice/src/transport.rs` (function `run_inner` and helpers).
// Copyright (c) 2026 Serein contributors. Licensed under MIT OR Apache-2.0; RustCord's
// modifications are under the same terms. See crates/voice/NOTICE.md.
//
// RustCord changes: no camera or diagnostics (Go Live runs on its own connection in
// stream.rs and only its audio is mixed here, see stream_mix.rs), per-user
// speaking/roster/ping events, a voice-chat Opus bitrate, tolerant endpoint parsing, named
// close codes and ignored unknown text opcodes. Beyond Serein: close codes below 4000 resume
// like 4015, a failed (re)connect is retried with backoff, and UDP discovery probes repeat.
// Signaling order, DAVE handling, resume and fail-closed rules otherwise follow Serein.
//! Voice gateway v8, UDP discovery and keepalive, `rtpsize` transport encryption, DAVE
//! frame encryption, Opus encode/decode and the 20 ms media clock of one call.
use crate::{
    Frame,
    crypto::{
        Dave, Encryption, Identity, MAX_PACKET, MAX_PARTICIPANTS, MAX_SIGNAL, MODE,
        OPUS_PAYLOAD_TYPE, rtp_header,
    },
    stream_mix::StreamMix,
};
use futures_util::{SinkExt, StreamExt};
use opus2::{Application, Bitrate, Channels, Encoder, SoftClip};
use serde_json::{Value, json};
use std::{
    net::{IpAddr, SocketAddr},
    sync::{
        Arc,
        mpsc::{Receiver, SyncSender},
    },
    time::Duration,
};
use tokio::{
    net::{TcpStream, UdpSocket},
    sync::watch,
    time::{Instant, MissedTickBehavior, timeout},
};
use tokio_tungstenite::{
    Connector, MaybeTlsStream, WebSocketStream,
    tungstenite::{Message, protocol::WebSocketConfig},
};
use zeroize::Zeroizing;

pub(crate) type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
/// Time a sole member gives the roster announcement before waiting for a peer.
pub(crate) const PEER_GRACE: Duration = Duration::from_millis(500);
/// IP discovery probes repeat this often until the reply arrives (one lost datagram must
/// not fail the join).
pub(crate) const DISCOVERY_RETRY: Duration = Duration::from_secs(1);
/// Waits before each further attempt to open the voice WebSocket, initially or to resume:
/// a network blip (Wi-Fi roam, DNS hiccup) must not end the call, while the total stays
/// within the time Discord keeps a voice session resumable.
const RECONNECT_BACKOFF: [Duration; 3] = if cfg!(test) {
    [Duration::from_millis(10); 3]
} else {
    [
        Duration::from_millis(500),
        Duration::from_secs(2),
        Duration::from_secs(5),
    ]
};
/// Each WebSocket open attempt (TCP, TLS and upgrade) gets this long.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// Outgoing Opus bitrate until the caller sets the channel's (`Controls::bitrate`).
/// Discord's default voice channel bitrate is 64 kbit/s.
pub(crate) const OPUS_BITRATE: i32 = 64_000;
/// The range a voice channel's bitrate can take (8 kbit/s up to a level 3 server's 384).
pub(crate) const OPUS_BITRATES: std::ops::RangeInclusive<i32> = 8_000..=384_000;
/// Silence frames sent after speech so receivers' decoders fade out instead of clicking.
const TRAILING_SILENCE_FRAMES: u8 = 5;

/// The voice server ended this device's session on purpose (close 4014); rejoining
/// automatically is wrong.
pub(crate) const DISCONNECTED_BY_DISCORD: &str = "Discord disconnected this device from the call";

/// Live controls read by the media loop every 20 ms tick.
#[derive(Clone, Copy)]
pub(crate) struct Controls {
    pub muted: bool,
    pub deafened: bool,
    /// Playback percentages (0..=200) per user; zero user IDs are unused slots.
    pub user_volumes: [(u64, u16); 64],
    /// Outgoing Opus bitrate (bit/s): the voice channel's.
    pub bitrate: i32,
}
impl Default for Controls {
    fn default() -> Self {
        Self {
            muted: false,
            deafened: false,
            user_volumes: [(0, 100); 64],
            bitrate: OPUS_BITRATE,
        }
    }
}

/// Voice-scoped credentials. The session ID and token are zeroized when dropped.
pub(crate) struct Credentials {
    pub user: u64,
    /// Identify/Resume `server_id`: the guild ID, or the channel ID for DM calls.
    pub server: u64,
    /// DAVE MLS group ID: always the voice channel ID.
    pub channel: u64,
    pub session: Zeroizing<String>,
    pub token: Zeroizing<String>,
}

/// Internal progress and media events of one call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Status {
    Connecting,
    Discovering,
    Securing,
    /// Joined and secured, but alone: nobody to share media keys with yet.
    WaitingForPeer,
    /// DAVE is ready; audio flows both ways.
    Ready,
    /// First decoded remote audio of this call.
    RemoteAudio,
    Speaking {
        user: u64,
        speaking: bool,
    },
    UserJoined(u64),
    UserLeft(u64),
    Ping(u32),
}

pub(crate) fn negotiation_timeout(
    hello: bool,
    transport: bool,
    key: bool,
    dave: &Dave,
    resuming: bool,
) -> &'static str {
    if resuming {
        "Discord voice resume acknowledgement timed out; rejoin the call"
    } else if !hello {
        "Discord voice Hello timed out; rejoin the call"
    } else if !transport {
        "Discord voice Ready timed out; rejoin the call"
    } else if !key {
        "Discord voice protocol selection timed out; no transport key was received"
    } else if dave.session.is_ready() && dave.transitioning() {
        "Discord DAVE transition execution timed out; no audio was enabled"
    } else {
        "Discord DAVE group negotiation timed out; no accepted commit or welcome was received"
    }
}

/// Turn the `endpoint` of VOICE_SERVER_UPDATE into the voice WebSocket URL.
///
/// Discord sends `host:port` (e.g. `c-ams05-1a2b3c4d.discord.media:443`), sometimes without
/// the port; stream servers append a numeric stream ID to the host. A `wss://` scheme and
/// a trailing slash are tolerated. Only Discord media hosts are accepted so the voice token
/// is never sent elsewhere.
pub(crate) fn endpoint(raw: &str) -> Result<String, &'static str> {
    let raw = raw.trim();
    let raw = raw.strip_prefix("wss://").unwrap_or(raw);
    let raw = raw.strip_suffix('/').unwrap_or(raw);
    if raw.is_empty() {
        return Err("Missing Discord voice endpoint");
    }
    if raw.len() > 256
        || raw.contains('@')
        || raw.contains('?')
        || raw.contains('#')
    {
        return Err("Invalid Discord voice endpoint");
    }
    if let Some((_, path)) = raw.split_once('/') {
        if path.is_empty() || path.len() > 24 || !path.bytes().all(|c| c.is_ascii_digit()) {
            return Err("Invalid Discord voice endpoint");
        }
    }
    let mut url = url::Url::parse(&format!("wss://{raw}"))
        .map_err(|_| "Invalid Discord voice endpoint")?;
    let host = url.host_str().ok_or("Missing Discord voice host")?;
    if !host.ends_with(".discord.media") || url.username() != "" || url.password().is_some() {
        return Err("Voice endpoint is outside Discord media");
    }
    url.set_query(Some("v=8"));
    Ok(url.into())
}
pub(crate) fn public_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ip) => {
            !ip.is_private()
                && !ip.is_loopback()
                && !ip.is_link_local()
                && !ip.is_broadcast()
                && !ip.is_multicast()
                && !ip.is_unspecified()
                && !ip.is_documentation()
                && ip.octets()[0] != 0
                && ip.octets()[0] < 240
                && !(ip.octets()[0] == 100 && (64..128).contains(&ip.octets()[1]))
        }
        IpAddr::V6(ip) => {
            !ip.is_loopback()
                && !ip.is_unspecified()
                && !ip.is_multicast()
                && !ip.is_unique_local()
                && !ip.is_unicast_link_local()
                && ip.to_ipv4_mapped().is_none()
                && !(ip.segments()[0] == 0x2001 && ip.segments()[1] == 0xdb8)
        }
    }
}

// ---- Voice gateway messages -------------------------------------------------------

/// Opcode 0 Identify. `video: false` and no streams: this client is audio only.
fn identify(credentials: &Credentials) -> Value {
    json!({"op":0,"d":{
        "server_id":credentials.server.to_string(),
        "user_id":credentials.user.to_string(),
        "session_id":credentials.session.as_str(),
        "token":credentials.token.as_str(),
        // RustCord: one video stream is asked for, so the camera has SSRCs when it is turned on.
        "video":true,
        "streams":[{"type":"video","rid":"100","quality":100}],
        "max_dave_protocol_version":1,
    }})
}
/// Opcode 7 Resume with the last sequence number received.
fn resume(credentials: &Credentials, seq_ack: i64) -> Value {
    json!({"op":7,"d":{
        "server_id":credentials.server.to_string(),
        "session_id":credentials.session.as_str(),
        "token":credentials.token.as_str(),
        "seq_ack":seq_ack,
    }})
}
/// Opcode 3 Heartbeat (v8 carries `seq_ack`).
fn heartbeat(nonce: u64, seq_ack: i64) -> Value {
    json!({"op":3,"d":{"t":nonce,"seq_ack":seq_ack}})
}
/// Opcode 1 Select Protocol with RustCord's discovered external address.
/// RustCord: the camera's H.264 beside Opus (send only; the payload types match Go Live's).
fn call_codecs() -> Value {
    json!([
        {"name":"opus","type":"audio","priority":1000,"payload_type":120},
        {"name":"H264","type":"video","priority":1000,"payload_type":101,"rtx_payload_type":102,"encode":true,"decode":true},
    ])
}

/// RustCord: other people's cameras. The video SSRCs an announcement (opcode 12) gives
/// its user: `None` when it says nothing about video, an empty list when the camera is off.
fn camera_sources(data: &Value) -> Option<Vec<(u32, Option<u32>)>> {
    let ssrc = |value: &Value| value.as_u64().and_then(|v| u32::try_from(v).ok()).filter(|v| *v != 0);
    let streams = data.get("streams").and_then(Value::as_array);
    let primary = data.get("video_ssrc");
    if streams.is_none() && primary.is_none() {
        return None;
    }
    let mut sources = Vec::with_capacity(4);
    // (A camera that is off keeps its stream entry, marked inactive, or reports SSRC 0.)
    if primary.and_then(Value::as_u64) != Some(0) {
        for stream in streams.into_iter().flatten().take(4) {
            if (stream.get("type").is_none() || stream["type"] == "video")
                && stream.get("active").and_then(Value::as_bool) != Some(false)
                && let Some(value) = ssrc(&stream["ssrc"])
            {
                sources.push((value, ssrc(&stream["rtx_ssrc"])));
            }
        }
        if streams.is_none() && let Some(value) = primary.and_then(ssrc) {
            sources.push((value, ssrc(&data["rtx_ssrc"])));
        }
    }
    Some(sources)
}

/// Every picture that is complete: decrypted (DAVE) and handed to its sender's decoder.
/// Anything that cannot be decoded waits for that sender's next keyframe.
fn decode_cameras(
    receivers: &mut crate::video_receive::Receivers,
    dave: &mut Dave,
    decoders: &std::collections::HashMap<u64, (crate::video_receive::DecoderQueue, crate::video_receive::Lost)>,
    mut first: Option<crate::video_receive::Received>,
) {
    while let Some(received) = first.take().or_else(|| receivers.pop_timed()) {
        let user = received.user;
        let Some(frame) = crate::stream::decrypt_video(receivers, dave, user, &received.data) else { continue };
        let queued = decoders.get(&user).is_some_and(|(queue, _)| matches!(crate::video_receive::offer(queue, frame), Ok(true)));
        if !queued {
            receivers.require_keyframe(user);
        }
    }
}

/// One authenticated video packet of someone's camera.
fn receive_camera(
    rtp: crate::crypto::Rtp,
    receivers: &mut crate::video_receive::Receivers,
    dave: &mut Dave,
    decoders: &std::collections::HashMap<u64, (crate::video_receive::DecoderQueue, crate::video_receive::Lost)>,
    reports: &mut crate::video_feedback::ReceiveReports,
) {
    // Authenticated network probes never reach media decoding.
    if !dave.ready || rtp.payload_type == crate::crypto::PROBE_PAYLOAD_TYPE {
        return;
    }
    let Some(rtp) = crate::stream::stream_video_packet(receivers, rtp) else { return };
    if !receivers.has_source(rtp.ssrc) {
        return;
    }
    reports.receive(rtp.ssrc, rtp.sequence, rtp.timestamp, std::time::Instant::now());
    let first = receivers.push_timed(rtp.ssrc, rtp.sequence, rtp.timestamp, rtp.marker, &rtp.payload);
    decode_cameras(receivers, dave, decoders, first);
}

/// Stop the camera's media at once: nothing queued may cross an encryption change.
fn invalidate_camera(video: &mut crate::screen::Video) {
    use std::sync::atomic::Ordering;
    video.ready.store(false, Ordering::Release);
    video.keyframe.store(true, Ordering::Release);
    while video.frames.try_recv().is_ok() {}
}

/// Viewers' reports about your camera: loss and bandwidth steer the bitrate, missing
/// packets are resent, and a lost picture asks the encoder for a keyframe.
fn camera_feedback(
    feedback: crate::crypto::Feedback,
    video: &crate::screen::Video,
    rate: &mut crate::video::Rate,
    history: &mut crate::video::History,
    rtx_ssrc: u32,
    next_keyframe: &mut Instant,
) {
    let now = Instant::now();
    rate.observe(feedback.loss, feedback.bitrate);
    let missing = if rtx_ssrc != 0 { history.request(&feedback.nacks, now) } else { !feedback.nacks.is_empty() };
    if feedback.keyframe || missing {
        video.stats.keyframe_request();
    }
    if (feedback.keyframe || missing) && now >= *next_keyframe {
        video.keyframe.store(true, std::sync::atomic::Ordering::Release);
        *next_keyframe = now + Duration::from_millis(500);
    }
}

fn select_protocol(address: IpAddr, port: u16) -> Value {
    json!({"op":1,"d":{
        "protocol":"udp",
        "data":{"address":address.to_string(),"port":port,"mode":MODE},
        "codecs":call_codecs(),
    }})
}
/// Opcode 5 Speaking; flag 1 is the microphone.
fn speaking(on: bool, ssrc: u32) -> Value {
    json!({"op":5,"d":{"speaking":u8::from(on),"delay":0,"ssrc":ssrc}})
}
/// Opcode 23 Ready For Transition.
fn ready_for_transition(id: u16) -> Value {
    json!({"op":23,"d":{"transition_id":id}})
}
/// Opcode 31 Invalid Commit/Welcome.
fn invalid_commit_welcome(id: u16) -> Value {
    json!({"op":31,"d":{"transition_id":id}})
}

fn websocket_config() -> WebSocketConfig {
    WebSocketConfig::default()
        .max_message_size(Some(MAX_SIGNAL))
        .max_frame_size(Some(MAX_SIGNAL))
        .write_buffer_size(0)
        .max_write_buffer_size(MAX_SIGNAL * 2)
}
/// TLS with normal certificate validation against the Mozilla roots and an explicit ring
/// provider, so the connection never depends on a process-wide rustls default (none is
/// installed in RustCord, and two enabled providers would make the default ambiguous).
pub(crate) fn tls_connector() -> Result<Connector, &'static str> {
    let mut roots = rustls::RootCertStore::empty();
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    let config = rustls::ClientConfig::builder_with_provider(Arc::new(
        rustls::crypto::ring::default_provider(),
    ))
    .with_safe_default_protocol_versions()
    .map_err(|_| "Voice TLS configuration failed")?
    .with_root_certificates(roots)
    .with_no_client_auth();
    Ok(Connector::Rustls(Arc::new(config)))
}
/// See [`crate::set_user_agent`].
pub(crate) static USER_AGENT: std::sync::OnceLock<String> = std::sync::OnceLock::new();

/// Open the voice WebSocket (`wss://` in production; tests use loopback `ws://`).
pub(crate) async fn open_socket(
    url: &str,
    tls: &Connector,
) -> Result<Socket, tokio_tungstenite::tungstenite::Error> {
    use tokio_tungstenite::tungstenite::client::IntoClientRequest;
    use tokio_tungstenite::tungstenite::http::HeaderValue;
    let mut request = url.into_client_request()?;
    if let Some(ua) = USER_AGENT.get().and_then(|ua| HeaderValue::from_str(ua).ok()) {
        let headers = request.headers_mut();
        headers.insert("user-agent", ua);
        headers.insert("origin", HeaderValue::from_static("https://discord.com"));
    }
    tokio_tungstenite::connect_async_tls_with_config(
        request,
        Some(websocket_config()),
        false,
        Some(tls.clone()),
    )
    .await
    .map(|(socket, _)| socket)
}
/// Open the voice WebSocket, retrying with backoff: a refused, reset or timed-out attempt
/// is often a momentary network change. `failed`/`timed_out` name the final outcome.
async fn connect(
    url: &str,
    tls: &Connector,
    failed: &'static str,
    timed_out: &'static str,
) -> Result<Socket, &'static str> {
    let mut outcome = failed;
    for wait in std::iter::once(Duration::ZERO).chain(RECONNECT_BACKOFF) {
        tokio::time::sleep(wait).await;
        match timeout(CONNECT_TIMEOUT, open_socket(url, tls)).await {
            Ok(Ok(socket)) => return Ok(socket),
            Ok(Err(_)) => outcome = failed,
            Err(_) => outcome = timed_out,
        }
    }
    Err(outcome)
}
pub(crate) async fn send(ws: &mut Socket, message: Message) -> Result<(), &'static str> {
    timeout(Duration::from_secs(5), ws.send(message))
        .await
        .map_err(|_| "Voice signaling write timed out")?
        .map_err(|_| "Voice signaling disconnected")
}
pub(crate) async fn json_send(ws: &mut Socket, value: Value) -> Result<(), &'static str> {
    send(ws, Message::Text(value.to_string().into())).await
}

/// Media datagrams are lossy by design. A full send buffer, a network roam or a stray
/// ICMP unreachable (which Windows reports on the next send of a connected socket) drops
/// one packet; only a path that keeps failing for `UDP_OUTAGE` ends the call.
/// Never wait for socket capacity here: that would stall audio and signaling.
const UDP_OUTAGE: Duration = Duration::from_secs(10);
#[derive(Default)]
pub(crate) struct UdpFailures(Option<Instant>);
impl UdpFailures {
    pub(crate) fn send(
        &mut self,
        socket: &UdpSocket,
        data: &[u8],
        outage: &'static str,
    ) -> Result<(), &'static str> {
        if socket.try_send(data).is_ok() {
            self.0 = None;
            return Ok(());
        }
        let now = Instant::now();
        if now.duration_since(*self.0.get_or_insert(now)) >= UDP_OUTAGE {
            return Err(outage);
        }
        Ok(())
    }
}
/// Receive errors that describe one lost or rejected datagram rather than a dead socket.
pub(crate) fn transient_receive(error: &std::io::Error) -> bool {
    // WSAEMSGSIZE: Windows fails an oversized datagram instead of truncating it.
    const WSAEMSGSIZE: i32 = 10040;
    matches!(
        error.kind(),
        std::io::ErrorKind::ConnectionReset
            | std::io::ErrorKind::ConnectionRefused
            | std::io::ErrorKind::Interrupted
    ) || (cfg!(windows) && error.raw_os_error() == Some(WSAEMSGSIZE))
}
// Native voice UDP ping: signaling heartbeats alone do not maintain an idle
// media path (notably a muted call).
pub(crate) fn udp_keepalive(
    socket: &UdpSocket,
    failures: &mut UdpFailures,
    sequence: &mut u32,
) -> Result<(), &'static str> {
    *sequence = sequence.wrapping_add(1);
    let mut packet = [0x13, 0x37, 0xca, 0xfe, 0, 0, 0, 0];
    packet[4..].copy_from_slice(&sequence.to_le_bytes());
    failures.send(socket, &packet, "Voice UDP keepalive failed")
}
pub(crate) fn number(data: &Value, key: &str) -> Result<u64, &'static str> {
    data[key].as_u64().ok_or("Malformed voice signaling field")
}
pub(crate) fn id(data: &Value, key: &str) -> Result<u64, &'static str> {
    data[key]
        .as_str()
        .and_then(|v| v.parse().ok())
        .filter(|v| *v != 0)
        .ok_or("Malformed voice participant")
}
pub(crate) fn transition(data: &Value) -> Result<u16, &'static str> {
    u16::try_from(number(data, "transition_id")?).map_err(|_| "Invalid voice transition")
}
/// The 74-byte IP discovery request (type 1, length 70, RustCord's SSRC, zeroed address/port).
pub(crate) fn discovery_request(ssrc: u32) -> [u8; 74] {
    let mut probe = [0; 74];
    probe[..4].copy_from_slice(&[0, 1, 0, 70]);
    probe[4..8].copy_from_slice(&ssrc.to_be_bytes());
    probe
}
/// Parse the IP discovery response: RustCord's external address and port as the server sees them.
pub(crate) fn discovery(packet: &[u8], ssrc: u32) -> Result<(IpAddr, u16), &'static str> {
    if packet.len() != 74 || packet[..4] != [0, 2, 0, 70] || packet[4..8] != ssrc.to_be_bytes() {
        return Err("Invalid voice UDP discovery reply");
    }
    let end = packet[8..72]
        .iter()
        .position(|b| *b == 0)
        .ok_or("Invalid voice discovery address")?;
    let address = std::str::from_utf8(&packet[8..8 + end])
        .map_err(|_| "Invalid voice discovery address")?
        .parse()
        .map_err(|_| "Invalid voice discovery address")?;
    let port = u16::from_be_bytes([packet[72], packet[73]]);
    if port == 0 {
        return Err("Invalid voice discovery port");
    }
    Ok((address, port))
}
/// Whether a heartbeat acknowledgement names the latest outstanding nonce or one of the
/// `missed` heartbeats sent before it; a late acknowledgement still proves liveness.
/// Others are stale duplicates of an already answered heartbeat and are ignored.
pub(crate) fn acknowledges(awaiting: Option<u64>, missed: u8, nonce: Option<u64>) -> bool {
    awaiting
        .zip(nonce)
        .is_some_and(|(latest, nonce)| latest.wrapping_sub(nonce) <= u64::from(missed))
}
/// Close codes after which the voice session survives and Discord expects a resume: 4015
/// (voice server crashed) and every code outside the voice range (1000-3999: server
/// restarts, drains and abnormal closures), as discord.js does.
fn resumable_close(code: u16) -> bool {
    code == 4015 || code < 4000
}
/// Terminal voice WebSocket close codes, named for the `Disconnected` reason.
fn close_reason(code: u16) -> &'static str {
    match code {
        4014 => DISCONNECTED_BY_DISCORD,
        4001 => "Discord voice rejected an unknown opcode (4001)",
        4002 => "Discord voice failed to decode a payload (4002)",
        4003 => "Discord voice: not authenticated (4003)",
        4004 => "Discord voice authentication failed; the voice token is invalid (4004)",
        4005 => "Discord voice: already authenticated (4005)",
        4006 => "Discord voice session is no longer valid; rejoin the call (4006)",
        4009 => "Discord voice session timed out; rejoin the call (4009)",
        4011 => "Discord voice server not found; rejoin the call (4011)",
        4012 => "Discord voice: unknown protocol (4012)",
        4016 => "Discord voice: unknown encryption mode (4016)",
        4017 => "Discord voice requires DAVE end-to-end encryption (4017)",
        4020 => "Discord voice rejected a malformed request (4020)",
        4021 => "Discord voice disconnected this device: rate limited (4021)",
        4022 => "Discord voice call was terminated (4022)",
        _ => "Discord voice connection closed; rejoin the call",
    }
}
/// Changes between the previous and current set of speaking users, in order.
fn speaking_changes(previous: &[u64], current: &[u64]) -> Vec<(u64, bool)> {
    previous
        .iter()
        .filter(|user| !current.contains(user))
        .map(|user| (*user, false))
        .chain(
            current
                .iter()
                .filter(|user| !previous.contains(user))
                .map(|user| (*user, true)),
        )
        .collect()
}

/// Outgoing Opus: 48 kHz, 20 ms, stereo (dual-mono from the microphone), full band.
fn opus_encoder() -> Result<Encoder, &'static str> {
    let mut encoder = Encoder::new(48_000, Channels::Stereo, Application::Audio)
        .map_err(|_| "Opus encoder initialization failed")?;
    encoder
        .set_bitrate(Bitrate::Bits(OPUS_BITRATE))
        .map_err(|_| "Opus bitrate configuration failed")?;
    // Capture is 32-bit float; the source carries at least 24 significant bits.
    encoder
        .set_lsb_depth(24)
        .map_err(|_| "Opus LSB depth configuration failed")?;
    encoder
        .set_complexity(10)
        .map_err(|_| "Opus complexity configuration failed")?;
    encoder
        .set_signal(opus2::Signal::Voice)
        .map_err(|_| "Opus signal configuration failed")?;
    encoder
        .set_force_channels(Some(Channels::Stereo))
        .map_err(|_| "Opus stereo configuration failed")?;
    encoder
        .set_max_bandwidth(opus2::Bandwidth::Fullband)
        .map_err(|_| "Opus bandwidth configuration failed")?;
    // Silence is handled by the capture gate and explicit silence frames, not DTX.
    encoder
        .set_dtx(false)
        .map_err(|_| "Opus DTX configuration failed")?;
    Ok(encoder)
}

/// A gap between media ticks from which the call starts over instead of catching up.
const STALL: Duration = Duration::from_millis(300);

/// One datagram from the voice server: authenticate, decrypt (transport, then DAVE) and
/// queue its Opus for the speaker it belongs to. Anything else is dropped.
fn receive_audio(
    packet: &[u8],
    length: usize,
    crypto: &Encryption,
    dave: &mut Dave,
    mixer: &mut crate::mixer::Mixer,
    deafened: bool,
    // RustCord: arrivals are noted for the sender's bandwidth estimate while cameras are watched.
    arrivals: Option<&mut crate::transport_feedback::TransportFeedback>,
) -> Option<crate::crypto::Rtp> {
    if length > MAX_PACKET {
        return None;
    }
    let rtp = crypto.open(&packet[..length])?;
    if let (Some(arrivals), Some(sequence)) = (arrivals, rtp.transport_sequence) {
        arrivals.receive(sequence, std::time::Instant::now());
    }
    // Anything that is not Opus (camera video, its retransmissions, probes) goes back to
    // the caller.
    if rtp.payload_type != OPUS_PAYLOAD_TYPE {
        return Some(rtp);
    }
    let user = mixer.user(rtp.ssrc)?;
    if !dave.ready || !dave.contains(user) || deafened {
        return None;
    }
    let opus = dave.session.decrypt(user, davey::MediaType::AUDIO, &rtp.payload).ok()?;
    crate::health::count(&crate::health::PACKETS);
    mixer.push(rtp.ssrc, rtp.sequence, opus);
    None
}

/// Resolves once the controls sender is dropped, i.e. the call was asked to stop.
pub(crate) async fn stopped(controls: &mut watch::Receiver<Controls>) {
    while controls.changed().await.is_ok() {}
}

/// Run one call until the controls sender is dropped (`Ok`) or the call fails (`Err`).
///
/// `capture` delivers gated 20 ms mono 48 kHz microphone frames (at most eight queued);
/// `playback` receives the mixed 20 ms mono frames, including watched Go Live audio from
/// `streams`. `identity` is the call's DAVE signing identity, shared with its streams.
/// No audio device opens here. `allow_loopback` admits a loopback media address in unit
/// tests only.
#[allow(clippy::too_many_arguments)] // Every media input of one call.
pub(crate) async fn run(
    credentials: Credentials,
    url: String,
    capture: Receiver<Frame>,
    playback: SyncSender<Frame>,
    mut controls: watch::Receiver<Controls>,
    emit: impl Fn(Status),
    identity: Arc<Identity>,
    streams: Arc<StreamMix>,
    camera: Receiver<Option<crate::screen::Video>>,
    feeds: Arc<crate::CameraFeeds>,
    allow_loopback: bool,
) -> Result<(), &'static str> {
    use std::sync::atomic::Ordering as Atomic;
    // RustCord: other people's cameras, one decoder each.
    let mut receivers = crate::video_receive::Receivers::default();
    let mut decoders: std::collections::HashMap<u64, (crate::video_receive::DecoderQueue, crate::video_receive::Lost)> = std::collections::HashMap::new();
    let mut receive_reports = crate::video_feedback::ReceiveReports::new(std::time::Instant::now());
    let mut transport_feedback = crate::transport_feedback::TransportFeedback::new(std::time::Instant::now());
    let mut next_sink_wants = Instant::now();
    let mut next_receive_report = Instant::now();
    let mut next_transport_feedback = Instant::now();
    let mut cameras_enabled = false;
    // RustCord: the camera. `Some` starts sending that source, `None` stops.
    let mut video: Option<crate::screen::Video> = None;
    let mut camera_closed = false;
    let (mut video_ssrc, mut rtx_ssrc) = (0u32, 0u32);
    let mut video_announced = false;
    let mut awaiting_keyframe = true;
    let mut outgoing_keyframe = false;
    let mut outgoing = crate::video::Pacer::new();
    let mut history = crate::video::History::default();
    let mut rate = crate::video::Rate::new(250_000, Instant::now());
    let mut next_keyframe = Instant::now();
    let mut video_random = [0; 4];
    getrandom::fill(&mut video_random).map_err(|_| "Voice random initialization failed")?;
    let mut video_sequence = u16::from_be_bytes([video_random[0], video_random[1]]);
    let mut rtx_sequence = u16::from_be_bytes([video_random[2], video_random[3]]);
    let mut mixer = crate::mixer::Mixer::default();
    let tls = tls_connector()?;
    emit(Status::Connecting);
    let mut ws = connect(
        &url,
        &tls,
        "Voice connection failed",
        "Voice connection timed out",
    )
    .await?;
    // Only voice-scoped credentials go to this validated endpoint; no account Authorization header.
    json_send(&mut ws, identify(&credentials)).await?;
    let mut dave = Dave::with_identity(credentials.user, None, credentials.channel, identity)?;
    let mut encryption: Option<Encryption> = None;
    // The roster message normally follows the session key within milliseconds; only after
    // this grace does a sole member conclude nobody else is in the call.
    let mut secured_at: Option<Instant> = None;
    let mut udp: Option<UdpSocket> = None;
    let mut next_udp_ping = Instant::now();
    let mut udp_ping_sequence = 0;
    let mut udp_failures = UdpFailures::default();
    let mut discovering = false;
    let mut discovery_deadline = Instant::now();
    let mut next_discovery_probe = Instant::now();
    let mut ssrc = 0u32;
    let mut seq_ack: i64 = -1;
    let mut heartbeat_ms: Option<u64> = None;
    let mut heartbeat_at = Instant::now();
    let mut heartbeat_sent = Instant::now();
    let mut awaiting_ack = None;
    let mut heartbeat_nonce = 0u64;
    let mut missed_acks = 0u8;
    // Set when the signaling socket died or went silent; the next loop turn resumes it.
    let mut reconnect: Option<&'static str> = None;
    let mut deadline = Some(Instant::now() + Duration::from_secs(90));
    let mut ready_announced = false;
    let mut waiting_announced = false;
    let mut resuming = false;
    let mut resume_attempts = 0u8;
    let mut heard = false;
    let mut speaking_now = false;
    let mut silence = 0u8;
    let mut encoder = opus_encoder()?;
    let mut encoder_bitrate = OPUS_BITRATE;
    let mut random = [0; 6];
    getrandom::fill(&mut random).map_err(|_| "Voice random initialization failed")?;
    let mut sequence = u16::from_be_bytes([random[0], random[1]]);
    let mut timestamp = u32::from_be_bytes([random[2], random[3], random[4], random[5]]);
    let mut packet = [0u8; MAX_PACKET + 1];
    let mut encoded = [0u8; 1275];
    let mut stereo = [0.0f32; 1_920];
    let mut soft_clip = SoftClip::new(Channels::Stereo);
    let mut tick = tokio::time::interval(Duration::from_millis(20));
    // A late wake-up (a game using every core) replays the missed ticks at once: queued
    // microphone frames are still sent and the speech that arrived meanwhile is still
    // played, a little late, instead of being skipped. Only a real stall starts over.
    tick.set_missed_tick_behavior(MissedTickBehavior::Burst);
    let mut health = crate::health::Reporter::default();
    let mut signal_window = Instant::now();
    let mut signal_count = 0u16;
    let mut capture_pacer = crate::capture::CapturePacer::default();
    let mut capture_at = Instant::now();
    let mut capture_enabled = false;
    let mut capture_reset = true;
    let mut local_activity = 0;
    let mut last_speakers: Vec<u64> = Vec::with_capacity(MAX_PARTICIPANTS);
    let mut current_speakers: Vec<u64> = Vec::with_capacity(MAX_PARTICIPANTS);
    // Users the voice server announced (opcode 11) and has not removed (opcode 13).
    let mut roster: Vec<u64> = Vec::new();
    loop {
        if let Some(reason) = reconnect.take() {
            if encryption.is_none() || resume_attempts >= 2 {
                return Err(reason);
            }
            resume_attempts += 1;
            resuming = true;
            ready_announced = false;
            waiting_announced = false;
            capture_reset = true;
            emit(Status::Securing);
            deadline = Some(Instant::now() + Duration::from_secs(30));
            heartbeat_ms = None;
            awaiting_ack = None;
            missed_acks = 0;
            ws = connect(
                &url,
                &tls,
                "Voice resume failed; rejoin the call",
                "Voice resume timed out; rejoin the call",
            )
            .await?;
            json_send(&mut ws, resume(&credentials, seq_ack)).await?;
        }
        // The rest of a picture encrypted before an encryption change is never sent.
        if !video_announced || !dave.ready || dave.transitioning() || !dave.session.is_ready() {
            outgoing.clear();
            history.clear();
            outgoing_keyframe = false;
        }
        if outgoing.stale(Instant::now()) {
            outgoing.clear();
            history.clear();
            outgoing_keyframe = false;
            awaiting_keyframe = true;
            if let Some(video) = &mut video {
                video.stats.dropped(1);
                while video.frames.try_recv().is_ok() {
                    video.stats.dropped(1);
                }
                video.keyframe.store(true, Atomic::Release);
            }
        }
        tokio::select! {
            _ = tokio::time::sleep_until(outgoing.deadline), if !outgoing.is_empty() || history.has_pending() => {
                let (Some(crypto), Some(socket)) = (encryption.as_mut(), udp.as_ref()) else {
                    outgoing.clear();
                    history.clear();
                    continue;
                };
                let now = Instant::now();
                if history.has_pending()
                    && outgoing.allow_repair(now, rate.target)
                    && let Some(packet) = history.repair(rtx_ssrc, &mut rtx_sequence, now)
                {
                    // The original DAVE ciphertext is reused; the transport nonce is always fresh.
                    let sealed = crypto.seal(&packet.header, &packet.payload)?;
                    udp_failures.send(socket, &sealed, "Camera retransmission failed")?;
                    if let Some(video) = &video {
                        video.stats.bytes(sealed.len());
                    }
                }
                for packet in outgoing.next_batch(now, rate.target) {
                    let sealed = crypto.seal(&packet.header, &packet.payload)?;
                    udp_failures.send(socket, &sealed, "Camera UDP send failed")?;
                    if let Some(video) = &video {
                        video.stats.bytes(sealed.len());
                    }
                    if rtx_ssrc != 0 {
                        history.remember(packet, now);
                    }
                }
                if outgoing.is_empty() && outgoing_keyframe {
                    awaiting_keyframe = false;
                }
            }
            frame = async {
                match video.as_mut() {
                    Some(video) => video.frames.recv().await,
                    None => std::future::pending().await,
                }
            }, if outgoing.is_empty() => {
                let Some(frame) = frame else {
                    // Capture ended (unplugged, or its worker failed): the tick withdraws it.
                    video = None;
                    camera_closed = true;
                    continue;
                };
                let Some(source) = video.as_mut() else { continue };
                let secure = video_announced && dave.ready && dave.session.is_ready() && !dave.transitioning() && encryption.is_some() && !discovering && !resuming && source.ready.load(Atomic::Acquire);
                if !secure || frame.data.len() > 2 * 1024 * 1024 {
                    source.stats.dropped(1);
                    awaiting_keyframe = true;
                    source.keyframe.store(true, Atomic::Release);
                    continue;
                }
                if awaiting_keyframe && !frame.keyframe {
                    source.stats.dropped(1);
                    continue;
                }
                let normalized = crate::video_sps::normalize(&frame.data)?;
                let encrypted = dave.session.encrypt(davey::MediaType::VIDEO, davey::Codec::H264, &normalized).map_err(|_| "DAVE H264 encryption failed")?;
                let packets = crate::video::packetize(&encrypted, &mut video_sequence, frame.timestamp, video_ssrc)?;
                outgoing.queue(packets, Instant::now());
                outgoing_keyframe = frame.keyframe;
                source.stats.frame();
            }
            changed = controls.changed() => {
                if changed.is_err() {
                    return Ok(());
                }
            }
            _ = tick.tick() => {
                let now = Instant::now();
                // Everything that already arrived joins the reorder windows before this
                // tick mixes: after a late wake-up the order of ticks and packets would
                // otherwise be a coin toss, and a tick that runs first conceals speech
                // that is sitting in the socket.
                if !discovering && let (Some(socket), Some(crypto)) = (&udp, &encryption) {
                    let deafened = controls.borrow().deafened;
                    for _ in 0..256 {
                        let Ok(length) = socket.try_recv(&mut packet) else { break };
                        if video_announced
                            && length <= MAX_PACKET
                            && let Some(source) = &video
                            && let Some(feedback) = crypto.feedback(&packet[..length], video_ssrc)
                        {
                            camera_feedback(feedback, source, &mut rate, &mut history, rtx_ssrc, &mut next_keyframe);
                            continue;
                        }
                        let arrivals = receivers.has_sources().then_some(&mut transport_feedback);
                        if let Some(rtp) = receive_audio(&packet, length, crypto, &mut dave, &mut mixer, deafened, arrivals) {
                            receive_camera(rtp, &mut receivers, &mut dave, &decoders, &mut receive_reports);
                        }
                    }
                }
                health.tick(now.into());
                if deadline.is_some_and(|d| now >= d) {
                    return Err(negotiation_timeout(heartbeat_ms.is_some(), udp.is_some(), encryption.is_some(), &dave, resuming));
                }
                if discovering {
                    if now >= discovery_deadline {
                        return Err("Discord voice UDP discovery timed out; check the network firewall");
                    }
                    // UDP is lossy: repeat the probe until the reply arrives.
                    if now >= next_discovery_probe && let Some(socket) = &udp {
                        let _ = socket.try_send(&discovery_request(ssrc));
                        next_discovery_probe = now + DISCOVERY_RETRY;
                    }
                }
                if !discovering && now >= next_udp_ping && let Some(socket) = &udp {
                    udp_keepalive(socket, &mut udp_failures, &mut udp_ping_sequence)?;
                    next_udp_ping = now + Duration::from_secs(5);
                }
                if let Some(interval) = heartbeat_ms && now >= heartbeat_at {
                    // A delayed wake can find the acknowledgement still unread; only a second
                    // silent interval marks the socket as zombied, and Discord expects a resume.
                    if awaiting_ack.is_some() {
                        missed_acks += 1;
                        if missed_acks >= 2 {
                            reconnect = Some("Discord voice heartbeat was not acknowledged; rejoin the call");
                            continue;
                        }
                    }
                    heartbeat_nonce = heartbeat_nonce.wrapping_add(1);
                    json_send(&mut ws, heartbeat(heartbeat_nonce, seq_ack)).await?;
                    awaiting_ack = Some(heartbeat_nonce);
                    heartbeat_sent = now;
                    heartbeat_at = now + Duration::from_millis(interval);
                }
                if secured_at.is_some_and(|at| now >= at + PEER_GRACE) && !discovering && !resuming && dave.should_wait_for_peer() {
                    dave.enter_sole_member_waiting()?;
                }
                let enabled = dave.ready && encryption.is_some() && !discovering && !resuming;
                let waiting = dave.waiting && encryption.is_some() && !discovering && !resuming;
                if (!enabled && ready_announced) || (!waiting && waiting_announced) {
                    ready_announced = false;
                    waiting_announced = false;
                    emit(Status::Securing);
                }
                if waiting && !waiting_announced {
                    deadline = None;
                    waiting_announced = true;
                    emit(Status::WaitingForPeer);
                }
                if !waiting {
                    waiting_announced = false;
                }
                if enabled && !ready_announced {
                    deadline = None;
                    ready_announced = true;
                    emit(Status::Ready);
                }
                // ---- other people's cameras ----
                if enabled != cameras_enabled {
                    cameras_enabled = enabled;
                    // Pictures predicted from before an encryption change are useless.
                    receivers.require_all_keyframes();
                }
                if enabled && receivers.has_sources() && let (Some(crypto), Some(socket)) = (encryption.as_mut(), udp.as_ref()) {
                    let wall = now.into_std();
                    // Pictures that were waiting for a packet that never came.
                    decode_cameras(&mut receivers, &mut dave, &decoders, None);
                    for (header, body) in receivers.nacks(ssrc, wall) {
                        udp_failures.send(socket, &crypto.seal_rtcp(&header, &body)?, "Camera NACK send failed")?;
                    }
                    for (_, lost) in decoders.values() {
                        receivers.absorb(lost);
                    }
                    for media in receivers.take_keyframe_requests(wall) {
                        let (header, body) = crate::video_receive::pli(ssrc, media);
                        udp_failures.send(socket, &crypto.seal_rtcp(&header, &body)?, "Camera keyframe request failed")?;
                    }
                    // The server forwards video only to those who keep asking for it.
                    if now >= next_sink_wants {
                        json_send(&mut ws, json!({"op":15,"d":{"any":100}})).await?;
                        next_sink_wants = now + Duration::from_secs(5);
                    }
                    if now >= next_receive_report {
                        receive_reports.retain(|source| receivers.has_source(source));
                        let (header, body) = receive_reports.report(ssrc, wall);
                        udp_failures.send(socket, &crypto.seal_rtcp(&header, &body)?, "Camera reception report failed")?;
                        next_receive_report = now + Duration::from_secs(1);
                    }
                    if now >= next_transport_feedback {
                        for _ in 0..2 {
                            let Some(report) = transport_feedback.report(ssrc, wall) else { break };
                            udp_failures.send(socket, &crypto.seal_rtcp(&report.header, &report.body)?, "Camera transport feedback failed")?;
                        }
                        next_transport_feedback = now + Duration::from_millis(100);
                    }
                }
                // ---- camera ----
                history.expire(now);
                let mut withdraw = std::mem::take(&mut camera_closed);
                let mut requested = None;
                while let Ok(next) = camera.try_recv() {
                    requested = Some(next);
                }
                if let Some(next) = requested {
                    withdraw = true;
                    video = next;
                    if let Some(source) = &video {
                        rate = crate::video::Rate::new(source.settings.bit_rate(), now);
                    }
                }
                if withdraw {
                    outgoing.clear();
                    history.clear();
                    outgoing_keyframe = false;
                    awaiting_keyframe = true;
                    if video_announced {
                        video_announced = false;
                        json_send(&mut ws, json!({"op":12,"d":{"audio_ssrc":ssrc,"video_ssrc":0,"rtx_ssrc":0,"streams":[]}})).await?;
                    }
                }
                let video_secure = enabled && video_ssrc != 0 && dave.session.is_ready() && !dave.transitioning();
                if let Some(source) = &mut video {
                    if video_secure && let Some(target) = rate.tick(now) {
                        source.bitrate.store(target, Atomic::Release);
                    }
                    if video_secure && !video_announced {
                        invalidate_camera(source);
                        let streams = json!([{"type":"video","rid":"100","ssrc":video_ssrc,"active":true,"quality":100,"rtx_ssrc":rtx_ssrc,"max_bitrate":source.settings.bit_rate(),"max_framerate":source.settings.fps,"max_resolution":{"type":"fixed","width":source.settings.width,"height":source.settings.height}}]);
                        json_send(&mut ws, json!({"op":12,"d":{"audio_ssrc":ssrc,"video_ssrc":video_ssrc,"rtx_ssrc":rtx_ssrc,"streams":streams}})).await?;
                        awaiting_keyframe = true;
                        source.keyframe.store(true, Atomic::Release);
                        source.ready.store(true, Atomic::Release);
                        video_announced = true;
                    }
                    if !video_secure && video_announced {
                        video_announced = false;
                        awaiting_keyframe = true;
                        invalidate_camera(source);
                    }
                }
                let control = *controls.borrow();
                if control.bitrate != encoder_bitrate {
                    encoder_bitrate = control.bitrate;
                    encoder.set_bitrate(Bitrate::Bits(encoder_bitrate)).map_err(|_| "Opus bitrate configuration failed")?;
                }
                // Preserve ordinary callback batches. Only a real stall (four packet
                // intervals) discards queued speech; mute/security gates always flush.
                let resumed_capture = enabled && (!capture_enabled || capture_reset);
                let gap = now.duration_since(capture_at);
                // Up to `STALL` the missed ticks are replayed (the queues hold 320 ms);
                // beyond it the audio is too old to be worth the delay.
                let stalled = !resumed_capture && gap >= STALL;
                if enabled && !resumed_capture {
                    if stalled {
                        crate::health::count(&crate::health::STALLS);
                        tick.reset();
                    } else if gap >= Duration::from_millis(30) {
                        crate::health::count(&crate::health::LATE_TICKS);
                    } else if gap < Duration::from_millis(5) {
                        crate::health::count(&crate::health::CATCH_UP_TICKS);
                    }
                    let late = u32::try_from(gap.as_millis().saturating_sub(20)).unwrap_or(u32::MAX);
                    crate::health::WORST_LATE_MS.fetch_max(late, std::sync::atomic::Ordering::Relaxed);
                }
                capture_at = now;
                capture_enabled = enabled;
                capture_reset = false;
                let latest = if waiting {
                    capture_pacer.preview(&capture)
                } else {
                    capture_pacer.next(&capture, enabled && !control.muted && !control.deafened, stalled)
                };
                local_activity = if (enabled || waiting) && !control.muted && !control.deafened && !stalled {
                    let energy = latest.as_ref().map_or(0.0, |frame| frame.iter().filter(|s| s.is_finite()).map(|s| s * s).sum());
                    // The speaking indicator follows the send gate's sensitivity.
                    crate::activity::hold_at(energy, local_activity, crate::settings::call_threshold_db())
                } else {
                    0
                };
                let active = enabled && !control.muted && !control.deafened && latest.is_some();
                if active && !speaking_now {
                    json_send(&mut ws, speaking(true, ssrc)).await?;
                    speaking_now = true;
                }
                if !active && speaking_now && silence == 0 {
                    silence = TRAILING_SILENCE_FRAMES;
                }
                if enabled && (active || silence > 0) {
                    let data = match latest {
                        Some(frame) if active => {
                            for (sample, pair) in frame.iter().zip(stereo.as_chunks_mut::<2>().0) {
                                let sample = if sample.is_finite() { sample.clamp(-1.0, 1.0) } else { 0.0 };
                                pair[0] = sample;
                                pair[1] = sample;
                            }
                            soft_clip.apply(&mut stereo);
                            let length = encoder.encode_float(&stereo, &mut encoded).map_err(|_| "Opus encoding failed")?;
                            dave.session.encrypt_opus(&encoded[..length]).map_err(|_| "DAVE audio encryption failed")?.into_owned()
                        }
                        _ => {
                            silence -= 1;
                            // DAVE passes Discord's three-byte silence frame through unencrypted.
                            davey::OPUS_SILENCE_PACKET.to_vec()
                        }
                    };
                    let header = rtp_header(sequence, timestamp, ssrc);
                    let wire = encryption.as_mut().ok_or("Missing voice transport key")?.seal(&header, &data)?;
                    if let Some(socket) = &udp {
                        udp_failures.send(socket, &wire, "Voice UDP send failed")?;
                    }
                    sequence = sequence.wrapping_add(1);
                    if !active && silence == 0 {
                        json_send(&mut ws, speaking(false, ssrc)).await?;
                        speaking_now = false;
                    }
                    if active {
                        silence = 0;
                    }
                }
                timestamp = timestamp.wrapping_add(960);
                if enabled && !control.deafened {
                    if stalled {
                        mixer.clear();
                    }
                    let (frame, remote_audio) = mixer.pop_with_volumes(&control.user_volumes);
                    // Watched Go Live audio joins the participants' voices.
                    if let Some(frame) = streams.mix(frame, true, stalled) {
                        // A full playback queue drops this frame rather than stalling the clock.
                        let _ = playback.try_send(frame);
                    }
                    if !heard && remote_audio {
                        heard = true;
                        emit(Status::RemoteAudio);
                    }
                } else {
                    mixer.clear();
                    streams.mix(None, false, false);
                }
                // Activity holds for 200 ms, so per-tick evaluation cannot flicker.
                current_speakers.clear();
                if local_activity > 0 {
                    current_speakers.push(credentials.user);
                }
                current_speakers.extend(mixer.speaking());
                if current_speakers != last_speakers {
                    for (user, speaking) in speaking_changes(&last_speakers, &current_speakers) {
                        emit(Status::Speaking { user, speaking });
                    }
                    std::mem::swap(&mut last_speakers, &mut current_speakers);
                }
            }
            result = async {
                match &udp {
                    Some(socket) => socket.recv(&mut packet).await,
                    None => std::future::pending().await,
                }
            } => {
                let length = match result {
                    Ok(length) => length,
                    Err(error) if transient_receive(&error) => continue,
                    Err(_) => return Err("Voice UDP receive failed"),
                };
                if length > MAX_PACKET {
                    continue;
                }
                if discovering {
                    // A stray datagram before the reply is not the reply.
                    let Ok((address, port)) = discovery(&packet[..length], ssrc) else {
                        continue;
                    };
                    json_send(&mut ws, select_protocol(address, port)).await?;
                    discovering = false;
                    continue;
                }
                let Some(crypto) = &encryption else { continue };
                if video_announced
                    && let Some(source) = &video
                    && let Some(feedback) = crypto.feedback(&packet[..length], video_ssrc)
                {
                    camera_feedback(feedback, source, &mut rate, &mut history, rtx_ssrc, &mut next_keyframe);
                    continue;
                }
                let deafened = controls.borrow().deafened;
                let arrivals = receivers.has_sources().then_some(&mut transport_feedback);
                if let Some(rtp) = receive_audio(&packet, length, crypto, &mut dave, &mut mixer, deafened, arrivals) {
                    receive_camera(rtp, &mut receivers, &mut dave, &decoders, &mut receive_reports);
                }
            }
            event = ws.next() => {
                let event = match event {
                    // A server crash (4015), a non-voice close code or a closure without a
                    // code preserves the voice session. Voice close codes remain terminal.
                    Some(Ok(Message::Close(frame)))
                        if frame.as_ref().is_none_or(|frame| resumable_close(u16::from(frame.code))) =>
                    {
                        reconnect = Some("Discord voice connection closed; rejoin the call");
                        continue;
                    }
                    Some(Ok(message)) => message,
                    _ => {
                        reconnect = Some("Voice socket failed; rejoin the call");
                        continue;
                    }
                };
                if signal_window.elapsed() > Duration::from_secs(1) {
                    signal_window = Instant::now();
                    signal_count = 0;
                }
                signal_count += 1;
                if signal_count > 256 {
                    return Err("Voice signaling exceeded the bounded processing rate");
                }
                match event {
                    Message::Text(text) => {
                        let mut event: Value = serde_json::from_str(&text).map_err(|_| "Invalid voice JSON")?;
                        if let Some(seq) = event["seq"].as_i64() {
                            seq_ack = seq;
                        }
                        let op = number(&event, "op")?;
                        let data = &mut event["d"];
                        match op {
                            // Hello
                            8 => {
                                let interval = data["heartbeat_interval"].as_f64().filter(|v| v.is_finite() && *v >= 100.0 && *v <= 120_000.0).ok_or("Invalid voice heartbeat interval")? as u64;
                                if !(100..=120_000).contains(&interval) || heartbeat_ms.is_some() {
                                    return Err("Invalid voice heartbeat negotiation");
                                }
                                heartbeat_ms = Some(interval.min(5000));
                                heartbeat_at = Instant::now();
                            }
                            // Heartbeat ACK
                            6 => {
                                let nonce = data["t"].as_u64();
                                if acknowledges(awaiting_ack, missed_acks, nonce) {
                                    if nonce == awaiting_ack {
                                        let rtt = Instant::now().saturating_duration_since(heartbeat_sent);
                                        emit(Status::Ping(u32::try_from(rtt.as_millis()).unwrap_or(u32::MAX)));
                                    }
                                    awaiting_ack = None;
                                    missed_acks = 0;
                                    // A healthy resumed socket renews the consecutive resume budget.
                                    if !resuming {
                                        resume_attempts = 0;
                                    }
                                }
                            }
                            // Ready: SSRC, media server address and offered encryption modes.
                            2 => {
                                if udp.is_some() {
                                    return Err("Unexpected voice transport replacement; rejoin the call");
                                }
                                ssrc = u32::try_from(number(data, "ssrc")?).map_err(|_| "Invalid voice SSRC")?;
                                // The camera's SSRCs, when Discord assigned them (without: no camera).
                                if let Some(stream) = data["streams"].as_array().and_then(|list| list.first()) {
                                    let value = |key: &str| stream[key].as_u64().and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
                                    (video_ssrc, rtx_ssrc) = (value("ssrc"), value("rtx_ssrc"));
                                    if video_ssrc == ssrc || (rtx_ssrc != 0 && (rtx_ssrc == video_ssrc || rtx_ssrc == ssrc)) {
                                        (video_ssrc, rtx_ssrc) = (0, 0);
                                    }
                                }
                                let address: IpAddr = data["ip"].as_str().ok_or("Missing voice server address")?.parse().map_err(|_| "Invalid voice server address")?;
                                if !public_ip(address) && !(cfg!(test) && allow_loopback && address.is_loopback()) {
                                    return Err("Voice server advertised a nonpublic address");
                                }
                                let port = u16::try_from(number(data, "port")?).ok().filter(|p| *p > 0).ok_or("Invalid voice server port")?;
                                if !data["modes"].as_array().is_some_and(|m| m.iter().any(|m| m.as_str() == Some(MODE))) {
                                    return Err("Required voice transport encryption is unavailable");
                                }
                                let socket = UdpSocket::bind(if address.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }).await.map_err(|_| "Could not bind voice UDP socket")?;
                                socket.connect(SocketAddr::new(address, port)).await.map_err(|_| "Could not connect voice UDP socket")?;
                                socket.send(&discovery_request(ssrc)).await.map_err(|_| "Voice UDP discovery failed")?;
                                udp = Some(socket);
                                discovering = true;
                                discovery_deadline = Instant::now() + Duration::from_secs(8);
                                next_discovery_probe = Instant::now() + DISCOVERY_RETRY;
                                emit(Status::Discovering);
                            }
                            // Session Description: transport key and negotiated DAVE version.
                            4 => {
                                if encryption.is_some() || udp.is_none() || discovering {
                                    return Err("Unexpected voice session description");
                                }
                                if data["mode"].as_str() != Some(MODE) || data["dave_protocol_version"].as_u64() != Some(1) {
                                    return Err("Required DAVE version 1 encryption was not negotiated");
                                }
                                let values = data["secret_key"].take();
                                let values = values.as_array().ok_or("Missing voice transport key")?;
                                if values.len() != 32 {
                                    return Err("Invalid voice transport key");
                                }
                                let mut key = Zeroizing::new([0; 32]);
                                for (out, v) in key.iter_mut().zip(values) {
                                    *out = v.as_u64().and_then(|v| u8::try_from(v).ok()).ok_or("Invalid voice transport key")?;
                                }
                                encryption = Some(Encryption::new(&key));
                                secured_at = Some(Instant::now());
                                // Register the audio SSRC without sending media.
                                json_send(&mut ws, speaking(false, ssrc)).await?;
                                send(&mut ws, Message::Binary(dave.key_package()?.into())).await?;
                                emit(Status::Securing);
                            }
                            // Speaking: maps another user's SSRC.
                            5 => {
                                let user = id(data, "user_id")?;
                                if user != credentials.user && dave.contains(user) {
                                    let value = u32::try_from(number(data, "ssrc")?).map_err(|_| "Invalid voice SSRC")?;
                                    mixer.announce(user, value)?;
                                }
                            }
                            // Clients Connect
                            11 => {
                                let ids = data["user_ids"].as_array().ok_or("Missing voice participants")?;
                                if ids.len() > MAX_PARTICIPANTS {
                                    return Err("Voice channel exceeds the participant limit");
                                }
                                let ids = ids.iter().map(|v| v.as_str().and_then(|v| v.parse::<u64>().ok()).filter(|v| *v != 0).ok_or("Malformed voice participant")).collect::<Result<Vec<_>, _>>()?;
                                let was_ready = dave.ready;
                                if dave.connect(&ids)? {
                                    if was_ready {
                                        dave.ready = true;
                                    } else {
                                        deadline = Some(Instant::now() + Duration::from_secs(90));
                                        capture_reset = true;
                                        mixer.clear();
                                    }
                                }
                                for user in ids {
                                    if user != credentials.user && !roster.contains(&user) {
                                        roster.push(user);
                                        emit(Status::UserJoined(user));
                                    }
                                }
                            }
                            // Client Disconnect
                            13 => {
                                let user = id(data, "user_id")?;
                                mixer.remove(user);
                                receivers.remove(user);
                                decoders.remove(&user);
                                feeds.remove(user);
                                if let Some(index) = roster.iter().position(|known| *known == user) {
                                    roster.swap_remove(index);
                                    emit(Status::UserLeft(user));
                                }
                                let was_group_member = dave.is_group_member(user);
                                let was_ready = dave.ready;
                                if dave.disconnect(user)? {
                                    if dave.alone() {
                                        capture_reset = true;
                                        mixer.clear();
                                        dave.enter_sole_member_waiting()?;
                                        deadline = None;
                                        waiting_announced = true;
                                        ready_announced = false;
                                        emit(Status::WaitingForPeer);
                                    } else if was_ready {
                                        // The remaining members still share the current epoch until the removal commit.
                                        dave.ready = true;
                                        deadline = None;
                                    } else if was_group_member {
                                        deadline = Some(Instant::now() + Duration::from_secs(30));
                                        capture_reset = true;
                                        mixer.clear();
                                    }
                                }
                            }
                            // DAVE Prepare Transition
                            21 => {
                                if number(data, "protocol_version")? != 1 {
                                    return Err("Discord requested a voice encryption downgrade; call stopped");
                                }
                                capture_reset = true;
                                let id = transition(data)?;
                                dave.prepare_protocol(id);
                                if id == 0 {
                                    if dave.session.is_ready() {
                                        dave.execute(0)?;
                                    } else if dave.alone() {
                                        dave.enter_sole_member_waiting()?;
                                        deadline = None;
                                        waiting_announced = true;
                                        ready_announced = false;
                                        emit(Status::WaitingForPeer);
                                    } else {
                                        dave.pending_protocol = None;
                                        dave.ready = false;
                                    }
                                } else {
                                    json_send(&mut ws, ready_for_transition(id)).await?;
                                }
                            }
                            // DAVE Execute Transition
                            22 => dave.execute(transition(data)?)?,
                            // DAVE Prepare Epoch
                            24 => {
                                if number(data, "protocol_version")? != 1 {
                                    return Err("Unsupported DAVE protocol version; call stopped");
                                }
                                if number(data, "epoch")? == 1 {
                                    capture_reset = true;
                                    dave.reinitialize()?;
                                    deadline = Some(Instant::now() + Duration::from_secs(30));
                                    send(&mut ws, Message::Binary(dave.key_package()?.into())).await?;
                                }
                            }
                            // Resumed
                            9 => {
                                if !resuming {
                                    return Err("Unexpected voice resumption");
                                }
                                json_send(&mut ws, speaking(false, ssrc)).await?;
                                speaking_now = false;
                                silence = 0;
                                resuming = false;
                            }
                            // Client connect with SSRCs (video-capable clients); only audio is used.
                            12 => {
                                let user = id(data, "user_id")?;
                                if user != credentials.user && dave.contains(user)
                                    && let Some(value) = data["audio_ssrc"].as_u64().and_then(|v| u32::try_from(v).ok())
                                    && value != 0
                                {
                                    mixer.announce(user, value)?;
                                }
                                // Their camera. (Nothing here may end the call: a camera that
                                // cannot be shown is simply not shown.)
                                if user != credentials.user && let Some(sources) = camera_sources(data) {
                                    let keep: Vec<u32> = sources.iter().map(|(ssrc, _)| *ssrc).collect();
                                    receivers.retain_user_sources(user, &keep);
                                    let mut bound = false;
                                    for (media, rtx) in sources {
                                        if media != ssrc && media != video_ssrc && receivers.announce(user, media).is_ok() {
                                            bound = true;
                                            if let Some(rtx) = rtx {
                                                let _ = receivers.announce_rtx(media, rtx);
                                            }
                                        }
                                    }
                                    if !bound {
                                        receivers.remove(user);
                                        decoders.remove(&user);
                                        feeds.remove(user);
                                    } else {
                                        if !decoders.contains_key(&user)
                                            && decoders.len() < crate::video_receive::MAX_SOURCES
                                            && let Ok(decoder) = crate::video_receive::spawn_decoder(feeds.add(user))
                                        {
                                            decoders.insert(user, decoder);
                                        }
                                        receivers.require_keyframe(user);
                                        next_sink_wants = Instant::now();
                                    }
                                }
                            }
                            // Media sink wants, codecs, backend version, client flags/platform and any
                            // future informational opcode: nothing for an audio-only client to do.
                            _ => {}
                        }
                    }
                    Message::Binary(bytes) => {
                        if bytes.len() < 3 {
                            return Err("Truncated DAVE signaling");
                        }
                        seq_ack = i64::from(u16::from_be_bytes([bytes[0], bytes[1]]));
                        let opcode = bytes[2];
                        let data = &bytes[3..];
                        match opcode {
                            // External sender package
                            25 => dave.session.set_external_sender(data).map_err(|_| "DAVE external sender validation failed")?,
                            // Proposals
                            27 => {
                                if let Some(response) = dave.proposals(data)? {
                                    send(&mut ws, Message::Binary(response.into())).await?;
                                }
                            }
                            // Announce commit transition / welcome
                            29 | 30 => {
                                ready_announced = false;
                                waiting_announced = false;
                                match dave.group_changed(opcode, data) {
                                    Ok(id) => {
                                        if id != 0 {
                                            json_send(&mut ws, ready_for_transition(id)).await?;
                                        }
                                    }
                                    Err(_) => {
                                        if data.len() < 2 {
                                            return Err("Truncated DAVE transition");
                                        }
                                        let id = u16::from_be_bytes([data[0], data[1]]);
                                        json_send(&mut ws, invalid_commit_welcome(id)).await?;
                                        dave.reset()?;
                                        send(&mut ws, Message::Binary(dave.key_package()?.into())).await?;
                                    }
                                }
                                // A live call only re-announces Ready.
                                if dave.ready {
                                    deadline = None;
                                } else {
                                    capture_reset = true;
                                    mixer.clear();
                                    deadline = Some(Instant::now() + Duration::from_secs(30));
                                    emit(Status::Securing);
                                }
                            }
                            _ => return Err("Unsupported DAVE opcode; call stopped"),
                        }
                    }
                    Message::Ping(data) => send(&mut ws, Message::Pong(data)).await?,
                    Message::Close(Some(frame)) => return Err(close_reason(u16::from(frame.code))),
                    Message::Close(None) => return Err("Discord voice connection closed; rejoin the call"),
                    Message::Pong(_) => {}
                    _ => return Err("Unsupported voice websocket frame"),
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use opus2::Decoder;
    fn credentials(server: u64) -> Credentials {
        Credentials {
            user: 1,
            server,
            channel: 3,
            session: Zeroizing::new("synthetic-session".into()),
            token: Zeroizing::new("synthetic-token".into()),
        }
    }
    #[test]
    fn endpoints_are_normalized_and_restricted_to_discord_media() {
        for (raw, expected) in [
            (
                "c-ams05-1a2b3c4d.discord.media:443",
                "wss://c-ams05-1a2b3c4d.discord.media/?v=8",
            ),
            (
                "c-ams05-1a2b3c4d.discord.media",
                "wss://c-ams05-1a2b3c4d.discord.media/?v=8",
            ),
            (
                "wss://voice-1.discord.media:443",
                "wss://voice-1.discord.media/?v=8",
            ),
            (
                "voice-1.discord.media:443/",
                "wss://voice-1.discord.media/?v=8",
            ),
            (
                "snam.discord.media:443/1234567890123456789",
                "wss://snam.discord.media/1234567890123456789?v=8",
            ),
            (
                " voice-1.discord.media:2096 ",
                "wss://voice-1.discord.media:2096/?v=8",
            ),
        ] {
            assert_eq!(endpoint(raw).unwrap(), expected, "{raw}");
        }
        for bad in [
            "",
            "127.0.0.1",
            "127.0.0.1:9",
            "voice.discord.media.evil.test",
            "voice.discord.media/path",
            "voice.discord.media/123/456",
            "voice.discord.media/123?token=x",
            "voice.discord.media.evil.test/123",
            "[email protected]",
            "voice.discord.media?token=x",
            "http://voice.discord.media",
            "ws://voice.discord.media",
        ] {
            assert!(endpoint(bad).is_err(), "{bad}");
        }
        assert!(!public_ip("127.0.0.1".parse().unwrap()));
        assert!(!public_ip("192.168.1.1".parse().unwrap()));
        assert!(!public_ip("100.64.0.1".parse().unwrap()));
        assert!(!public_ip("::1".parse().unwrap()));
        assert!(public_ip("162.159.130.234".parse().unwrap()));
        assert!(public_ip("2606:4700::1".parse().unwrap()));
    }
    #[test]
    fn ip_discovery_packets_round_trip() {
        let request = discovery_request(42);
        assert_eq!(&request[..8], &[0, 1, 0, 70, 0, 0, 0, 42]);
        assert!(request[8..].iter().all(|b| *b == 0));
        let mut reply = [0; 74];
        reply[..4].copy_from_slice(&[0, 2, 0, 70]);
        reply[4..8].copy_from_slice(&42u32.to_be_bytes());
        reply[8..21].copy_from_slice(b"203.0.113.250");
        reply[72..].copy_from_slice(&50_004u16.to_be_bytes());
        assert_eq!(
            discovery(&reply, 42).unwrap(),
            ("203.0.113.250".parse().unwrap(), 50_004)
        );
        assert!(discovery(&reply, 43).is_err(), "SSRC must match");
        assert!(discovery(&reply[..73], 42).is_err());
        let mut request_echo = reply;
        request_echo[1] = 1;
        assert!(discovery(&request_echo, 42).is_err());
        let mut no_port = reply;
        no_port[72..].copy_from_slice(&[0, 0]);
        assert!(discovery(&no_port, 42).is_err());
        let mut unterminated = reply;
        unterminated[8..72].fill(b'1');
        assert!(discovery(&unterminated, 42).is_err());
        let mut ipv6 = [0; 74];
        ipv6[..8].copy_from_slice(&reply[..8]);
        ipv6[8..19].copy_from_slice(b"2001:db8::7");
        ipv6[72..].copy_from_slice(&1u16.to_be_bytes());
        assert_eq!(
            discovery(&ipv6, 42).unwrap().0,
            "2001:db8::7".parse::<IpAddr>().unwrap()
        );
    }
    #[test]
    fn gateway_messages_serialize_as_discord_expects() {
        let guild = credentials(30);
        assert_eq!(
            identify(&guild),
            json!({"op":0,"d":{"server_id":"30","user_id":"1","session_id":"synthetic-session","token":"synthetic-token","video":true,"streams":[{"type":"video","rid":"100","quality":100}],"max_dave_protocol_version":1}})
        );
        assert_eq!(
            resume(&credentials(3), 17),
            json!({"op":7,"d":{"server_id":"3","session_id":"synthetic-session","token":"synthetic-token","seq_ack":17}})
        );
        assert_eq!(heartbeat(5, -1), json!({"op":3,"d":{"t":5,"seq_ack":-1}}));
        assert_eq!(
            select_protocol("203.0.113.9".parse().unwrap(), 4000),
            json!({"op":1,"d":{"protocol":"udp","data":{"address":"203.0.113.9","port":4000,"mode":"aead_xchacha20_poly1305_rtpsize"},"codecs":[{"name":"opus","type":"audio","priority":1000,"payload_type":120},{"name":"H264","type":"video","priority":1000,"payload_type":101,"rtx_payload_type":102,"encode":true,"decode":true}]}})
        );
        assert_eq!(
            speaking(true, 42),
            json!({"op":5,"d":{"speaking":1,"delay":0,"ssrc":42}})
        );
        assert_eq!(
            speaking(false, 42),
            json!({"op":5,"d":{"speaking":0,"delay":0,"ssrc":42}})
        );
        assert_eq!(
            ready_for_transition(7),
            json!({"op":23,"d":{"transition_id":7}})
        );
        assert_eq!(
            invalid_commit_welcome(7),
            json!({"op":31,"d":{"transition_id":7}})
        );
        // Parsing helpers used on incoming dispatches.
        let hello: Value =
            serde_json::from_str(r#"{"op":8,"d":{"v":8,"heartbeat_interval":13750.25}}"#).unwrap();
        assert_eq!(number(&hello, "op").unwrap(), 8);
        let speaking_event: Value = serde_json::from_str(
            r#"{"op":5,"seq":3,"d":{"user_id":"80351110224678912","ssrc":43,"speaking":1}}"#,
        )
        .unwrap();
        assert_eq!(
            id(&speaking_event["d"], "user_id").unwrap(),
            80_351_110_224_678_912
        );
        assert_eq!(number(&speaking_event["d"], "ssrc").unwrap(), 43);
        assert!(id(&json!({"user_id":"0"}), "user_id").is_err());
        assert!(id(&json!({"user_id":5}), "user_id").is_err());
        assert_eq!(transition(&json!({"transition_id":9})).unwrap(), 9);
        assert!(transition(&json!({"transition_id":70000})).is_err());
        // Heartbeat acknowledgements: latest or a recently missed nonce only.
        assert!(acknowledges(Some(5), 0, Some(5)));
        assert!(!acknowledges(Some(5), 0, Some(4)));
        assert!(acknowledges(Some(5), 1, Some(4)));
        assert!(!acknowledges(None, 0, Some(5)));
        assert!(!acknowledges(Some(5), 0, None));
        assert_eq!(close_reason(4014), DISCONNECTED_BY_DISCORD);
        // Server crashes and non-voice closures resume; voice-specific codes are final.
        for code in [4015, 1000, 1001, 1006, 1011, 3000] {
            assert!(resumable_close(code), "{code}");
        }
        for code in [4001, 4004, 4006, 4009, 4014, 4021, 4022] {
            assert!(!resumable_close(code), "{code}");
        }
        assert!(close_reason(4006).contains("4006"));
        assert_eq!(
            close_reason(1000),
            "Discord voice connection closed; rejoin the call"
        );
        assert_eq!(
            speaking_changes(&[1, 2], &[2, 3]),
            vec![(1, false), (3, true)]
        );
        assert!(speaking_changes(&[4], &[4]).is_empty());
    }
    #[test]
    fn opus_encode_decode_round_trip_at_48k_stereo_20ms() {
        let mut encoder = opus_encoder().unwrap();
        let mut decoder = Decoder::new(48_000, Channels::Mono).unwrap();
        let mut stereo_decoder = Decoder::new(48_000, Channels::Stereo).unwrap();
        let mut out = [0.0; 960];
        let mut out_stereo = [0.0; 1920];
        let mut peak = 0.0f32;
        for frame in 0..10 {
            let input = std::array::from_fn::<_, 1920, _>(|i| {
                ((frame * 960 + i / 2) as f32 * 0.06).sin() * 0.3
            });
            let mut encoded = [0; 1275];
            let length = encoder.encode_float(&input, &mut encoded).unwrap();
            // 64 kbit/s: about 160 bytes per 20 ms packet.
            assert!(length < 400, "{length}");
            assert_eq!(
                opus2::packet::get_nb_channels(&encoded[..length]).unwrap(),
                Channels::Stereo
            );
            assert_eq!(
                decoder
                    .decode_float(&encoded[..length], &mut out, false)
                    .unwrap(),
                960
            );
            assert_eq!(
                stereo_decoder
                    .decode_float(&encoded[..length], &mut out_stereo, false)
                    .unwrap(),
                960
            );
            peak = out.iter().fold(peak, |peak, s| peak.max(s.abs()));
        }
        assert!(peak > 0.1, "decoded audio must carry the signal: {peak}");
        // The silence frame decodes to 20 ms of silence.
        let mut decoder = Decoder::new(48_000, Channels::Mono).unwrap();
        assert_eq!(
            decoder
                .decode_float(&davey::OPUS_SILENCE_PACKET, &mut out, false)
                .unwrap(),
            960
        );
        assert!(out.iter().all(|s| s.abs() < 0.001));
    }
    #[tokio::test]
    async fn wss_uses_an_explicit_rustls_provider_and_fails_cleanly_without_tls() {
        let tls = tls_connector().unwrap();
        assert!(matches!(tls, Connector::Rustls(_)));
        // A local server that answers the TLS ClientHello with plain text: the handshake
        // must fail with an error (no missing-CryptoProvider panic, no hang).
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            use tokio::io::{AsyncReadExt, AsyncWriteExt};
            let (mut tcp, _) = listener.accept().await.unwrap();
            let mut hello = [0; 5];
            tcp.read_exact(&mut hello).await.unwrap();
            assert_eq!(hello[0], 0x16, "a TLS handshake record");
            let _ = tcp.write_all(b"HTTP/1.1 400 Bad Request\r\n\r\n").await;
        });
        let result = timeout(
            Duration::from_secs(10),
            open_socket(&format!("wss://{address}/?v=8"), &tls),
        )
        .await
        .unwrap();
        assert!(result.is_err());
        server.await.unwrap();
    }
    #[tokio::test]
    async fn udp_send_errors_drop_datagrams_without_waiting_and_recover() {
        let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        socket.connect(peer.local_addr().unwrap()).await.unwrap();
        // As in `run`, where the awaited discovery probe precedes any `try_send`.
        socket.writable().await.unwrap();
        let mut failures = UdpFailures::default();
        failures.send(&socket, b"ok", "outage").unwrap();
        assert!(failures.0.is_none());
        let mut received = [0; 8];
        let length = timeout(Duration::from_secs(5), peer.recv(&mut received))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(length, 2);
        // An oversized datagram fails to send; that is one lost packet, not a dead call.
        let oversized = vec![0; 70_000];
        failures.send(&socket, &oversized, "outage").unwrap();
        failures.0 = Some(Instant::now() - UDP_OUTAGE);
        assert_eq!(failures.send(&socket, &oversized, "outage"), Err("outage"));
        socket.writable().await.unwrap();
        failures.send(&socket, b"ok", "outage").unwrap();
        assert!(
            failures.0.is_none(),
            "a successful send clears the outage clock"
        );
        let length = timeout(Duration::from_secs(5), peer.recv(&mut received))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(length, 2);
    }
}

#[cfg(test)]
#[path = "transport_tests.rs"]
mod local_server_tests;