nandi/jolt-nativepublic Fork 0
3cfee15a9d938584f526f606f853771eaad7f56c
Commits
Clone
git clone https://git.rickub.com/nandi/jolt-native.git
git clone ssh://git@rickub.com/nandi/jolt-native.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Let the media plane cross to the phone, camera and all fd0e21a · on 3cfee15a9d938584f526f606f853771eaad7f56c · nandi · 18d ago
lib.rs · 996 lines · 37.0 KBRust Blame HistoryRaw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
//! freeq's AV media plane, for callers that are not Rust.
//!
//! sleek reaches its calls by calling Rust from Rust. A client written in
//! anything else cannot, and this is not a plane to write twice: MoQ over
//! QUIC, Opus, H.264, camera capture and the SFU's own dial rules come to some
//! three thousand lines that would say exactly the same thing again in another
//! language, and be wrong in different places.
//!
//! So it was lifted out of sleek to here, and what crosses the boundary is
//! only what jolt can hold: integers, doubles, borrowed UTF-8 strings, and one
//! borrowed pixel pointer.
//!
//! # What is not here
//!
//! **Signaling.** A freeq call is opened, joined and left over IRC TAGMSGs —
//! `+freeq.at/av-start` and its siblings — and the server answers with
//! `+freeq.at/av-state`. Any client that can speak IRC already has everything
//! it needs for that, in whatever language it speaks IRC in; crossing an FFI
//! boundary to send a TAGMSG would be worse than not. This library begins once
//! the session id and the SFU token are known, and ends when the call does.
//!
//! # The shape of it
//!
//! **Nothing calls back.** Status arrives through [`joltmoq_poll_status`],
//! video through [`joltmoq_frame_poll`], both drained from whatever thread the
//! caller paints on — see [`jolt_abi`] for why.
//!
//! **One call at a time.** There is one microphone, so there is one session,
//! held in a global. A handle would imply a second call could run beside the
//! first, which is not something the hardware or the person would enjoy.
//!
//! **Frames are borrowed, not copied.** [`joltmoq_frame_rgba`] hands out a
//! pointer into the decoder's own buffer, good until the next poll. A frame is
//! a megabyte or two; copying it out so the caller can hand it straight to a
//! texture upload would be two copies a frame to no end.

pub mod av;
pub mod av_media;
// Pure arithmetic on planes, so it builds and is tested everywhere even though
// only the Android camera path calls it — a rotate is easier to get wrong than
// to test, and a desktop `cargo test` is where that gets caught.
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
mod nv12_orient;
// V4L2 is Linux's camera interface and the phone does not offer it; there the
// camera is Java, reached through the two modules below.
#[cfg(not(target_os = "android"))]
mod v4l2cam;
#[cfg(target_os = "android")]
mod android_camera;
#[cfg(target_os = "android")]
mod android_jni;

use std::collections::HashMap;
use std::ffi::{c_char, c_int};
use std::sync::{Mutex, OnceLock};

use jolt_abi::{borrowed, empty_str, guard, preference, Scratch};

use av::{RgbaVideoFrame, VideoFrameStore};
use av_media::{AvMediaConfig, AvMediaSession, AvMediaUpdate};

/// One scratch per family of string-returning calls, so that asking for the
/// video keys does not invalidate a device list the caller is still reading.
static STATUS_TEXT: Scratch = Scratch::new();
static FRAME_KEY: Scratch = Scratch::new();
static VIDEO_KEYS: Scratch = Scratch::new();
static DEVICES: Scratch = Scratch::new();
static DIAL: Scratch = Scratch::new();

// ── The one session ─────────────────────────────────────────────────────────

/// Everything a live call holds on this side.
#[derive(Default)]
struct Slot {
    session: Option<AvMediaSession>,
    /// Which session the statuses below belong to.
    ///
    /// Tearing a call down is spawned rather than waited for, so the task of a
    /// call that has ended outlives the call — and finishes, and reports that
    /// it ended, possibly after the *next* call has started. Without a way to
    /// tell whose news this is, the old session's dying breath tears down the
    /// new one, which is exactly what rejoining a call did.
    ///
    /// Bumped on every start and every stop, so anything a departed session
    /// still has to say is discarded rather than acted on.
    generation: u64,
    /// Status updates from the media task, waiting to be polled, each with the
    /// generation it was produced under.
    status: Vec<(u64, Status)>,
    /// The status most recently handed out, whose fields the accessors read.
    current: Option<Status>,
    /// The live session's frame store, and the generation last handed out per
    /// feed — which is how a poll knows what is new.
    video: Option<VideoFrameStore>,
    seen: HashMap<String, u64>,
    /// The frame most recently handed out. Held so that the pixel pointer the
    /// caller was given stays alive until the next poll replaces it.
    frame: Option<(String, RgbaVideoFrame)>,
}

