Skip to content

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

42.8 KB
Raw Blame
// Adapted from Serein (https://github.com/ViceVerse-cz/Serein) at commit a0e72cc,
// file `crates/discord-voice/src/transport.rs` (tests `local_voice_exchange` and
// `local_voice_peer_disconnect_enters_waiting_without_timeout`).
// 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.
//! A loopback voice server (WebSocket + UDP + synthetic MLS delivery service) drives the
//! real event loop. Nothing here contacts Discord.
use super::*;
use crate::test_mls::Delivery;
use opus2::Decoder;
use tokio::net::TcpListener;

async fn receive_media(socket: &UdpSocket, packet: &mut [u8]) -> (usize, SocketAddr) {
    loop {
        let received = socket.recv_from(packet).await.unwrap();
        if received.0 != 8 {
            return received;
        }
        assert_eq!(&packet[..4], &[0x13, 0x37, 0xca, 0xfe]);
    }
}
async fn text(ws: &mut WebSocketStream<TcpStream>, value: Value) {
    ws.send(Message::Text(value.to_string().into()))
        .await
        .unwrap();
}
/// Read client messages, answering heartbeats, until one with `op` arrives.
async fn expect_op(ws: &mut WebSocketStream<TcpStream>, op: u64) -> Value {
    loop {
        let event: Value =
            serde_json::from_str(ws.next().await.unwrap().unwrap().to_text().unwrap()).unwrap();
        if event["op"] == 3 && op != 3 {
            text(ws, json!({"op":6,"d":{"t":event["d"]["t"]}})).await;
            continue;
        }
        assert_eq!(event["op"], op, "{event}");
        return event;
    }
}
/// Hello, Ready and the UDP discovery exchange, up to the client's Select Protocol.
async fn handshake(ws: &mut WebSocketStream<TcpStream>, udp: &UdpSocket) -> SocketAddr {
    let port = udp.local_addr().unwrap().port();
    text(ws, json!({"op":8,"d":{"heartbeat_interval":5000}})).await;
    text(ws, json!({"op":2,"d":{"ssrc":42,"ip":"127.0.0.1","port":port,"modes":["aead_aes256_gcm_rtpsize",MODE]}})).await;
    let mut probe = [0; 4096];
    let (n, client) = udp.recv_from(&mut probe).await.unwrap();
    assert_eq!(n, 74);
    assert_eq!(&probe[..8], &[0, 1, 0, 70, 0, 0, 0, 42]);
    probe[..4].copy_from_slice(&[0, 2, 0, 70]);
    probe[8..17].copy_from_slice(b"127.0.0.1");
    probe[72..74].copy_from_slice(&client.port().to_be_bytes());
    udp.send_to(&probe[..74], client).await.unwrap();
    let select = expect_op(ws, 1).await;
    assert_eq!(select["d"]["protocol"], "udp");
    assert_eq!(select["d"]["data"]["mode"], MODE);
    assert_eq!(select["d"]["data"]["address"], "127.0.0.1");
    assert_eq!(select["d"]["data"]["port"], client.port());
    assert_eq!(select["d"]["codecs"][0]["name"], "opus");
    client
}
fn local_credentials(server: u64) -> Credentials {
    Credentials {
        user: 1,
        server,
        channel: 3,
        session: Zeroizing::new("synthetic-session".into()),
        token: Zeroizing::new("synthetic-token".into()),
    }
}

