rift-sdk 0.1.4

High-level SDK for building Rift P2P applications
Documentation
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
//! C FFI bindings for the Rift SDK.
//!
//! This module exposes a minimal C ABI for initializing the SDK, joining
//! channels, and receiving events. It is intentionally narrow to keep ABI
//! compatibility manageable.

use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int};
use std::ptr;

use crate::{RiftConfig, RiftEvent, RiftHandle, RiftError, SDK_VERSION, SDK_ABI_VERSION};
use rift_protocol::SessionId;
use rift_core::PeerId;

#[repr(C)]
pub struct RiftHandleC {
    /// Dedicated Tokio runtime for the SDK.
    runtime: tokio::runtime::Runtime,
    /// Rust-side SDK handle.
    handle: RiftHandle,
}

#[repr(C)]
#[derive(Copy, Clone)]
pub struct PeerIdC {
    /// Raw peer id bytes.
    pub bytes: [u8; 32],
}

#[repr(C)]
#[derive(Copy, Clone)]
pub struct SessionIdC {
    /// Raw session id bytes.
    pub bytes: [u8; 32],
}

#[repr(C)]
#[derive(Copy, Clone)]
pub enum RiftEventTag {
    None = 0,
    IncomingChat = 1,
    IncomingCall = 2,
    CallStateChanged = 3,
    PeerJoined = 4,
    PeerLeft = 5,
    AudioLevel = 6,
}

#[repr(C)]
pub struct RiftEventC {
    /// Event type discriminator.
    pub tag: RiftEventTag,
    /// Peer associated with the event.
    pub peer: PeerIdC,
    /// Session associated with the event.
    pub session: SessionIdC,
    /// Audio level (if applicable).
    pub level: f32,
    /// Optional text payload (heap-allocated C string).
    pub text: *mut c_char,
}

#[repr(C)]
pub enum RiftErrorCode {
    Ok = 0,
    InvalidConfig = 1,
    InitFailed = 2,
    NotJoined = 3,
    Other = 255,
}

fn peer_to_c(peer: PeerId) -> PeerIdC {
    PeerIdC { bytes: peer.0 }
}

fn session_to_c(session: SessionId) -> SessionIdC {
    SessionIdC { bytes: session.0 }
}

/// Initialize the SDK from a TOML config path (or defaults if null).
///
/// # Safety
/// `config_path` must be a valid null-terminated string if non-null.
#[no_mangle]
pub extern "C" fn rift_init(config_path: *const c_char, out_error: *mut RiftErrorCode) -> *mut RiftHandleC {
    unsafe {
        if !out_error.is_null() {
            *out_error = RiftErrorCode::Ok;
        }
    }

    let config = if config_path.is_null() {
        RiftConfig::default()
    } else {
        let c_str = unsafe { CStr::from_ptr(config_path) };
        match c_str.to_str() {
            Ok(path) => {
                match std::fs::read_to_string(path) {
                    Ok(content) => match toml::from_str::<RiftConfig>(&content) {
                        Ok(cfg) => cfg,
                        Err(_) => {
                            unsafe {
                                if !out_error.is_null() {
                                    *out_error = RiftErrorCode::InvalidConfig;
                                }
                            }
                            return ptr::null_mut();
                        }
                    },
                    Err(_) => {
                        unsafe {
                            if !out_error.is_null() {
                                *out_error = RiftErrorCode::InvalidConfig;
                            }
                        }
                        return ptr::null_mut();
                    }
                }
            }
            Err(_) => {
                unsafe {
                    if !out_error.is_null() {
                        *out_error = RiftErrorCode::InvalidConfig;
                    }
                }
                return ptr::null_mut();
            }
        }
    };

    let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
        Ok(rt) => rt,
        Err(_) => {
            unsafe {
                if !out_error.is_null() {
                    *out_error = RiftErrorCode::InitFailed;
                }
            }
            return ptr::null_mut();
        }
    };

    let handle = match runtime.block_on(RiftHandle::new(config)) {
        Ok(handle) => handle,
        Err(_) => {
            unsafe {
                if !out_error.is_null() {
                    *out_error = RiftErrorCode::InitFailed;
                }
            }
            return ptr::null_mut();
        }
    };

    let boxed = Box::new(RiftHandleC { runtime, handle });
    Box::into_raw(boxed)
}

/// Return the SDK version string.
#[no_mangle]
pub extern "C" fn rift_sdk_version() -> *const c_char {
    concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char
}

/// Return the SDK ABI version.
#[no_mangle]
pub extern "C" fn rift_sdk_abi_version() -> c_int {
    SDK_ABI_VERSION as c_int
}