#[derive(Clone)]
enum Status {
    Live { has_camera: bool, has_mic: bool },
    Ended,
    Failed(String),
}

fn session_slot() -> &'static Mutex<Slot> {
    static SLOT: OnceLock<Mutex<Slot>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(Slot::default()))
}

/// A tokio runtime of our own: the caller has no reactor to lend us.
///
/// Deliberately *not* in the slot. Tearing a call down needs the runtime and
/// must not be holding the slot lock while it does — see [`joltmoq_stop`].
/// Made once and kept, since building one per call would tear worker threads
/// down and up again on every join.
fn runtime() -> Option<&'static tokio::runtime::Runtime> {
    static RUNTIME: OnceLock<Option<tokio::runtime::Runtime>> = OnceLock::new();
    RUNTIME
        .get_or_init(|| {
            tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .thread_name("joltmoq")
                .build()
                .map_err(|e| log::error!("joltmoq: no runtime: {e}"))
                .ok()
        })
        .as_ref()
}

/// Run `f` against the one session, catching panics on the way out.
///
/// `fallback` answers both a panic and a poisoned lock, and is deliberately
/// taken by value rather than requiring `Copy`: the answer is sometimes a
/// `String`. The `Option` is how one value serves both arms without being
/// moved twice.
fn with_slot<R>(fallback: R, f: impl FnOnce(&mut Slot) -> R) -> R {
    guard(None, || match session_slot().lock() {
        Ok(mut slot) => Some(f(&mut slot)),
        Err(_) => None,
    })
    .unwrap_or(fallback)
}

// ── Lifecycle ───────────────────────────────────────────────────────────────

/// Hand over the phone's `JavaVM` and Activity. Android only, and required
/// there before a call with a camera in it can start.
///
/// The camera on Android is Java, and this library cannot reach the handles a
/// JNI call needs: `android-activity`'s glue receives them, and the glue is in
/// `libvidya.so`. So the glue in `android/jolt_main.c` — which links both
/// objects — reads them out of libvidya's C ABI and passes them here, once,
/// before Jolt starts. See `android_jni` for why `ndk_context` cannot do this.
///
/// Everything else works without it. Only the camera calls fail, and they say
/// which call was missed rather than crashing.
///
/// # Safety
/// `vm` is the process's `JavaVM` and `activity` a global reference to the
/// running Activity, both live for the rest of the process — which is what
/// `vidya_android_vm` and `vidya_android_activity` return.
#[cfg(target_os = "android")]
#[no_mangle]
pub unsafe extern "C" fn joltmoq_android_init(
    vm: *mut std::ffi::c_void,
    activity: *mut std::ffi::c_void,
) {
    guard((), || {
        if vm.is_null() || activity.is_null() {
            log::error!("joltmoq_android_init: null JavaVM or Activity; camera will not open");
            return;
        }
        // SAFETY: the caller's contract, restated on this function.
        unsafe { android_jni::set(vm.cast(), activity.cast()) };
        log::info!("joltmoq: Android JNI handles received");
    })
}

/// Turn on logging to stderr, honouring `RUST_LOG`. Safe to call twice.
///
/// Worth calling first while a call refuses to connect: the media plane says a
/// great deal about why, and says none of it otherwise.
#[no_mangle]
pub extern "C" fn joltmoq_init_logging() {
    guard((), || {
        let _ = env_logger::try_init();
    })
}