#[tokio::test]
async fn local_voice_websocket_udp_dave_and_opus_exchange() {
    local_voice_exchange(false).await;
}
#[tokio::test]
async fn local_guild_voice_waiting_mixed_audio_and_resume() {
    local_voice_exchange(true).await;
}
async fn local_voice_exchange(guild: bool) {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let (done_tx, done_rx) = tokio::sync::oneshot::channel();
    let (captured_tx, mut captured_rx) = tokio::sync::oneshot::channel();
    let (waiting_tx, waiting_rx) = tokio::sync::oneshot::channel();
    let (heard_tx, heard_rx) = tokio::sync::oneshot::channel();
    let (resumed_tx, resumed_rx) = tokio::sync::oneshot::channel();
    let server = tokio::spawn(async move {
        let (tcp, _) = listener.accept().await.unwrap();
        let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
        let identify = ws.next().await.unwrap().unwrap().into_text().unwrap();
        let identify: Value = serde_json::from_str(&identify).unwrap();
        assert_eq!(identify["op"], 0);
        assert_eq!(identify["d"]["server_id"], if guild { "30" } else { "3" });
        assert_eq!(identify["d"]["user_id"], "1");
        assert_eq!(identify["d"]["session_id"], "synthetic-session");
        assert_eq!(identify["d"]["token"], "synthetic-token");
        assert_eq!(identify["d"]["max_dave_protocol_version"], 1);
        assert_eq!(identify["d"]["video"], true);
        let client = handshake(&mut ws, &udp).await;
        let mut probe = [0; 4096];
        let delivery = Delivery::new();
        let mut bob = Dave::new(2, (!guild).then_some(1), 3).unwrap();
        bob.session.set_external_sender(&delivery.external).unwrap();
        let mut charlie = Dave::new(4, None, 3).unwrap();
        if guild {
            bob.connect(&[1, 2, 4]).unwrap();
            charlie
                .session
                .set_external_sender(&delivery.external)
                .unwrap();
            charlie.connect(&[1, 2, 4]).unwrap();
            let (commit, welcome) = delivery.add(&mut bob, &charlie.key_package().unwrap());
            bob.group_changed(29, &[&[0, 0], commit.as_slice()].concat())
                .unwrap();
            charlie
                .group_changed(30, &[&[0, 0], welcome.as_slice()].concat())
                .unwrap();
        }
        let mut external = vec![0, 1, 25];
        external.extend(&delivery.external);
        ws.send(Message::Binary(external.into())).await.unwrap();
        text(
            &mut ws,
            json!({"op":4,"d":{"mode":MODE,"secret_key":vec![7;32],"dave_protocol_version":1}}),
        )
        .await;
        if !guild {
            // Discord announces the already connected DM peer to the joiner before any welcome.
            text(&mut ws, json!({"op":11,"d":{"user_ids":["1","2"]}})).await;
        }
        let mut audio_announced = false;
        let package = loop {
            match ws.next().await.unwrap().unwrap() {
                Message::Binary(bytes) => {
                    assert!(audio_announced);
                    break bytes;
                }
                Message::Text(text_frame) => {
                    let value: Value = serde_json::from_str(&text_frame).unwrap();
                    if value["op"] == 5 {
                        assert_eq!(value["d"]["speaking"], 0);
                        assert_eq!(value["d"]["ssrc"], 42);
                        audio_announced = true;
                        continue;
                    }
                    assert_eq!(value["op"], 3);
                    text(&mut ws, json!({"op":6,"d":{"t":value["d"]["t"]}})).await;
                }
                _ => panic!("unexpected test client frame"),
            }
        };
        assert_eq!(package[0], 26);
        if guild {
            text(
                &mut ws,
                json!({"op":21,"d":{"protocol_version":1,"transition_id":0}}),
            )
            .await;
            waiting_rx.await.unwrap();
            // Even queued synthetic capture cannot leave while the empty room lacks media keys.
            assert!(
                timeout(Duration::from_millis(80), receive_media(&udp, &mut probe))
                    .await
                    .is_err()
            );
            text(&mut ws, json!({"op":11,"d":{"user_ids":["1","2","4"]}})).await;
            let proposal = delivery.add_proposal(&bob, &package);
            charlie.proposals(&proposal).unwrap();
        }
        let (commit, welcome) = delivery.add(&mut bob, &package);
        let mut committed = vec![0, 0];
        committed.extend(commit);
        bob.group_changed(29, &committed).unwrap();
        if guild {
            charlie.group_changed(29, &committed).unwrap();
        }
        assert!(bob.ready);
        let mut welcome_frame = vec![0, 2, 30, 0, 0];
        welcome_frame.extend(welcome);
        ws.send(Message::Binary(welcome_frame.into()))
            .await
            .unwrap();
        // Exercise media readiness after a scheduling gap while the fixture
        // supplies continuous capture and fences signaling before UDP.
        std::thread::sleep(Duration::from_millis(100));
        text(
            &mut ws,
            json!({"op":5,"seq":3,"d":{"user_id":"2","ssrc":43,"speaking":1}}),
        )
        .await;
        if guild {
            text(
                &mut ws,
                json!({"op":5,"seq":4,"d":{"user_id":"4","ssrc":44,"speaking":1}}),
            )
            .await;
        }
        // Fence the SSRC announcements before UDP can race ahead of signaling.
        ws.send(Message::Ping(b"announced".to_vec().into()))
            .await
            .unwrap();
        loop {
            match ws.next().await.unwrap().unwrap() {
                Message::Pong(data) if data.as_ref() == b"announced" => break,
                Message::Text(text_frame) => {
                    let event: Value = serde_json::from_str(&text_frame).unwrap();
                    if event["op"] == 3 {
                        text(&mut ws, json!({"op":6,"d":{"t":event["d"]["t"]}})).await;
                    } else {
                        assert_eq!(event["op"], 5);
                    }
                }
                _ => panic!("unexpected test client frame before SSRC acknowledgement"),
            }
        }
        let (length, _) = receive_media(&udp, &mut probe).await;
        let mut transport = Encryption::new(&[7; 32]);
        let opened = transport.open(&probe[..length]).unwrap();
        let (ssrc, ciphertext) = (opened.ssrc, opened.payload);
        assert_eq!(ssrc, 42);
        let encoded = bob
            .session
            .decrypt(1, davey::MediaType::AUDIO, &ciphertext)
            .unwrap();
        assert_eq!(
            opus2::packet::get_nb_channels(&encoded).unwrap(),
            Channels::Stereo
        );
        assert!(encoded.len() < 1275);
        let mut decoder = Decoder::new(48_000, Channels::Mono).unwrap();
        let mut out = [0.0; 960];
        assert_eq!(
            decoder.decode_float(&encoded, &mut out, false).unwrap(),
            960
        );
        assert!(out.iter().any(|s| s.abs() > 0.01));
        captured_tx.send(()).unwrap();
        let mut encoder = Encoder::new(48_000, Channels::Mono, Application::Voip).unwrap();
        let mut encoded = [0; 1275];
        let tone: [f32; 960] = std::array::from_fn(|i| (i as f32 * 0.05).sin() * 0.3);
        let length = encoder.encode_float(&tone, &mut encoded).unwrap();
        let encrypted = bob.session.encrypt_opus(&encoded[..length]).unwrap();
        let header = [0x80, 120, 0, 1, 0, 0, 0, 1, 0, 0, 0, 43];
        let packet = transport.seal(&header, &encrypted).unwrap();
        udp.send_to(&packet, client).await.unwrap();
        if guild {
            let encrypted = charlie.session.encrypt_opus(&encoded[..length]).unwrap();
            let mut header = header;
            header[11] = 44;
            let packet = transport.seal(&header, &encrypted).unwrap();
            udp.send_to(&packet, client).await.unwrap();
        }
        // Resume only after the client has actually played the initial remote audio.
        heard_rx.await.unwrap();
        if guild {
            ws.send(Message::Close(Some(
                tokio_tungstenite::tungstenite::protocol::CloseFrame {
                    code: 4015.into(),
                    reason: "synthetic server restart".into(),
                },
            )))
            .await
            .unwrap();
        }
        drop(ws);
        let (tcp, _) = listener.accept().await.unwrap();
        let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
        let resume: Value =
            serde_json::from_str(ws.next().await.unwrap().unwrap().to_text().unwrap()).unwrap();
        assert_eq!(resume["op"], 7);
        assert_eq!(resume["d"]["seq_ack"], if guild { 4 } else { 3 });
        assert_eq!(resume["d"]["server_id"], if guild { "30" } else { "3" });
        assert_eq!(resume["d"]["session_id"], "synthetic-session");
        assert_eq!(resume["d"]["token"], "synthetic-token");
        text(&mut ws, json!({"op":8,"d":{"heartbeat_interval":5000}})).await;
        text(&mut ws, json!({"op":9,"d":null})).await;
        resumed_rx.await.unwrap();
        // A new encrypted frame after resume reuses the live MLS group, never its old nonce.
        let encrypted = bob.session.encrypt_opus(&encoded[..length]).unwrap();
        let mut header = header;
        header[3] = 2;
        let packet = transport.seal(&header, &encrypted).unwrap();
        udp.send_to(&packet, client).await.unwrap();
        done_rx.await.unwrap();
        if guild {
            ws.send(Message::Close(Some(
                tokio_tungstenite::tungstenite::protocol::CloseFrame {
                    code: 4014.into(),
                    reason: "synthetic terminal disconnect".into(),
                },
            )))
            .await
            .unwrap();
            // A terminal disconnect must never attempt another connection.
            assert!(
                timeout(Duration::from_millis(100), listener.accept())
                    .await
                    .is_err()
            );
        }
    });
    let (capture_tx, capture) = std::sync::mpsc::sync_channel(8);
    capture_tx.try_send([0.25; 960]).unwrap();
    let (playback, playback_rx) = std::sync::mpsc::sync_channel(8);
    let (control_tx, control_rx) = watch::channel(Controls::default());
    let (status_tx, mut status_rx) = tokio::sync::mpsc::unbounded_channel();
    let task = tokio::spawn(run(
        local_credentials(if guild { 30 } else { 3 }),
        format!("ws://{address}"),
        capture,
        playback,
        control_rx,
        move |status| {
            let _ = status_tx.send(status);
        },
        crate::crypto::Identity::generate(),
        Arc::default(),
        std::sync::mpsc::channel().1,
        Arc::default(),
        true,
    ));
    let mut seen = Vec::new();
    let pcm = timeout(Duration::from_secs(10), async {
        let mut ready = 0;
        let mut heard = false;
        let mut waiting = false;
        let mut captured = false;
        let mut resumed_pcm = None;
        let mut waiting_tx = Some(waiting_tx);
        let mut heard_tx = Some(heard_tx);
        let mut resumed_tx = Some(resumed_tx);
        let mut capture_tick = tokio::time::interval(Duration::from_millis(20));
        capture_tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
        loop {
            tokio::select! {
                status = status_rx.recv() => {
                    let status = status.unwrap();
                    match &status {
                        Status::Ready => {
                            ready += 1;
                            if ready == 2 {
                                // Discard first-session playback before allowing the peer's new frame.
                                for _ in 0..8 {
                                    if playback_rx.try_recv().is_err() { break; }
                                }
                                resumed_tx.take().unwrap().send(()).unwrap();
                            }
                        }
                        Status::RemoteAudio => {
                            heard = true;
                            if let Some(sender) = heard_tx.take() { sender.send(()).unwrap(); }
                        }
                        Status::WaitingForPeer => {
                            waiting = true;
                            if let Some(sender) = waiting_tx.take() { sender.send(()).unwrap(); }
                        }
                        _ => {}
                    }
                    seen.push(status);
                },
                result = &mut captured_rx, if !captured => {
                    result.unwrap();
                    captured = true;
                },
                _ = capture_tick.tick(), if ready > 0 => {
                    // Model a bounded continuous microphone, not one frame discarded by a stall.
                    if !captured {
                        match capture_tx.try_send(std::array::from_fn(|i| (i as f32 * 0.06).sin() * 0.3)) {
                            Ok(()) | Err(std::sync::mpsc::TrySendError::Full(_)) => {}
                            Err(std::sync::mpsc::TrySendError::Disconnected(_)) => panic!("test capture stopped before peer receipt"),
                        }
                    }
                    if ready == 2 {
                        resumed_pcm = playback_rx.try_recv().ok();
                    }
                }
            }
            if ready == 2 && heard && captured && let Some(pcm) = resumed_pcm.take() {
                assert_eq!(waiting, guild);
                break pcm;
            }
        }
    })
    .await
    .unwrap();
    assert!(pcm.iter().any(|s| s.abs() > 0.01));
    if guild {
        done_tx.send(()).unwrap();
        assert_eq!(
            timeout(Duration::from_secs(2), task)
                .await
                .unwrap()
                .unwrap(),
            Err(DISCONNECTED_BY_DISCORD)
        );
        drop(control_tx);
    } else {
        drop(control_tx);
        assert!(task.await.unwrap().is_ok());
        done_tx.send(()).unwrap();
    }
    server.await.unwrap();
    while let Ok(status) = status_rx.try_recv() {
        seen.push(status);
    }
    // Progress order up to the first readiness.
    let progress: Vec<_> = seen
        .iter()
        .filter(|s| {
            matches!(
                s,
                Status::Connecting | Status::Discovering | Status::Securing | Status::Ready
            )
        })
        .take(4)
        .cloned()
        .collect();
    assert_eq!(
        progress[..3],
        [Status::Connecting, Status::Discovering, Status::Securing]
    );
    // Roster, ping and speaking events reach the application.
    assert!(seen.contains(&Status::UserJoined(2)));
    assert_eq!(seen.contains(&Status::UserJoined(4)), guild);
    assert!(
        !seen.contains(&Status::UserJoined(1)),
        "never announce your own ID"
    );
    assert!(
        seen.iter()
            .any(|s| matches!(s, Status::Ping(ms) if *ms < 5_000))
    );
    assert!(seen.contains(&Status::Speaking {
        user: 2,
        speaking: true
    }));
    assert!(seen.contains(&Status::Speaking {
        user: 1,
        speaking: true
    }));
    if guild {
        assert!(seen.contains(&Status::Speaking {
            user: 4,
            speaking: true
        }));
    }
}