/// Free a previously allocated Rift handle.
///
/// # Safety
/// `handle` must be a pointer returned by `rift_init`.
#[no_mangle]
pub extern "C" fn rift_free(handle: *mut RiftHandleC) {
    if handle.is_null() {
        return;
    }
    unsafe {
        drop(Box::from_raw(handle));
    }
}

/// Join a channel by name/password.
///
/// # Safety
/// `handle` must be valid. Strings must be null-terminated if non-null.
#[no_mangle]
pub extern "C" fn rift_join_channel(
    handle: *mut RiftHandleC,
    name: *const c_char,
    password: *const c_char,
    internet: c_int,
) -> c_int {
    if handle.is_null() || name.is_null() {
        return -1;
    }
    let handle = unsafe { &mut *handle };
    let name = unsafe { CStr::from_ptr(name) }.to_string_lossy().to_string();
    let password = if password.is_null() {
        None
    } else {
        Some(unsafe { CStr::from_ptr(password) }.to_string_lossy().to_string())
    };
    let internet = internet != 0;
    let result = handle.runtime.block_on(handle.handle.join_channel(&name, password.as_deref(), internet));
    match result {
        Ok(_) => 0,
        Err(_) => -1,
    }
}

/// Leave the current channel.
///
/// # Safety
/// `handle` must be valid. `name` must be a null-terminated string if non-null.
#[no_mangle]
pub extern "C" fn rift_leave_channel(handle: *mut RiftHandleC, name: *const c_char) -> c_int {
    if handle.is_null() {
        return -1;
    }
    let handle = unsafe { &mut *handle };
    let name = if name.is_null() {
        "".to_string()
    } else {
        unsafe { CStr::from_ptr(name) }.to_string_lossy().to_string()
    };
    let result = handle.runtime.block_on(handle.handle.leave_channel(&name));
    match result {
        Ok(_) => 0,
        Err(_) => -1,
    }
}

/// Send a chat message to peers.
///
/// # Safety
/// `handle` must be valid. `text` must be a null-terminated string if non-null.
#[no_mangle]
pub extern "C" fn rift_send_chat(handle: *mut RiftHandleC, text: *const c_char) -> c_int {
    if handle.is_null() || text.is_null() {
        return -1;
    }
    let handle = unsafe { &mut *handle };
    let text = unsafe { CStr::from_ptr(text) }.to_string_lossy().to_string();
    let result = handle.runtime.block_on(handle.handle.send_chat(&text));
    match result {
        Ok(_) => 0,
        Err(_) => -1,
    }
}

/// Enable push-to-talk.
///
/// # Safety
/// `handle` must be valid.
#[no_mangle]
pub extern "C" fn rift_start_ptt(handle: *mut RiftHandleC) -> c_int {
    if handle.is_null() {
        return -1;
    }
    let handle = unsafe { &mut *handle };
    handle.handle.set_ptt_active(true);
    0
}

/// Disable push-to-talk.
///
/// # Safety
/// `handle` must be valid.
#[no_mangle]
pub extern "C" fn rift_stop_ptt(handle: *mut RiftHandleC) -> c_int {
    if handle.is_null() {
        return -1;
    }
    let handle = unsafe { &mut *handle };
    handle.handle.set_ptt_active(false);
    0
}

/// Mute or unmute microphone capture.
///
/// # Safety
/// `handle` must be valid.
#[no_mangle]
pub extern "C" fn rift_set_mute(handle: *mut RiftHandleC, muted: c_int) -> c_int {
    if handle.is_null() {
        return -1;
    }
    let handle = unsafe { &mut *handle };
    handle.handle.set_mute(muted != 0);
    0
}

/// Start a call to a specific peer.
///
/// # Safety
/// `handle` must be valid. `peer` must point to a valid `PeerIdC`.
#[no_mangle]
pub extern "C" fn rift_start_call(handle: *mut RiftHandleC, peer: *const PeerIdC) -> SessionIdC {
    if handle.is_null() || peer.is_null() {
        return SessionIdC { bytes: [0u8; 32] };
    }
    let handle = unsafe { &mut *handle };
    let peer = unsafe { &*peer };
    let peer_id = PeerId(peer.bytes);
    let result = handle.runtime.block_on(handle.handle.start_call(peer_id));
    match result {
        Ok(session) => session_to_c(session),
        Err(_) => SessionIdC { bytes: [0u8; 32] },
    }
}

/// Accept an incoming call.
///
/// # Safety
/// `handle` must be valid.
#[no_mangle]
pub extern "C" fn rift_accept_call(handle: *mut RiftHandleC, session: SessionIdC) -> c_int {
    if handle.is_null() {
        return -1;
    }
    let handle = unsafe { &mut *handle };
    let session = SessionId(session.bytes);
    let result = handle.runtime.block_on(handle.handle.accept_call(session));
    match result {
        Ok(_) => 0,
        Err(_) => -1,
    }
}