/// Join the call at `sfu_url` as `nick`, answering 1 when the media task
/// started.
///
/// `sfu_url` is what [`joltmoq_sfu_url`] built, `session_id` is the id the
/// server broadcast in `+freeq.at/av-id`, and `instance` is the per-device id
/// the caller put in its own `av-join` — two devices signed in as the same
/// person need different ones or their broadcast paths collide and each
/// unpublishes the other.
///
/// The rest are pre-call preferences: `muted`, `speaker_muted` and `camera` as
/// 0 or 1, then three device preferences, each an empty string for "whatever
/// the system uses".
///
/// This returns as soon as the task is spawned. Connecting takes a moment, and
/// it is [`joltmoq_poll_status`] that says whether it worked. Starting a second
/// call while one is live is refused; stop the first.
///
/// # Safety
/// Every pointer is null or a NUL-terminated UTF-8 string.
#[no_mangle]
#[allow(clippy::too_many_arguments)]
pub unsafe extern "C" fn joltmoq_start(
    sfu_url: *const c_char,
    session_id: *const c_char,
    nick: *const c_char,
    instance: *const c_char,
    muted: c_int,
    speaker_muted: c_int,
    camera: c_int,
    camera_id: *const c_char,
    mic_id: *const c_char,
    speaker_id: *const c_char,
) -> c_int {
    let sfu_url = borrowed(sfu_url);
    let session_id = borrowed(session_id);
    let nick = borrowed(nick);
    let instance = borrowed(instance);
    let camera_id = preference(borrowed(camera_id));
    let mic_id = preference(borrowed(mic_id));
    let speaker_id = preference(borrowed(speaker_id));

    let Some(runtime) = runtime() else {
        return 0;
    };

    with_slot(0, |slot| {
        if slot.session.is_some() {
            log::warn!("joltmoq: a call is already live; stop it first");
            return 0;
        }
        let Ok(url) = url::Url::parse(&sfu_url) else {
            log::warn!("joltmoq: not a URL: {sfu_url}");
            return 0;
        };

        let config = AvMediaConfig {
            sfu_url: url,
            session_id,
            nick,
            instance,
            muted: muted != 0,
            speaker_muted: speaker_muted != 0,
            camera_enabled: camera != 0,
            camera_id,
            mic_id,
            speaker_id,
        };

        // `AvMediaSession::start` spawns onto the ambient runtime, so it has to
        // be entered. The status closure it takes runs on a worker thread,
        // which is why all it does is push onto a queue the caller drains.
        slot.generation = slot.generation.wrapping_add(1);
        let generation = slot.generation;

        let _entered = runtime.enter();
        let session = AvMediaSession::start(config, move |update| {
            let status = match update {
                AvMediaUpdate::Live {
                    has_camera,
                    has_mic,
                    ..
                } => Status::Live {
                    has_camera,
                    has_mic,
                },
                AvMediaUpdate::Ended => Status::Ended,
                AvMediaUpdate::Failed(e) => Status::Failed(e),
            };
            if let Ok(mut slot) = session_slot().lock() {
                // Dropped on the floor if this session is no longer the
                // current one — see `Slot::generation`.
                if slot.generation == generation {
                    slot.status.push((generation, status));
                }
            }
        });

        slot.video = Some(session.video.clone());
        slot.session = Some(session);
        slot.seen.clear();
        slot.frame = None;
        1
    })
}

/// Leave the call: unpublish, drop the devices, forget the frames.
///
/// Waits briefly for the media task to tear MoQ down rather than aborting it
/// outright. An abandoned broadcast lingers on the SFU and peers subscribe to
/// it, so they see someone present and hear silence.
#[no_mangle]
pub extern "C" fn joltmoq_stop() {
    // Take the session out from under the lock and let the lock go *before*
    // anything waits on it.
    //
    // Waiting while holding it deadlocks, and did: the status callback locks
    // this same slot from a tokio worker, so a task that still had an update
    // to deliver could not finish, while the thread that would have released
    // the lock was waiting for exactly that task to finish. The caller's UI
    // thread is the one that hangs, which is every thread it has.
    let session = with_slot(None, |slot| {
        slot.video = None;
        slot.seen.clear();
        slot.frame = None;
        // Nothing this session says from here on is about the call the caller
        // is in, because it is not in one — and may be in a different one by
        // the time the task gets round to saying it.
        slot.generation = slot.generation.wrapping_add(1);
        slot.status.clear();
        slot.current = None;
        slot.session.take()
    });
    let Some(mut session) = session else {
        return;
    };

    // Not waited for either. Tearing MoQ down is a network round trip, and the
    // press that asked for it was on the thread that paints — half a second of
    // frozen window is not the answer to "leave". The teardown still runs, and
    // still unpublishes properly: an abandoned broadcast lingers on the SFU and
    // peers subscribe to it, seeing someone present who is silent.
    match runtime() {
        Some(runtime) => {
            runtime.spawn(async move {
                session
                    .stop_and_wait(std::time::Duration::from_secs(2))
                    .await;
            });
        }
        // No runtime means no call ever started; nothing to unwind gracefully.
        None => session.stop(),
    }
}

/// 1 while a call is live on this side.
#[no_mangle]
pub extern "C" fn joltmoq_is_live() -> c_int {
    with_slot(0, |slot| slot.session.is_some() as c_int)
}

// ── Controls ────────────────────────────────────────────────────────────────