#[tokio::test]
async fn local_voice_peer_disconnect_enters_waiting_without_timeout() {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let (waiting_peer_tx, waiting_peer_rx) = tokio::sync::oneshot::channel();
    let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
    let (finished_tx, finished_rx) = tokio::sync::oneshot::channel::<()>();

    let server = tokio::spawn(async move {
        let (tcp, _) = listener.accept().await.unwrap();
        let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
        let _identify = ws.next().await.unwrap().unwrap();
        handshake(&mut ws, &udp).await;

        let delivery = Delivery::new();
        let mut bob = Dave::new(2, Some(1), 3).unwrap();
        bob.session.set_external_sender(&delivery.external).unwrap();

        let mut external = vec![0, 1, 25];
        external.extend(&delivery.external);
        ws.send(Message::Binary(external.into())).await.unwrap();
        text(
            &mut ws,
            json!({"op":4,"d":{"mode":MODE,"secret_key":vec![7;32],"dave_protocol_version":1}}),
        )
        .await;
        text(&mut ws, json!({"op":11,"d":{"user_ids":["1","2"]}})).await;

        let package = loop {
            match ws.next().await.unwrap().unwrap() {
                Message::Binary(bytes) => break bytes,
                Message::Text(text_frame) => {
                    let value: Value = serde_json::from_str(&text_frame).unwrap();
                    if value["op"] == 3 {
                        text(&mut ws, json!({"op":6,"d":{"t":value["d"]["t"]}})).await;
                    }
                }
                _ => {}
            }
        };
        let (commit, welcome) = delivery.add(&mut bob, &package);
        let mut committed = vec![0, 0];
        committed.extend(commit);
        bob.group_changed(29, &committed).unwrap();
        assert!(bob.ready);
        let mut welcome_frame = vec![0, 2, 30, 0, 0];
        welcome_frame.extend(welcome);
        ws.send(Message::Binary(welcome_frame.into()))
            .await
            .unwrap();

        // Wait until the client has reached Ready.
        ready_rx.await.unwrap();

        // Bob departs (leaves the DM call). You are now the sole member.
        text(&mut ws, json!({"op":13,"d":{"user_id":"2"}})).await;

        // Wait until client transitions to WaitingForPeer.
        waiting_peer_rx.await.unwrap();

        // An unannounced participant leaving (quick connect/disconnect) must neither crash
        // nor start a negotiation timeout.
        text(&mut ws, json!({"op":13,"d":{"user_id":"999"}})).await;
        // Keep the socket open until the client is told to stop.
        let _ = finished_rx.await;
    });

    let (_capture_tx, capture) = std::sync::mpsc::sync_channel(8);
    let (playback, _playback_rx) = std::sync::mpsc::sync_channel(8);
    let (control_tx, control_rx) = watch::channel(Controls::default());
    let (status_tx, mut status_rx) = tokio::sync::mpsc::unbounded_channel();
    let task = tokio::spawn(run(
        local_credentials(3),
        format!("ws://{address}"),
        capture,
        playback,
        control_rx,
        move |status| {
            let _ = status_tx.send(status);
        },
        crate::crypto::Identity::generate(),
        Arc::default(),
        std::sync::mpsc::channel().1,
        Arc::default(),
        true,
    ));

    let mut seen = Vec::new();
    timeout(Duration::from_secs(5), async {
        let mut ready_tx = Some(ready_tx);
        let mut waiting_peer_tx = Some(waiting_peer_tx);
        while let Some(status) = status_rx.recv().await {
            match status {
                Status::Ready => {
                    if let Some(tx) = ready_tx.take() {
                        tx.send(()).unwrap();
                    }
                }
                Status::WaitingForPeer => {
                    if let Some(tx) = waiting_peer_tx.take() {
                        tx.send(()).unwrap();
                        seen.push(status);
                        break;
                    }
                }
                _ => {}
            }
            seen.push(status);
        }
    })
    .await
    .unwrap();
    // Let the client process the unknown departure.
    tokio::time::sleep(Duration::from_millis(100)).await;
    drop(control_tx);
    let res = task.await.unwrap();
    assert!(res.is_ok());
    let _ = finished_tx.send(());
    server.await.unwrap();
    while let Ok(status) = status_rx.try_recv() {
        seen.push(status);
    }
    assert!(seen.contains(&Status::UserJoined(2)));
    assert!(seen.contains(&Status::UserLeft(2)));
    assert!(!seen.contains(&Status::UserLeft(999)));
}