/// Decline an incoming call with optional reason.
///
/// # Safety
/// `handle` must be valid. `reason` must be a null-terminated string if non-null.
#[no_mangle]
pub extern "C" fn rift_decline_call(
    handle: *mut RiftHandleC,
    session: SessionIdC,
    reason: *const c_char,
) -> c_int {
    if handle.is_null() {
        return -1;
    }
    let handle = unsafe { &mut *handle };
    let session = SessionId(session.bytes);
    let reason = if reason.is_null() {
        None
    } else {
        Some(unsafe { CStr::from_ptr(reason) }.to_string_lossy().to_string())
    };
    let result = handle
        .runtime
        .block_on(handle.handle.decline_call(session, reason.as_deref()));
    match result {
        Ok(_) => 0,
        Err(_) => -1,
    }
}

/// End an active call.
///
/// # Safety
/// `handle` must be valid.
#[no_mangle]
pub extern "C" fn rift_end_call(handle: *mut RiftHandleC, session: SessionIdC) -> c_int {
    if handle.is_null() {
        return -1;
    }
    let handle = unsafe { &mut *handle };
    let session = SessionId(session.bytes);
    let result = handle.runtime.block_on(handle.handle.end_call(session));
    match result {
        Ok(_) => 0,
        Err(_) => -1,
    }
}

/// Fetch the next event without blocking.
///
/// # Safety
/// `handle` and `out_event` must be valid pointers.
#[no_mangle]
pub extern "C" fn rift_next_event(handle: *mut RiftHandleC, out_event: *mut RiftEventC) -> c_int {
    if handle.is_null() || out_event.is_null() {
        return -1;
    }
    let handle = unsafe { &mut *handle };
    let event = handle.handle.try_next_event();
    unsafe {
        (*out_event) = RiftEventC {
            tag: RiftEventTag::None,
            peer: PeerIdC { bytes: [0u8; 32] },
            session: SessionIdC { bytes: [0u8; 32] },
            level: 0.0,
            text: ptr::null_mut(),
        };
    }
    let Some(event) = event else { return 0; };

    match event {
        RiftEvent::IncomingChat(chat) => {
            let text = CString::new(chat.text).unwrap_or_default().into_raw();
            unsafe {
                (*out_event).tag = RiftEventTag::IncomingChat;
                (*out_event).peer = peer_to_c(chat.from);
                (*out_event).text = text;
            }
        }
        RiftEvent::IncomingCall {
            session,
            from,
            rndzv_srt_uri: _,
        } => unsafe {
            (*out_event).tag = RiftEventTag::IncomingCall;
            (*out_event).peer = peer_to_c(from);
            (*out_event).session = session_to_c(session);
        },
        RiftEvent::CallStateChanged { session, .. } => unsafe {
            (*out_event).tag = RiftEventTag::CallStateChanged;
            (*out_event).session = session_to_c(session);
        },
        RiftEvent::PeerJoinedChannel { peer, .. } => unsafe {
            (*out_event).tag = RiftEventTag::PeerJoined;
            (*out_event).peer = peer_to_c(peer);
        },
        RiftEvent::PeerLeftChannel { peer, .. } => unsafe {
            (*out_event).tag = RiftEventTag::PeerLeft;
            (*out_event).peer = peer_to_c(peer);
        },
        RiftEvent::AudioLevel { peer, level } => unsafe {
            (*out_event).tag = RiftEventTag::AudioLevel;
            (*out_event).peer = peer_to_c(peer);
            (*out_event).level = level;
        },
        RiftEvent::CodecSelected { .. }
        | RiftEvent::PeerCapabilities { .. }
        | RiftEvent::AudioBitrate { .. }
        | RiftEvent::StatsUpdate { .. }
        | RiftEvent::RouteUpdated { .. }
        | RiftEvent::GroupTopology { .. }
        | RiftEvent::PeerFingerprint { .. }
        | RiftEvent::SecurityNotice { .. }
        | RiftEvent::VoiceFrame { .. } => {}
    }
    1
}

/// Free strings owned by an event.
///
/// # Safety
/// `event` must be a pointer returned by `rift_next_event`.
#[no_mangle]
pub extern "C" fn rift_event_free(event: *mut RiftEventC) {
    if event.is_null() {
        return;
    }
    unsafe {
        if !(*event).text.is_null() {
            drop(CString::from_raw((*event).text));
            (*event).text = ptr::null_mut();
        }
    }
}