/// Mute or unmute the microphone. Peers stop hearing you; you still hear them.
#[no_mangle]
pub extern "C" fn joltmoq_set_muted(muted: c_int) {
    with_slot((), |slot| {
        if let Some(s) = &slot.session {
            s.set_muted(muted != 0);
        }
    })
}

/// Mute or unmute remote audio — deafen. Deliberately not the same control as
/// [`joltmoq_set_muted`]: peers still hear you if the microphone is open.
#[no_mangle]
pub extern "C" fn joltmoq_set_speaker_muted(muted: c_int) {
    with_slot((), |slot| {
        if let Some(s) = &slot.session {
            s.set_speaker_muted(muted != 0);
        }
    })
}

/// Start or stop publishing camera. The device is only held while publishing,
/// so turning it off gives the hardware back to the rest of the machine.
#[no_mangle]
pub extern "C" fn joltmoq_set_camera(enabled: c_int) {
    with_slot((), |slot| {
        if let Some(s) = &slot.session {
            s.set_camera_enabled(enabled != 0);
        }
    })
}

/// Re-open the camera by id; an empty string means the first available.
///
/// # Safety
/// `id` is null or a NUL-terminated UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn joltmoq_set_camera_device(id: *const c_char) {
    let id = preference(borrowed(id));
    with_slot((), |slot| {
        if let Some(s) = &slot.session {
            s.set_camera_device(id);
        }
    })
}

/// Switch microphone by name; an empty string means the system default.
///
/// # Safety
/// `id` is null or a NUL-terminated UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn joltmoq_set_mic_device(id: *const c_char) {
    let id = preference(borrowed(id));
    with_slot((), |slot| {
        if let Some(s) = &slot.session {
            s.set_mic_device(id);
        }
    })
}

/// Switch speaker by name; an empty string means the system default.
///
/// # Safety
/// `id` is null or a NUL-terminated UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn joltmoq_set_speaker_device(id: *const c_char) {
    let id = preference(borrowed(id));
    with_slot((), |slot| {
        if let Some(s) = &slot.session {
            s.set_speaker_device(id);
        }
    })
}

/// The live microphone envelope, 0.0 to 1.0 — what a level meter draws. 0 when
/// no call is up.
#[no_mangle]
pub extern "C" fn joltmoq_mic_level() -> f64 {
    with_slot(0.0, |slot| {
        slot.session
            .as_ref()
            .map_or(0.0, |s| s.mic_level.get() as f64)
    })
}

// ── Status ──────────────────────────────────────────────────────────────────

/// Nothing waiting.
pub const JOLTMOQ_STATUS_NONE: c_int = 0;
/// Connected and publishing.
pub const JOLTMOQ_STATUS_LIVE: c_int = 1;
/// The session ended cleanly.
pub const JOLTMOQ_STATUS_ENDED: c_int = 2;
/// Connect or runtime failure; [`joltmoq_status_text`] says what.
pub const JOLTMOQ_STATUS_FAILED: c_int = 3;

/// Dequeue one status update, or 0 when there is none.
///
/// The media task produces these on its own threads; this hands them to the
/// caller's. Drain it until it answers 0 wherever the caller polls — beside a
/// repaint is the natural place. Missing an update means a call that is up
/// still looks like it is connecting.
#[no_mangle]
pub extern "C" fn joltmoq_poll_status() -> c_int {
    with_slot(JOLTMOQ_STATUS_NONE, |slot| {
        // Drop anything a replaced session left behind, rather than stopping
        // at it: answering NONE on a stale entry would strand every fresh one
        // queued behind it.
        let current = slot.generation;
        slot.status.retain(|(generation, _)| *generation == current);
        if slot.status.is_empty() {
            slot.current = None;
            return JOLTMOQ_STATUS_NONE;
        }
        let (_, status) = slot.status.remove(0);
        let code = match &status {
            Status::Live { .. } => JOLTMOQ_STATUS_LIVE,
            Status::Ended => JOLTMOQ_STATUS_ENDED,
            Status::Failed(_) => JOLTMOQ_STATUS_FAILED,
        };
        slot.current = Some(status);
        code
    })
}

/// Why the last polled status failed; the empty string for any other status.
///
/// # Safety
/// The returned pointer is valid until the next call to this function.
#[no_mangle]
pub extern "C" fn joltmoq_status_text() -> *const c_char {
    let text = with_slot(String::new(), |slot| match &slot.current {
        Some(Status::Failed(e)) => e.clone(),
        _ => String::new(),
    });
    if text.is_empty() {
        return empty_str();
    }
    STATUS_TEXT.lend(text)
}