#[tokio::test]
async fn unreachable_or_refusing_voice_servers_fail_instead_of_hanging() {
    // A port with no listener: the connection is refused at once.
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    drop(listener);
    let (_control_tx, control_rx) = watch::channel(Controls::default());
    let (_capture_tx, capture) = std::sync::mpsc::sync_channel(8);
    let (playback, _playback_rx) = std::sync::mpsc::sync_channel(8);
    let result = timeout(
        Duration::from_secs(20),
        run(
            local_credentials(3),
            format!("ws://{address}"),
            capture,
            playback,
            control_rx,
            |_| {},
            crate::crypto::Identity::generate(),
            Arc::default(),
        std::sync::mpsc::channel().1,
        Arc::default(),
            true,
        ),
    )
    .await
    .unwrap();
    assert_eq!(result, Err("Voice connection failed"));

    // A server that closes with a terminal code before Ready ends the call with that reason.
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let server = tokio::spawn(async move {
        let (tcp, _) = listener.accept().await.unwrap();
        let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
        let _identify = ws.next().await.unwrap().unwrap();
        ws.send(Message::Close(Some(
            tokio_tungstenite::tungstenite::protocol::CloseFrame {
                code: 4004.into(),
                reason: "Authentication failed".into(),
            },
        )))
        .await
        .unwrap();
        // No resume is attempted before a transport key exists.
        assert!(
            timeout(Duration::from_millis(200), listener.accept())
                .await
                .is_err()
        );
    });
    let (_control_tx, control_rx) = watch::channel(Controls::default());
    let (_capture_tx, capture) = std::sync::mpsc::sync_channel(8);
    let (playback, _playback_rx) = std::sync::mpsc::sync_channel(8);
    let result = run(
        local_credentials(3),
        format!("ws://{address}"),
        capture,
        playback,
        control_rx,
        |_| {},
        crate::crypto::Identity::generate(),
        Arc::default(),
        std::sync::mpsc::channel().1,
        Arc::default(),
        true,
    )
    .await;
    assert_eq!(result, Err(close_reason(4004)));
    server.await.unwrap();
}