/// 1 when the last polled `live` status found a capture device for this call.
///
/// A call can be live with no camera at all, so a caller shows a camera control
/// only when there is something for it to turn on.
#[no_mangle]
pub extern "C" fn joltmoq_status_has_camera() -> c_int {
    with_slot(0, |slot| match &slot.current {
        Some(Status::Live { has_camera, .. }) => *has_camera as c_int,
        _ => 0,
    })
}

/// 1 when the last polled `live` status had a real microphone feeding the
/// outbound track. 0 means listen-only: audio is still published, as silence.
#[no_mangle]
pub extern "C" fn joltmoq_status_has_mic() -> c_int {
    with_slot(0, |slot| match &slot.current {
        Some(Status::Live { has_mic, .. }) => *has_mic as c_int,
        _ => 0,
    })
}

// ── Video ───────────────────────────────────────────────────────────────────

/// Advance to the next feed carrying a frame the caller has not been given,
/// answering 1 while there was one.
///
/// Loop until it answers 0, reading [`joltmoq_frame_key`],
/// [`joltmoq_frame_width`], [`joltmoq_frame_height`] and
/// [`joltmoq_frame_rgba`] for each and handing those to whatever paints. Only
/// what changed comes over: a participant sitting still costs nothing, and a
/// decoder running ahead of the window is coalesced to its newest frame rather
/// than queued behind stale ones.
///
/// The key is the participant's nick, or `__local__` for the self-view.
#[no_mangle]
pub extern "C" fn joltmoq_frame_poll() -> c_int {
    with_slot(0, |slot| {
        slot.frame = None;
        let Some(video) = slot.video.clone() else {
            return 0;
        };
        let snapshot = video.snapshot();
        for (key, frame) in &snapshot {
            if slot.seen.get(key) == Some(&frame.gen) {
                continue;
            }
            slot.seen.insert(key.clone(), frame.gen);
            slot.frame = Some((key.clone(), frame.clone()));
            return 1;
        }
        // Nothing new. Forget the keys nobody is publishing any more, so that
        // if they come back the first frame of the new stream reads as new
        // rather than as one already seen.
        slot.seen
            .retain(|k, _| snapshot.iter().any(|(live, _)| live == k));
        0
    })
}

/// Whose picture the last polled frame is: a nick, or `__local__`.
///
/// # Safety
/// The returned pointer is valid until the next call to this function.
#[no_mangle]
pub extern "C" fn joltmoq_frame_key() -> *const c_char {
    let key = with_slot(String::new(), |slot| {
        slot.frame
            .as_ref()
            .map_or(String::new(), |(k, _)| k.clone())
    });
    if key.is_empty() {
        return empty_str();
    }
    FRAME_KEY.lend(key)
}

/// The last polled frame's width in pixels, or 0.
#[no_mangle]
pub extern "C" fn joltmoq_frame_width() -> c_int {
    with_slot(0, |slot| {
        slot.frame.as_ref().map_or(0, |(_, f)| f.width as c_int)
    })
}

/// The last polled frame's height in pixels, or 0.
#[no_mangle]
pub extern "C" fn joltmoq_frame_height() -> c_int {
    with_slot(0, |slot| {
        slot.frame.as_ref().map_or(0, |(_, f)| f.height as c_int)
    })
}

/// The last polled frame's pixels: `width * height * 4` bytes, row-major, 8
/// bits a channel, un-premultiplied and opaque. Null when there is no frame.
///
/// **Borrowed, and only until the next [`joltmoq_frame_poll`].** That is the
/// point of polling: a frame is a megabyte or two, and copying it into the
/// caller's memory so it can hand it straight to a texture upload would be two
/// copies a frame for nothing. Upload it, then poll again.
///
/// # Safety
/// Valid for reads of `width * height * 4` bytes until the next call to
/// [`joltmoq_frame_poll`] or [`joltmoq_stop`].
#[no_mangle]
pub extern "C" fn joltmoq_frame_rgba() -> *const u8 {
    with_slot(std::ptr::null(), |slot| match &slot.frame {
        Some((_, frame)) => frame.rgba.as_ptr(),
        None => std::ptr::null(),
    })
}

/// Everyone whose picture the call is currently carrying, one key a line.
///
/// A caller painting a tile per feed uses this to notice a tile it should stop
/// painting: someone who left stops appearing here, while their last frame
/// would otherwise hang on the wall for the rest of the call.
///
/// # Safety
/// The returned pointer is valid until the next call to this function.
#[no_mangle]
pub extern "C" fn joltmoq_video_keys() -> *const c_char {
    let keys = with_slot(String::new(), |slot| match &slot.video {
        Some(video) => {
            let mut keys: Vec<String> = video.snapshot().into_iter().map(|(k, _)| k).collect();
            keys.sort();
            keys.join("\n")
        }
        None => String::new(),
    });
    if keys.is_empty() {
        return empty_str();
    }
    VIDEO_KEYS.lend(keys)
}

// ── Devices ─────────────────────────────────────────────────────────────────

/// The cameras, one a line, each `id\tname\tdefault`.
///
/// Enumerating opens nothing, so this is safe to ask before a call and during
/// one. Empty on a machine with no camera, which is a normal answer.
///
/// # Safety
/// The returned pointer is valid until the next device-listing call.
#[no_mangle]
pub extern "C" fn joltmoq_cameras() -> *const c_char {
    lend_devices(guard(Vec::new(), av_media::list_cameras))
}

/// The microphones, one a line, each `id\tname\tdefault`.
///
/// # Safety
/// The returned pointer is valid until the next device-listing call.
#[no_mangle]
pub extern "C" fn joltmoq_microphones() -> *const c_char {
    lend_devices(guard(Vec::new(), av_media::list_microphones))
}

/// The speakers, one a line, each `id\tname\tdefault`.
///
/// # Safety
/// The returned pointer is valid until the next device-listing call.
#[no_mangle]
pub extern "C" fn joltmoq_speakers() -> *const c_char {
    lend_devices(guard(Vec::new(), av_media::list_speakers))
}

fn lend_devices(list: Vec<av_media::MediaDevice>) -> *const c_char {
    let rendered = devices(list);
    if rendered.is_empty() {
        return empty_str();
    }
    DEVICES.lend(rendered)
}