#[tokio::test]
async fn lost_discovery_probes_are_repeated_and_a_normal_close_resumes() {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let server = tokio::spawn(async move {
        let (tcp, _) = listener.accept().await.unwrap();
        let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
        let _identify = ws.next().await.unwrap().unwrap();
        let port = udp.local_addr().unwrap().port();
        text(&mut ws, json!({"op":8,"d":{"heartbeat_interval":5000}})).await;
        text(
            &mut ws,
            json!({"op":2,"d":{"ssrc":42,"ip":"127.0.0.1","port":port,"modes":[MODE]}}),
        )
        .await;
        // The first probe is "lost"; the client must ask again instead of timing out.
        let mut probe = [0; 74];
        let (n, _) = udp.recv_from(&mut probe).await.unwrap();
        assert_eq!(n, 74);
        let (n, client) = timeout(Duration::from_secs(3), udp.recv_from(&mut probe))
            .await
            .expect("discovery probe was not repeated")
            .unwrap();
        assert_eq!(n, 74);
        probe[..4].copy_from_slice(&[0, 2, 0, 70]);
        probe[8..17].copy_from_slice(b"127.0.0.1");
        probe[72..74].copy_from_slice(&client.port().to_be_bytes());
        udp.send_to(&probe[..74], client).await.unwrap();
        expect_op(&mut ws, 1).await;
        let delivery = Delivery::new();
        let mut external = vec![0, 1, 25];
        external.extend(&delivery.external);
        ws.send(Message::Binary(external.into())).await.unwrap();
        text(
            &mut ws,
            json!({"op":4,"d":{"mode":MODE,"secret_key":vec![7;32],"dave_protocol_version":1}}),
        )
        .await;
        // Wait for the key package, then close normally (1001, e.g. a server drain).
        loop {
            match ws.next().await.unwrap().unwrap() {
                Message::Binary(_) => break,
                Message::Text(frame) => {
                    let value: Value = serde_json::from_str(&frame).unwrap();
                    if value["op"] == 3 {
                        text(&mut ws, json!({"op":6,"d":{"t":value["d"]["t"]}})).await;
                    }
                }
                _ => {}
            }
        }
        ws.send(Message::Close(Some(
            tokio_tungstenite::tungstenite::protocol::CloseFrame {
                code: 1001.into(),
                reason: "synthetic drain".into(),
            },
        )))
        .await
        .unwrap();
        drop(ws);
        // The voice session survives: the client resumes on a fresh socket.
        let (tcp, _) = timeout(Duration::from_secs(5), listener.accept())
            .await
            .expect("a normal close must resume")
            .unwrap();
        let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
        let resume: Value =
            serde_json::from_str(ws.next().await.unwrap().unwrap().to_text().unwrap()).unwrap();
        assert_eq!(resume["op"], 7);
        ws
    });
    let (_capture_tx, capture) = std::sync::mpsc::sync_channel(8);
    let (playback, _playback_rx) = std::sync::mpsc::sync_channel(8);
    let (control_tx, control_rx) = watch::channel(Controls::default());
    let task = tokio::spawn(run(
        local_credentials(3),
        format!("ws://{address}"),
        capture,
        playback,
        control_rx,
        |_| {},
        crate::crypto::Identity::generate(),
        Arc::default(),
        std::sync::mpsc::channel().1,
        Arc::default(),
        true,
    ));
    let _ws = timeout(Duration::from_secs(15), server)
        .await
        .unwrap()
        .unwrap();
    drop(control_tx);
    assert_eq!(task.await.unwrap(), Ok(()));
}