/// A device list as lines of `id\tname\tdefault`, where the last column is 1
/// for the system default and 0 otherwise.
///
/// Tab and newline are the delimiters because a device name may contain
/// anything else — "EMEET SmartCam C960, Mono" has spaces and a comma in it,
/// and a caller splitting on those gets nonsense. A name that somehow holds a
/// delimiter has it replaced rather than being allowed to forge a row.
///
/// The default is worth a column of its own: a picker that cannot mark it has
/// to guess, and "Default" is not reliably the first entry or a name anyone
/// can match on.
fn devices(list: Vec<av_media::MediaDevice>) -> String {
    list.into_iter()
        .map(|d| {
            format!(
                "{}\t{}\t{}",
                d.id.replace(['\t', '\n'], " "),
                d.name.replace(['\t', '\n'], " "),
                d.is_default as u8
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

// ── Dialling ────────────────────────────────────────────────────────────────

/// The SFU URL to hand [`joltmoq_start`], built from the IRC server the caller
/// is connected to and the JWT the server minted in `+freeq.at/av-token`.
///
/// `server` is whatever the client knows the server as — `irc.freeq.at:6697`,
/// `wss://irc.freeq.at/irc` — and both become `https://irc.freeq.at/av/moq`.
/// `jwt` and `instance` may be empty. The empty string comes back when the
/// server is not something a URL can be made of.
///
/// This lives here rather than in the caller because the rules are fiddly and
/// already tested on this side: which scheme maps to which, where the port
/// goes, and what to do with a path that was there.
///
/// # Safety
/// Every pointer is null or a NUL-terminated UTF-8 string; the returned pointer
/// is valid until the next call to this function.
#[no_mangle]
pub unsafe extern "C" fn joltmoq_sfu_url(
    server: *const c_char,
    jwt: *const c_char,
    instance: *const c_char,
) -> *const c_char {
    let server = borrowed(server);
    let jwt = preference(borrowed(jwt));
    let instance = preference(borrowed(instance));
    let url = guard(String::new(), || {
        av::sfu_moq_dial_url(&server, jwt.as_deref(), instance.as_deref())
            .map(|u| u.to_string())
            .unwrap_or_default()
    });
    if url.is_empty() {
        return empty_str();
    }
    DIAL.lend(url)
}

/// 1 when dialling this server is worth attempting.
///
/// A remote SFU with no token accepts the connection and closes it, and
/// moq-lite then retries in a tight loop that looks, from the outside, exactly
/// like a hang. Asking first is cheaper than explaining that.
///
/// # Safety
/// Both pointers are null or NUL-terminated UTF-8 strings.
#[no_mangle]
pub unsafe extern "C" fn joltmoq_can_dial(server: *const c_char, jwt: *const c_char) -> c_int {
    let server = borrowed(server);
    let jwt = preference(borrowed(jwt));
    guard(0, || av::can_dial_sfu(&server, jwt.as_deref()) as c_int)
}

/// A per-device call instance id — eight hex characters.
///
/// Two devices signed in as the same person need different ones, or their MoQ
/// broadcast paths collide and each unpublishes the other. The caller puts this
/// in its own `+freeq.at/av-instance` tag and hands the same one to
/// [`joltmoq_start`].
///
/// # Safety
/// The returned pointer is valid until the next call to this function.
#[no_mangle]
pub extern "C" fn joltmoq_new_instance() -> *const c_char {
    DIAL.lend(guard("00000000".to_owned(), || {
        format!("{:08x}", rand::random::<u32>())
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::{CStr, CString};

    fn read(ptr: *const c_char) -> String {
        unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned()
    }

    /// There is one session in this library, so there is one in its tests, and
    /// cargo runs them in parallel. Anything touching the global slot takes
    /// this first; without it a test asserting "nothing is live" fails because
    /// another was mid-call at the time.
    static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());

    fn exclusive() -> std::sync::MutexGuard<'static, ()> {
        // A test that panicked while holding it poisoned it; that is the
        // failure being reported, not a reason to fail every test after it.
        ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner())
    }

    #[test]
    fn a_device_list_is_tab_and_newline_delimited() {
        let list = vec![
            av_media::MediaDevice {
                id: "/dev/video0".to_owned(),
                name: "EMEET SmartCam C960, Mono".to_owned(),
                is_default: true,
            },
            av_media::MediaDevice {
                id: "/dev/video2".to_owned(),
                name: "Integrated".to_owned(),
                is_default: false,
            },
        ];
        assert_eq!(
            devices(list),
            "/dev/video0\tEMEET SmartCam C960, Mono\t1\n/dev/video2\tIntegrated\t0"
        );
    }

    #[test]
    fn a_name_holding_a_delimiter_cannot_forge_a_row() {
        let list = vec![av_media::MediaDevice {
            id: "a\tb".to_owned(),
            name: "two\nlines".to_owned(),
            is_default: false,
        }];
        let rendered = devices(list);
        assert_eq!(rendered, "a b\ttwo lines\t0");
        assert_eq!(rendered.lines().count(), 1);
    }

    #[test]
    fn the_sfu_url_is_built_from_whatever_the_server_is_known_as() {
        let jwt = CString::new("tok.jwt.value").unwrap();
        let inst = CString::new("abcd1234").unwrap();
        for known_as in ["irc.freeq.at:6697", "wss://irc.freeq.at/irc"] {
            let server = CString::new(known_as).unwrap();
            let url =
                read(unsafe { joltmoq_sfu_url(server.as_ptr(), jwt.as_ptr(), inst.as_ptr()) });
            assert!(url.starts_with("https://irc.freeq.at/av/moq"), "{url}");
            assert!(url.contains("inst=abcd1234"), "{url}");
        }
    }

    #[test]
    fn a_server_that_is_not_a_url_answers_the_empty_string() {
        let server = CString::new(" ").unwrap();
        let url = read(unsafe {
            joltmoq_sfu_url(server.as_ptr(), std::ptr::null(), std::ptr::null())
        });
        assert_eq!(url, "");
    }

    #[test]
    fn a_remote_sfu_without_a_token_is_not_worth_dialling() {
        let remote = CString::new("wss://chat.example.com").unwrap();
        let local = CString::new("ws://localhost:4443").unwrap();
        let jwt = CString::new("tok").unwrap();
        assert_eq!(
            unsafe { joltmoq_can_dial(remote.as_ptr(), std::ptr::null()) },
            0
        );
        assert_eq!(unsafe { joltmoq_can_dial(remote.as_ptr(), jwt.as_ptr()) }, 1);
        assert_eq!(
            unsafe { joltmoq_can_dial(local.as_ptr(), std::ptr::null()) },
            1
        );
    }

    #[test]
    fn an_instance_id_is_eight_hex_characters_and_differs() {
        let one = read(joltmoq_new_instance());
        let two = read(joltmoq_new_instance());
        assert_eq!(one.len(), 8);
        assert!(one.chars().all(|c| c.is_ascii_hexdigit()), "{one}");
        assert_ne!(one, two, "two devices would collide on the SFU");
    }

    #[test]
    fn nothing_is_live_before_a_call_and_every_poll_answers_empty() {
        let _guard = exclusive();
        assert_eq!(joltmoq_is_live(), 0);
        assert_eq!(joltmoq_poll_status(), JOLTMOQ_STATUS_NONE);
        assert_eq!(read(joltmoq_status_text()), "");
        assert_eq!(joltmoq_frame_poll(), 0);
        assert!(joltmoq_frame_rgba().is_null());
        assert_eq!(joltmoq_frame_width(), 0);
        assert_eq!(read(joltmoq_frame_key()), "");
        assert_eq!(read(joltmoq_video_keys()), "");
    }

    #[test]
    fn a_control_with_no_call_under_it_is_inert() {
        let _guard = exclusive();
        // A UI that sends a mute as the call is ending must not take the
        // process with it.
        joltmoq_set_muted(1);
        joltmoq_set_speaker_muted(1);
        joltmoq_set_camera(1);
        unsafe { joltmoq_set_mic_device(std::ptr::null()) };
        joltmoq_stop();
        assert_eq!(joltmoq_mic_level(), 0.0);
        assert_eq!(joltmoq_is_live(), 0);
    }

    #[test]
    fn stopping_does_not_hold_the_lock_a_status_callback_needs() {
        let _guard = exclusive();
        // The deadlock this guards: `stop` used to wait for the media task
        // while holding the slot, and the task's status callback locks the
        // slot to deliver an update — so neither could finish. Here a thread
        // takes the slot the way that callback does, while the main thread
        // stops. If stop waits under the lock, this never returns.
        use std::sync::mpsc;
        use std::time::Duration;

        let (tx, rx) = mpsc::channel();
        std::thread::spawn(move || {
            for _ in 0..200 {
                if let Ok(mut slot) = session_slot().lock() {
                    let generation = slot.generation;
                    slot.status.push((generation, Status::Ended));
                    slot.status.clear();
                }
                std::thread::sleep(Duration::from_millis(1));
            }
            let _ = tx.send(());
        });

        for _ in 0..50 {
            joltmoq_stop();
        }
        assert_eq!(joltmoq_is_live(), 0);
        rx.recv_timeout(Duration::from_secs(10))
            .expect("the status thread never got the lock back");
    }

    #[test]
    fn a_departed_session_cannot_end_the_one_that_replaced_it() {
        let _guard = exclusive();
        // Rejoining a call did exactly this. Teardown is spawned, so the old
        // task finishes after the new call has started, and its "ended" landed
        // in the same queue — where it read as the new call ending.
        if let Ok(mut slot) = session_slot().lock() {
            slot.generation = 7;
            slot.status.clear();
            // The old session (6) signing off, and the live one (7) saying it
            // is up. Queued in that order, which is the order that hurt.
            slot.status.push((6, Status::Ended));
            slot.status.push((
                7,
                Status::Live {
                    has_camera: false,
                    has_mic: true,
                },
            ));
        }

        // The stale "ended" is skipped, not acted on, and not left blocking
        // the fresh one behind it.
        assert_eq!(joltmoq_poll_status(), JOLTMOQ_STATUS_LIVE);
        assert_eq!(joltmoq_status_has_mic(), 1);
        assert_eq!(joltmoq_poll_status(), JOLTMOQ_STATUS_NONE);

        if let Ok(mut slot) = session_slot().lock() {
            slot.generation = 0;
            slot.status.clear();
            slot.current = None;
        }
    }

    #[test]
    fn stopping_makes_the_next_call_a_new_generation() {
        let _guard = exclusive();
        let before = session_slot().lock().map(|s| s.generation).unwrap_or(0);
        joltmoq_stop();
        let after = session_slot().lock().map(|s| s.generation).unwrap_or(0);
        assert_ne!(before, after, "a stopped session must stop being current");
    }

    #[test]
    fn a_frame_poll_yields_each_feed_once_until_it_changes() {
        let _guard = exclusive();
        let video = VideoFrameStore::new();
        video.set("nandi", 1, 1, std::sync::Arc::from(vec![9u8; 4]));
        if let Ok(mut slot) = session_slot().lock() {
            slot.video = Some(video.clone());
            slot.seen.clear();
        }

        assert_eq!(joltmoq_frame_poll(), 1);
        assert_eq!(read(joltmoq_frame_key()), "nandi");
        assert_eq!(joltmoq_frame_width(), 1);
        // Same frame: nothing new to hand over.
        assert_eq!(joltmoq_frame_poll(), 0);

        // A new frame under the same key is new again.
        video.set("nandi", 1, 1, std::sync::Arc::from(vec![3u8; 4]));
        assert_eq!(joltmoq_frame_poll(), 1);
        assert_eq!(read(joltmoq_frame_key()), "nandi");

        assert_eq!(read(joltmoq_video_keys()), "nandi");

        if let Ok(mut slot) = session_slot().lock() {
            slot.video = None;
            slot.seen.clear();
            slot.frame = None;
        }
    }
}