/// RustCord: a peer's camera, end to end. The loopback server announces a video stream for
/// "bob" (opcode 12) and sends one DAVE-encrypted H.264 keyframe over UDP until the client
/// has decoded it into that user's camera feed. Also checks the client asks for video
/// (opcode 15) once a camera is announced.
#[tokio::test]
async fn a_peers_camera_is_decrypted_decoded_and_published() {
    fn keyframe(width: usize, height: usize) -> Vec<u8> {
        use openh264::{
            OpenH264API,
            encoder::{Encoder, EncoderConfig},
            formats::YUVBuffer,
        };
        let mut encoder = Encoder::with_api_config(OpenH264API::from_source(), EncoderConfig::new()).unwrap();
        let mut data = Vec::new();
        encoder.encode(&YUVBuffer::new(width, height)).unwrap().write_vec(&mut data);
        data
    }
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let (wanted_tx, wanted_rx) = tokio::sync::oneshot::channel();
    let server = tokio::spawn(async move {
        let (tcp, _) = listener.accept().await.unwrap();
        let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
        let _identify = ws.next().await.unwrap().unwrap();
        let client = handshake(&mut ws, &udp).await;
        let delivery = Delivery::new();
        let mut bob = Dave::new(2, Some(1), 3).unwrap();
        bob.session.set_external_sender(&delivery.external).unwrap();
        let mut external = vec![0, 1, 25];
        external.extend(&delivery.external);
        ws.send(Message::Binary(external.into())).await.unwrap();
        text(&mut ws, json!({"op":4,"d":{"mode":MODE,"secret_key":vec![7;32],"dave_protocol_version":1}})).await;
        text(&mut ws, json!({"op":11,"d":{"user_ids":["1","2"]}})).await;
        let package = loop {
            match ws.next().await.unwrap().unwrap() {
                Message::Binary(bytes) => break bytes,
                Message::Text(frame) => {
                    let value: Value = serde_json::from_str(&frame).unwrap();
                    if value["op"] == 3 {
                        text(&mut ws, json!({"op":6,"d":{"t":value["d"]["t"]}})).await;
                    }
                }
                _ => panic!("unexpected test client frame"),
            }
        };
        let (commit, welcome) = delivery.add(&mut bob, &package);
        let mut committed = vec![0, 0];
        committed.extend(commit);
        bob.group_changed(29, &committed).unwrap();
        assert!(bob.ready);
        let mut welcome_frame = vec![0, 2, 30, 0, 0];
        welcome_frame.extend(welcome);
        ws.send(Message::Binary(welcome_frame.into())).await.unwrap();
        // Bob turns his camera on.
        text(&mut ws, json!({"op":12,"seq":5,"d":{"user_id":"2","audio_ssrc":43,"video_ssrc":50,"rtx_ssrc":51,
            "streams":[{"type":"video","rid":"100","ssrc":50,"active":true,"quality":100,"rtx_ssrc":51}]}})).await;
        let picture = keyframe(64, 64);
        let mut transport = Encryption::new(&[7; 32]);
        let mut sequence = 100u16;
        let mut timestamp = 9_000u32;
        let mut wanted_tx = Some(wanted_tx);
        // One keyframe every 100 ms until the test ends (the socket closes), while
        // answering heartbeats and noting the request for video.
        loop {
            let encrypted = bob.session.encrypt(davey::MediaType::VIDEO, davey::Codec::H264, &picture).unwrap();
            for packet in crate::video::packetize(&encrypted, &mut sequence, timestamp, 50).unwrap() {
                let sealed = transport.seal(&packet.header, &packet.payload).unwrap();
                let _ = udp.send_to(&sealed, client).await;
            }
            timestamp = timestamp.wrapping_add(9_000);
            match timeout(Duration::from_millis(100), ws.next()).await {
                Ok(Some(Ok(Message::Text(frame)))) => {
                    let value: Value = serde_json::from_str(&frame).unwrap();
                    if value["op"] == 3 {
                        text(&mut ws, json!({"op":6,"d":{"t":value["d"]["t"]}})).await;
                    }
                    if value["op"] == 15 && let Some(tx) = wanted_tx.take() {
                        assert_eq!(value["d"]["any"], 100);
                        let _ = tx.send(());
                    }
                }
                Ok(Some(Ok(_))) | Err(_) => {}
                Ok(_) => break,
            }
        }
    });
    let (_capture_tx, capture) = std::sync::mpsc::sync_channel(8);
    let (playback, _playback_rx) = std::sync::mpsc::sync_channel(8);
    let (control_tx, control_rx) = watch::channel(Controls::default());
    let feeds: Arc<crate::CameraFeeds> = Arc::default();
    let task = tokio::spawn(run(
        local_credentials(3),
        format!("ws://{address}"),
        capture,
        playback,
        control_rx,
        |_| {},
        crate::crypto::Identity::generate(),
        Arc::default(),
        std::sync::mpsc::channel().1,
        feeds.clone(),
        true,
    ));
    let frame = timeout(Duration::from_secs(15), async {
        loop {
            if let Some(frame) = feeds.latest(2) {
                break frame;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
    })
    .await
    .expect("bob's camera picture arrives");
    assert_eq!((frame.width, frame.height), (64, 64));
    assert_eq!(feeds.users(), vec![2]);
    timeout(Duration::from_secs(5), wanted_rx).await.expect("video was asked for").unwrap();
    drop(control_tx);
    let _ = timeout(Duration::from_secs(5), task).await;
    server.abort();
}

/// RustCord: your camera, end to end. The client is handed a camera source (encoded H.264
/// pictures), announces it (opcode 12 with the SSRCs the server assigned at Ready) and
/// sends it; "bob" on the loopback server reassembles the RTP, decrypts it with DAVE and
/// gets the keyframe back.
#[tokio::test]
async fn our_camera_is_announced_encrypted_and_sent() {
    use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
    fn keyframe(width: usize, height: usize) -> Vec<u8> {
        use openh264::{
            OpenH264API,
            encoder::{Encoder, EncoderConfig},
            formats::YUVBuffer,
        };
        let mut encoder = Encoder::with_api_config(OpenH264API::from_source(), EncoderConfig::new()).unwrap();
        let mut data = Vec::new();
        encoder.encode(&YUVBuffer::new(width, height)).unwrap().write_vec(&mut data);
        data
    }
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let (seen_tx, seen_rx) = tokio::sync::oneshot::channel::<(Value, bool)>();
    let server = tokio::spawn(async move {
        let (tcp, _) = listener.accept().await.unwrap();
        let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
        let identify: Value = serde_json::from_str(ws.next().await.unwrap().unwrap().to_text().unwrap()).unwrap();
        assert_eq!(identify["d"]["streams"][0]["type"], "video");
        // Hello, then Ready with a video stream's SSRCs, and UDP discovery.
        let port = udp.local_addr().unwrap().port();
        text(&mut ws, json!({"op":8,"d":{"heartbeat_interval":5000}})).await;
        text(&mut ws, json!({"op":2,"d":{"ssrc":42,"ip":"127.0.0.1","port":port,"modes":[MODE],
            "streams":[{"type":"video","rid":"100","ssrc":60,"rtx_ssrc":61,"active":false,"quality":100}]}})).await;
        let mut probe = [0; 4096];
        let (n, client) = udp.recv_from(&mut probe).await.unwrap();
        assert_eq!(n, 74);
        probe[..4].copy_from_slice(&[0, 2, 0, 70]);
        probe[8..17].copy_from_slice(b"127.0.0.1");
        probe[72..74].copy_from_slice(&client.port().to_be_bytes());
        udp.send_to(&probe[..74], client).await.unwrap();
        let select = expect_op(&mut ws, 1).await;
        assert_eq!(select["d"]["codecs"][1]["name"], "H264");
        let delivery = Delivery::new();
        let mut bob = Dave::new(2, Some(1), 3).unwrap();
        bob.session.set_external_sender(&delivery.external).unwrap();
        let mut external = vec![0, 1, 25];
        external.extend(&delivery.external);
        ws.send(Message::Binary(external.into())).await.unwrap();
        text(&mut ws, json!({"op":4,"d":{"mode":MODE,"secret_key":vec![7;32],"dave_protocol_version":1}})).await;
        text(&mut ws, json!({"op":11,"d":{"user_ids":["1","2"]}})).await;
        let package = loop {
            match ws.next().await.unwrap().unwrap() {
                Message::Binary(bytes) => break bytes,
                Message::Text(frame) => {
                    let value: Value = serde_json::from_str(&frame).unwrap();
                    if value["op"] == 3 {
                        text(&mut ws, json!({"op":6,"d":{"t":value["d"]["t"]}})).await;
                    }
                }
                _ => panic!("unexpected test client frame"),
            }
        };
        let (commit, welcome) = delivery.add(&mut bob, &package);
        let mut committed = vec![0, 0];
        committed.extend(commit);
        bob.group_changed(29, &committed).unwrap();
        let mut welcome_frame = vec![0, 2, 30, 0, 0];
        welcome_frame.extend(welcome);
        ws.send(Message::Binary(welcome_frame.into())).await.unwrap();
        // The announcement, then the media.
        let transport = Encryption::new(&[7; 32]);
        let mut receivers = crate::video_receive::Receivers::default();
        receivers.announce(1, 60).unwrap();
        let mut announcement: Option<Value> = None;
        let mut packet = [0u8; 4096];
        let mut seen_tx = Some(seen_tx);
        loop {
            tokio::select! {
                event = ws.next() => {
                    let Some(Ok(event)) = event else { break };
                    let Message::Text(frame) = event else { continue };
                    let value: Value = serde_json::from_str(&frame).unwrap();
                    if value["op"] == 3 {
                        text(&mut ws, json!({"op":6,"d":{"t":value["d"]["t"]}})).await;
                    }
                    if value["op"] == 12 && value["d"]["video_ssrc"] == 60 {
                        announcement = Some(value["d"].clone());
                    }
                }
                received = udp.recv_from(&mut packet) => {
                    let (length, _) = received.unwrap();
                    let Some(rtp) = transport.open(&packet[..length]) else { continue };
                    if rtp.payload_type != crate::crypto::H264_PAYLOAD_TYPE || rtp.ssrc != 60 {
                        continue;
                    }
                    // Video never leaves before it is announced.
                    let announced = announcement.clone().expect("camera media before its announcement");
                    let Some(picture) = receivers.push_timed(rtp.ssrc, rtp.sequence, rtp.timestamp, rtp.marker, &rtp.payload) else { continue };
                    let Ok(clear) = bob.session.decrypt(1, davey::MediaType::VIDEO, &picture.data) else { continue };
                    if let Some(tx) = seen_tx.take() {
                        let _ = tx.send((announced, crate::video_codec::is_keyframe(&clear)));
                    }
                }
            }
        }
    });
    let (_capture_tx, capture) = std::sync::mpsc::sync_channel(8);
    let (playback, _playback_rx) = std::sync::mpsc::sync_channel(8);
    let (control_tx, control_rx) = watch::channel(Controls::default());
    let (camera_tx, camera_rx) = std::sync::mpsc::channel();
    // A stand-in for the capture worker: a keyframe every 50 ms while the call says "ready".
    let (frames_tx, frames) = tokio::sync::mpsc::channel(3);
    let ready = Arc::new(AtomicBool::new(false));
    let settings = crate::screen::Settings {
        source: crate::screen::SourceId::Camera(1),
        width: 64,
        height: 64,
        fps: 30,
        cursor: false,
        audio: false,
    };
    let video = crate::screen::Video {
        settings,
        frames,
        ready: ready.clone(),
        keyframe: Arc::new(AtomicBool::new(true)),
        bitrate: Arc::new(AtomicU32::new(settings.bit_rate())),
        audio: None,
        audio_epoch: Arc::new(AtomicU64::new(0)),
        failure: Arc::default(),
        stats: Arc::default(),
    };
    camera_tx.send(Some(video)).unwrap();
    let feeder = tokio::spawn(async move {
        let picture = keyframe(64, 64);
        let mut timestamp = 0u32;
        loop {
            tokio::time::sleep(Duration::from_millis(50)).await;
            if ready.load(Ordering::Acquire) {
                timestamp = timestamp.wrapping_add(4_500);
                if frames_tx.try_send(crate::screen::EncodedFrame { data: picture.clone(), timestamp, keyframe: true }).is_err() && frames_tx.is_closed() {
                    break;
                }
            }
        }
    });
    let task = tokio::spawn(run(
        local_credentials(3),
        format!("ws://{address}"),
        capture,
        playback,
        control_rx,
        |_| {},
        crate::crypto::Identity::generate(),
        Arc::default(),
        camera_rx,
        Arc::default(),
        true,
    ));
    let (announced, keyframe_arrived) = timeout(Duration::from_secs(15), seen_rx).await.expect("the camera picture arrives").unwrap();
    assert!(keyframe_arrived);
    assert_eq!(announced["audio_ssrc"], 42);
    assert_eq!(announced["rtx_ssrc"], 61);
    assert_eq!(announced["streams"][0]["active"], true);
    assert_eq!(announced["streams"][0]["max_resolution"]["width"], 64);
    drop(control_tx);
    drop(camera_tx);
    let _ = timeout(Duration::from_secs(5), task).await;
    feeder.abort();
    server.abort();
}