rtci-ffi
rtci-host as a dynamic library for JavaScript runtimes that load WebRTC through FFI (dodo-bindgen). 76 exported calls, generated from src/lib.rs (the #[dodo_bindgen] items and their Rust documentation) and the generated bindings/rtci_ffi.ts at 0.1.0.
crates.io · src/lib.rs · bindings/rtci_ffi.ts
Exported calls
Names are the TypeScript ones (the Rust name in parentheses); each parameter shows its Rust type and, after the arrow, the type the generated binding takes. OutBuf parameters are the (out, cap) result buffer described in the README.
- function
buildId(out, cap)(build_id):;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberThe library's version (
rtci-ffi/0.1.0), for the shim's check that it loaded the build it was made for: written toout(capacitycap), its length returned ([buf]). - constructor
new Engine(options)(new):;options: JsStr→string;returnsEngineStarts an engine of its own (its own thread).
optionsis JSON ({}, or{ "logLevel": "warn" }). It can't throw: if the options are invalid or a thread can't start, the engine is poisoned (isPoisoned()) andlastError()says why. - method
id()(id):;returnsnumberThe id the waker is called with.
- method
isPoisoned()(is_poisoned):;returnsbooleanWhether the engine failed (a panic, or a thread that couldn't start), or this handle did: every call then fails with
POISONED(-10). - method
lastErrorCode()(last_error_code):;returnsnumberThe calling thread's last error code (0 before any error).
- method
lastError(out, cap)(last_error):;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberThe calling thread's last error message, into
out([buf]). - method
takeResult(out, cap)(take_result):;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberCopies this thread's result that didn't fit its buffer (a call returned a length over its capacity) into
out: its length (still kept whencapis too small again), orBAD_RESOURCE(-9) when none waits. The slot holds one result: take it before the next call. - method
setWaker(waker)(set_waker):;waker: extern "C" fn(u32)→RustFnPtr<'extern "C" fn(u32)'>;returnsvoidRegisters the waker: a
Deno.UnsafeCallback.threadSafe({ parameters: ["u32"], result: "void" }, onWake)'s pointer, called (from another thread) withid()when events are queued, at most once until the nextdrain. Never pass a null pointer; keep the callback alive (unref it while idle) for the engine's lifetime and don't close it. - method
clearWaker()(clear_waker):;returnsvoidStops calling the waker (a call already started still completes).
- method
drainSize(max_bytes)(drain_size):;max_bytes: u32→number;returnsnumberThe size of the batch a drain would take now, up to about
maxBytes(0: no limit; always at least the oldest event): what to allocate fordrain. 0 when nothing is queued. - method
drain(out, cap)(drain):;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberTakes the queued events that fit in
out(capacitycap), oldest first, written as one batch:u32 count, then per eventu32 handle,u32 jsonLen, JSON,u32 binLen, payload (little-endian). An event whose JSON has adatakey gets the payload asdata; anullevent is the end of the resource's events. Returns the bytes written (0: nothing queued), or, when even the oldest event doesn't fit, the size it needs (overcap; nothing taken). A buffer ofdrainSize(n)bytes takes exactly that batch. Events left over wake JavaScript again. - method
pending()(pending):;returnsnumberHow many events are queued.
- method
wait(timeout_ms) → Promise(wait):;timeout_ms: u32→number;returnsPromise<number>The fallback to the waker: waits up to
timeoutMs(off JavaScript's thread) for an event, and resolves to how many are queued. - method
gateAttach()(gate_attach):;returnsnumberThe shim answers
gaterequestevents from now on. Before this every address is refused andpcCreatefails (INVALID_STATE_ERROR): call it before creating connections. 0 or an error code. - method
gateAnswer(ticket, allow, message)(gate_answer):;ticket: u32→number;allow: bool→boolean;message: JsStr→string;returnsnumberAnswers the
gaterequestticket: allowed, or refused withmessage(the permission state, for the error text). 0, orBAD_RESOURCE(-9) when nothing waits for it any more (an unknown ticket, answered already, timed out, or its connection closed). - method
pcCreate(config)(pc_create):;config: JsStr→string;returnsnumbernew RTCPeerConnection(configuration):configis the JSON of the built-in op'sConfigArg(iceServers,iceTransportPolicy,bundlePolicy,certificatesids,networkhandle). The connection's handle, or an error code (INVALID_STATE_ERRORbeforegateAttach(): the connection asks the gate for the interface list as it is made, and would keep the refusal). The ICE servers are asked of the gate when the connection first uses them (a refusal is anicecandidateerror). - method
pcCreateOffer(pc, ice_restart, out, cap)(pc_create_offer):;pc: u32→number;ice_restart: bool→boolean;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumbercreateOffer(): the SDP, intoout([buf]). - method
pcCreateAnswer(pc, out, cap)(pc_create_answer):;pc: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumbercreateAnswer(): the SDP, intoout([buf]). - method
pcSetLocalDescription(pc, kind, sdp)(pc_set_local_description):;pc: u32→number;kind: JsStr→string;sdp: JsStr→string;returnsnumbersetLocalDescription({ type, sdp }): 0 or an error code. - method
pcSetRemoteDescription(pc, kind, sdp)(pc_set_remote_description):;pc: u32→number;kind: JsStr→string;sdp: JsStr→string;returnsnumbersetRemoteDescription({ type, sdp }), two-phase: the operation's id (positive) once the arguments are checked, or an error code (a closed connection, an oversized description, an invalid type, a malformed candidate). The outcome is the connection'sopdoneevent for the id: noerrorwhen the description was applied, else{ kind, message }(NotCapablefor a refused address). - method
pcAddIceCandidate(pc, candidate)(pc_add_ice_candidate):;pc: u32→number;candidate: JsStr→string;returnsnumberaddIceCandidate(candidate), two-phase aspcSetRemoteDescription:candidateisRTCIceCandidateInitas JSON. The operation's id, or an error code; the outcome is theopdoneevent for the id. - method
pcDescriptions(pc, out, cap)(pc_descriptions):;pc: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberThe four description slots (
currentLocal,pendingLocal,currentRemote,pendingRemote, each[type, sdp]ornull), JSON intoout. - method
pcCreateDataChannel(pc, init, out, cap)(pc_create_data_channel):;pc: u32→number;init: JsStr→string;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumbercreateDataChannel(label, init):initis the built-in op'sDataChannelArgas JSON.{ channel, id }as JSON (channelis the engine's handle for it,idthe stream id ornull), intoout. - method
pcGetStats(pc, key, selected, sender, out, cap)(pc_get_stats):;pc: u32→number;key: u32→number;selected: bool→boolean;sender: bool→boolean;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumbergetStats(selector): withselected,keynames a transceiver whose sender (sender) or receiver is the selector. The stats dictionaries as a JSON array (timestamps relative to the wall clock at the call), intoout. - method
pcClose(pc)(pc_close):;pc: u32→number;returnsnumberclose(): removes and closes the connection (an unknown handle is ignored). Its events end with anullevent. 0 or an error code. - method
pcSelectedPair(pc, out, cap)(pc_selected_pair):;pc: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberThe selected pair's
[local, remote, "udp" | "tcp"]addresses once the connection has sent on one, elsenull, as JSON intoout. - method
pcIceSelectedPair(pc, out, cap)(pc_ice_selected_pair):;pc: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumbergetSelectedCandidatePair():{ local, remote }with each candidate's fields, ornull, as JSON intoout. - method
pcSetIceServers(pc, config)(pc_set_ice_servers):;pc: u32→number;config: JsStr→string;returnsnumbersetConfiguration()'s ICE servers and policy for the next gathering (configas inpcCreate; the servers are asked of the gate when used). 0 or an error code. - method
dcSend(pc, channel, text, data, len)(dc_send):;pc: u32→number;channel: u32→number;text: bool→boolean;data: InBuf→Uint8Array<ArrayBuffer>;len: u32→number;returnsnumbersend(data):dataislenbytes ([buf]). The channel's buffered amount after it, or an error code (a number, as the amount can passi32). - method
dcId(pc, channel)(dc_id):;pc: u32→number;channel: u32→number;returnsnumberRTCDataChannel.idwhile it is null in JavaScript: the stream id assigned since, or -1 (none yet, or an unknown connection; never an error, as the built-in op). - method
dcSetLowThreshold(pc, channel, threshold)(dc_set_low_threshold):;pc: u32→number;channel: u32→number;threshold: u32→number;returnsnumberbufferedAmountLowThreshold = threshold. 0 or an error code. - method
dcClose(pc, channel)(dc_close):;pc: u32→number;channel: u32→number;returnsnumberclose()on a channel. 0 or an error code. - method
pcAddTransceiver(pc, arg)(pc_add_transceiver):;pc: u32→number;arg: JsStr→string;returnsnumberaddTransceiver()/addTrack()'s new transceiver:argis the built-in op'sTransceiverArgas JSON (kind,track,direction,streams,sendEncodings,codec,addTrack). Its key, or an error code. - method
pcAttachTrack(pc, key, track, streams)(pc_attach_track):;pc: u32→number;key: u32→number;track: JsStr→string;streams: JsStr→string;returnsnumberA track for a transceiver's sender (
addTrack()reusing one,replaceTrack()):trackis{ id, label },streamsan array of stream ids, both JSON. 0 or an error code. - method
pcTransceivers(pc, out, cap)(pc_transceivers):;pc: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumbergetTransceivers(): theTransceiverInfos as a JSON array intoout(empty once the connection is closed). - method
transceiverSetDirection(pc, key, direction)(transceiver_set_direction):;pc: u32→number;key: u32→number;direction: JsStr→string;returnsnumbertransceiver.direction = direction. 0 or an error code. - method
transceiverStop(pc, key)(transceiver_stop):;pc: u32→number;key: u32→number;returnsnumbertransceiver.stop(). 0 or an error code. - method
transceiverSetCodecPreferences(pc, key, codecs)(transceiver_set_codec_preferences):;pc: u32→number;key: u32→number;codecs: JsStr→string;returnsnumbertransceiver.setCodecPreferences(codecs):codecsa JSON array of{ mimeType, clockRate, channels?, sdpFmtpLine? }. 0 or an error code. - method
transceiverSetHeaderExtensions(pc, key, uris)(transceiver_set_header_extensions):;pc: u32→number;key: u32→number;uris: JsStr→string;returnsnumbertransceiver.setHeaderExtensionsToNegotiate(), by URI (a JSON array). 0 or an error code. - method
pcSetNegotiationOptions(pc, rtp_header_encryption_policy, always_negotiate_data_channels)(pc_set_negotiation_options):;pc: u32→number;rtp_header_encryption_policy: JsStr→string;always_negotiate_data_channels: bool→boolean;returnsnumberRTCConfiguration.rtpHeaderEncryptionPolicyandalwaysNegotiateDataChannels. 0 or an error code. - method
senderSetTrackCodec(pc, key, codec)(sender_set_track_codec):;pc: u32→number;key: u32→number;codec: JsStr→string;returnsnumberThe sender's track is an encoded track of
codec(JSON{ mimeType, clockRate, ... }), ornull: another track or none. 0 or an error code. - method
senderSetPaused(pc, key, paused)(sender_set_paused):;pc: u32→number;key: u32→number;paused: bool→boolean;returnsnumberWhether a sender sends (a disabled or ended track pauses it). 0 or an error code.
- method
senderSetStreams(pc, key, streams)(sender_set_streams):;pc: u32→number;key: u32→number;streams: JsStr→string;returnsnumbersender.setStreams(): stream ids as a JSON array. 0 or an error code. - method
senderParameters(pc, key, out, cap)(sender_parameters):;pc: u32→number;key: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumbersender.getParameters()'s negotiated part, JSON intoout. - method
receiverParameters(pc, key, out, cap)(receiver_parameters):;pc: u32→number;key: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberreceiver.getParameters(), JSON intoout. - method
receiverSources(pc, key, contributing, out, cap)(receiver_sources):;pc: u32→number;key: u32→number;contributing: bool→boolean;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberreceiver.getSynchronizationSources()(or, withcontributing,getContributingSources()), a JSON array intoout. - method
senderWriteRtp(pc, key, data, len)(sender_write_rtp):;pc: u32→number;key: u32→number;data: InBuf→Uint8Array<ArrayBuffer>;len: u32→number;returnsnumberWrites an RTP packet (header included,
lenbytes) for a sender: 1 when sent, 0 when not (nothing negotiated yet), or an error code. - method
senderWriteFrame(pc, key, data, len, duration_ms)(sender_write_frame):;pc: u32→number;key: u32→number;data: InBuf→Uint8Array<ArrayBuffer>;len: u32→number;duration_ms: f64→number;returnsnumberWrites an encoded frame (
lenbytes) for a sender (Deno.webrtc.EncodedMediaTrack): 1 when sent, 0 when not, or an error code. - method
senderWriteFrameAt(pc, key, data, len, duration_ms, rtp_timestamp)(sender_write_frame_at):;pc: u32→number;key: u32→number;data: InBuf→Uint8Array<ArrayBuffer>;len: u32→number;duration_ms: f64→number;rtp_timestamp: u32→number;returnsnumberWrites an encoded transform's frame (
lenbytes) at the RTP timestamp it was given: 1 when sent, 0 when not, or an error code. - method
senderWriteFake(pc, key, stereo)(sender_write_fake):;pc: u32→number;key: u32→number;stereo: bool→boolean;returnsnumberWrites a fake capture device's next frame for a sender: 1 when sent, 0 when not, or an error code.
- method
senderFakeFrame(pc, key, stereo, out, cap)(sender_fake_frame):;pc: u32→number;key: u32→number;stereo: bool→boolean;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberA fake device's next frame for a sender with an encoded transform, into
outasu32 jsonLen(little-endian), the JSON (the built-in op'sFakeFramewith"data": null, ornullwhen there is no frame yet), then the frame's bytes (itsdata). - method
receiverTransform(pc, key, on)(receiver_transform):;pc: u32→number;key: u32→number;on: bool→boolean;returnsnumberreceiver.transformset or cleared: the receiver's frames come asencodedframeevents while it is set. 0 or an error code. - method
receiverReadRtp(pc, key, on)(receiver_read_rtp):;pc: u32→number;key: u32→number;on: bool→boolean;returnsnumberDeno.webrtc.readRtp(): whether a receiver's RTP packets come asrtpevents. 0 or an error code. - method
receiverReadFrames(pc, key, on)(receiver_read_frames):;pc: u32→number;key: u32→number;on: bool→boolean;returnsnumberDeno.webrtc.readFrames(): whether a receiver's frames are put together and come asmediaframeevents. 0 or an error code. - method
receiverMuted(pc, key, generation)(receiver_muted):;pc: u32→number;key: u32→number;generation: u32→number;returnsnumberA receiver's track was muted (its remote side stopped sending): the next RTP packet unmutes it (
trackunmutewithgeneration). 0 or an error code. - method
senderSendDtmf(pc, key, event, duration_ms)(sender_send_dtmf):;pc: u32→number;key: u32→number;event: u32→number;duration_ms: u32→number;returnsnumberRTCDTMFSender: one telephone event (eventabove 15 is 15): 1 when sent, 0 when not, or an error code. - method
receiverRequestKeyFrame(pc, key)(receiver_request_key_frame):;pc: u32→number;key: u32→number;returnsnumberAsks a receiver's remote sender for a key frame (PLI): 1 when asked, 0 when not, or an error code.
- method
iceCreate()(ice_create):;returnsnumbernew RTCIceTransport(): a transport with fresh local parameters, gathering nothing untiliceGather. Its handle, or an error code (INVALID_STATE_ERRORbeforegateAttach(), aspcCreate). Its events (icecandidate,gatheringcomplete,statechange,selectedcandidatepairchange,rolechange) come on its handle,nullonce it stops. - method
iceLocalParameters(ice, out, cap)(ice_local_parameters):;ice: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumbergetLocalParameters():[usernameFragment, password]as JSON intoout. - method
iceGather(ice, servers, relay_only)(ice_gather):;ice: u32→number;servers: JsStr→string;relay_only: bool→boolean;returnsnumbergather(options):serversisRTCIceServer[]as JSON (checked for syntax, not used yet, as the built-in op),relay_onlytherelaygather policy. The binds wait for the gate. 0 or an error code. - method
iceStart(ice, ufrag, pwd, controlling)(ice_start):;ice: u32→number;ufrag: JsStr→string;pwd: JsStr→string;controlling: bool→boolean;returnsnumberstart(remoteParameters, role). 0 or an error code. - method
iceAddRemoteCandidate(ice, candidate)(ice_add_remote_candidate):;ice: u32→number;candidate: JsStr→string;returnsnumberaddRemoteCandidate(candidate): the candidate-attribute value (the address is asked of the gate before it is used). 0 or an error code. - method
iceSelectedPair(ice, out, cap)(ice_selected_pair):;ice: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumbergetSelectedCandidatePair()'s addresses, ornull, as JSON intoout. - method
iceStop(ice)(ice_stop):;ice: u32→number;returnsnumberstop(): removes and stops the transport (an unknown handle is ignored); its events end with anullevent. 0 or an error code. - method
generateCertificate(algorithm, expires_at_ms, out, cap) → Promise(generate_certificate):;algorithm: JsStr→string;expires_at_ms: f64→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsPromise<number>RTCPeerConnection.generateCertificate(keygenAlgorithm), off JavaScript's thread:algorithmis WebCrypto's dictionary as JSON,expiresAtMsthe expiry on the JavaScript clock. Writes{ id, expires, fingerprints }, or{ error, message }(an error code and its message: a promise can't use the thread's last error), tooutand resolves to its length. Pass at least 1 KiB: a result that doesn't fit becomes an{ error }(the pool thread's result slot is out of reach), or -11 when not even that fits. - method
certificateToPem(id, out, cap)(certificate_to_pem):;id: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberDeno.webrtc.exportCertificate: the key and certificate as PEM, intoout. - method
certificateFromPem(pem, out, cap)(certificate_from_pem):;pem: JsStr→string;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberImports an exported certificate:
{ id, expires, fingerprints }as JSON intoout. - method
certificateDrop(id)(certificate_drop):;id: u32→number;returnsvoidForgets certificate
id(itsRTCCertificatewas collected); the connections given it keep their copy. - method
capabilities(kind, sender, out, cap)(capabilities):;kind: JsStr→string;sender: bool→boolean;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberRTCRtpSender/Receiver.getCapabilities(kind)as JSON (nullfor an unknown kind), intoout. - method
fakeMediaDevices()(fake_media_devices):;returnsbooleanWhether the fake capture devices are on (
DENO_FAKE_MEDIA_DEVICES=1). - method
networkCreate(options, out, cap) → Promise(network_create):;options: JsStr→string;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsPromise<number>Deno.webrtc.createNetwork(options)(options as JSON), off JavaScript's thread: aportnetwork binds its sockets before it resolves, each bind waiting for the gate's answer (answer thegaterequests meanwhile). Writes{ network }(its handle) or{ error, message }(an error code and its message: a promise can't use the thread's last error;NOT_CAPABLEfor a refused bind) tooutand resolves to its length (sizes asgenerateCertificate). - method
networkAddresses(network, out, cap)(network_addresses):;network: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberThe network's shared UDP addresses (
ip:port), a JSON array intoout. - method
networkTcpAddresses(network, out, cap)(network_tcp_addresses):;network: u32→number;out: OutBuf→Uint8Array<ArrayBuffer>;cap: u32→number;returnsnumberThe network's ICE-TCP listener addresses, a JSON array into
out. - method
networkClose(network)(network_close):;network: u32→number;returnsnumberCloses a network (an unknown handle is ignored). 0 or an error code.
- method
setLogLevel(level)(set_log_level):;level: JsStr→string;returnsnumberDeno.webrtc.setLogLevel(level):off,error,warn,info,debugortrace(process-wide; records go to standard error). 0 orTYPE_ERROR.
README
rtci-host (the host I/O around the rtci WebRTC engine) as a dynamic library for JavaScript runtimes that load WebRTC through plain FFI (Deno.dlopen), built with dodo-bindgen 2.0.
This crate is the native half. The JavaScript half, the shim that installs RTCPeerConnection and the rest of the W3C API over this library and answers its permission gate from Deno.permissions, lives with the runtime that uses it (for Dodo, in the Dodo repository). Each release attaches the prebuilt library for every supported target with a SHA-256 checksum, which the shim verifies before loading it, and the generated TypeScript bindings.
Surface
One class, Engine, and buildId(out, cap). new Engine("{}") starts an engine thread of its own; Engine.shared("{}") is a handle on the process-wide engine (started by the first such handle, shared by every thread that asks: the main thread and its workers). Each handle is a sink: its own event queue and waker (id()), its own permission gate (attach and answer it per handle: each thread answers with its own permissions) and the connections and networks made through it, which other handles can't reach (-9). Disposing of a handle (using / [Symbol.dispose]()) closes what it made; the engine thread ends with its last handle. Every method is synchronous except generateCertificate, networkCreate and wait (Deno's blocking pool, a Promise). Disposing waits for those to settle.
- Buffers (
src/buf.rs), so a caller needs onlyDeno.dlopenand symbol calls, which--allow-ffi=<this library>permits (no pointer views):- strings in: dodo-bindgen's
JsStr(a length-prefixedbuffer); - bytes in: a
Uint8Arrayand its length (dcSend(pc, ch, text, data, data.byteLength)); - results out: a
Uint8Arrayand its capacity,(out, cap)as the last two arguments; the call returns the result's lengthn.n <= cap: it is inout[0..n].n > cap: nothing was written and the result waits in the calling thread's slot:takeResult(out, cap)withcap >= ncopies it (returnsn; still too small, it returnsnand keeps it; nothing waiting, -9). The call never has to run twice. generateCertificate(alg, expiresAtMs, out, cap)andnetworkCreate(options, out, cap)resolve to the length of the JSON they wrote ({ error, message }on error: a Promise can't use the thread's last error). Pass at least 1 KiB: their results are small, and one that doesn't fit becomes an{ error }(or -11).
- strings in: dodo-bindgen's
- Errors: a negative number is an error code; the error is then
lastErrorCode()/lastError(out, cap)(per calling thread). - Codes: -1 TypeError, -2 SyntaxError, -3 InvalidAccessError, -4 InvalidStateError, -5 OperationError, -6 InvalidModificationError, -7 NotSupportedError, -8 NotCapable, -9 BadResource, -10 engine poisoned, -11 internal error.
- Events:
drainSize(maxBytes)is the size of the batch a drain takes now (0: nothing queued; at least the oldest event);drain(out, cap)takes the events that fit, returns the bytes written (format insrc/events.rs), or the size the oldest needs when it doesn't fit (nothing taken). AllocatedrainSize(n)bytes and drain exactly that batch. - Waking:
setWaker(threadSafeCallback.pointer): the callback gets the engine'sid()when events are queued (once until the next drain). ADeno.UnsafeCallbackneeds a bare--allow-ffi; under a scoped grant, poll withwait(timeoutMs)(resolves to how many events are queued, as soon as one is) andpending().
Media
Transceivers are named by the key pcAddTransceiver(pc, argJson) returns (argJson: the built-in op's TransceiverArg). Each call takes the connection and the key; structured arguments are JSON; a call that answers a boolean returns 1 or 0; results go to (out, cap):
pcTransceivers(pc, out, cap),pcAttachTrack(pc, key, trackJson, streamsJson),pcSetNegotiationOptions(pc, policy, alwaysNegotiate);transceiverSetDirection(pc, key, direction),transceiverStop,transceiverSetCodecPreferences(pc, key, codecsJson),transceiverSetHeaderExtensions(pc, key, urisJson);senderSetTrackCodec(pc, key, codecJsonOrNull),senderSetPaused,senderSetStreams(pc, key, streamsJson),senderParameters(pc, key, out, cap),senderSendDtmf(pc, key, event, durationMs);senderWriteRtp(pc, key, data, len),senderWriteFrame(pc, key, data, len, durationMs),senderWriteFrameAt(pc, key, data, len, durationMs, rtpTimestamp)(an encoded transform's frame),senderWriteFake(pc, key, stereo);senderFakeFrame(pc, key, stereo, out, cap):u32 jsonLen, theFakeFrameJSON with"data": null(ornull: no frame yet), then the frame's bytes;receiverParameters(pc, key, out, cap),receiverSources(pc, key, contributing, out, cap),receiverMuted(pc, key, generation),receiverRequestKeyFrame, and the switchesreceiverReadRtp,receiverReadFrames,receiverTransform(pc, key, on)(rtp,mediaframe,encodedframeevents, each with its bytes);pcGetStats(pc, key, selected, sender, out, cap)covers the media stats (a sender or receiver as the selector).
RTCIceTransport
iceCreate() (a handle; InvalidStateError before gateAttach()), iceLocalParameters(ice, out, cap) ([ufrag, pwd]), iceGather(ice, serversJson, relayOnly), iceStart(ice, ufrag, pwd, controlling), iceAddRemoteCandidate(ice, candidate), iceSelectedPair(ice, out, cap), iceStop(ice). Its events (icecandidate, gatheringcomplete, statechange, selectedcandidatepairchange, rolechange) come on its handle, null after iceStop.
The permission gate
gateAttach()(0, or an error code) once the shim can answer. Until then every address is refused andpcCreatefails with InvalidStateError: a connection asks for the interface list as it is made, and a refusal it gets is kept for its life.- Each new question is a
gaterequestevent on handle 0:{"type":"gaterequest","ticket":7,"kind":"remoteCandidate","dir":"connect","proto":"udp","host":"192.0.2.7","port":4000,"resolvedFrom":null}.kindisiceServer,iceServerResolved,remoteCandidate,sendTo,tcpDial,bind,mdnsorinterfaces(whosedir,proto,host,portandresolvedFromarenull);portisnullfor a bind. gateAnswer(ticket, allow, state): 0, or -9 when nothing waits for that ticket any more (answered already, timed out, or its connection closed).state("denied","prompt", ...) goes into the refusal's message.
The engine waits for the answer: nothing is bound, resolved or sent to that address before an allow. An answer that doesn't come within 10 s is a refusal. Answers are remembered for every connection of the engine, so a question is asked once. ICE servers are asked when a connection first uses them; a refusal there is an icecandidateerror, not a constructor error.
Calls that finish later
pcSetRemoteDescriptionandpcAddIceCandidateare two-phase: they return an operation id (positive) once their arguments are checked, or an error code for an argument error (a closed connection, an oversized description, an invalid type, a malformed candidate). The outcome is the connection'sopdoneevent,{"type":"opdone","op":3}on success or{"type":"opdone","op":4,"error":{"kind":"NotCapable","message":"..."}}.kindis a W3C name (NotCapablefor a refused address,InvalidStateErrorfor an operation still waiting when the connection closed, ...). Operations finish in the order they were made.networkCreate(options)resolves to{"network":3}once aportnetwork's sockets are bound (each bind asked of the gate: answer thegaterequests meanwhile), or to{"error":-8,"message":"..."}.
Events
Handle 0 (the engine): gaterequest. A connection's handle: icecandidate, icecandidateerror, signalingstatechange, icegatheringstatechange, iceconnectionstatechange, connectionstatechange, negotiationneeded, opdone, sctpstatechange, dtlsstatechange, dcopen, dcclosing, dcclose, dcerror, dcsent, dcmessage, trackmute, trackunmute, trackresize, rtp, keyframerequest, encodedframe, mediaframe, and null when its events end (after pcClose). The JSON is rtci-host's JsEvent; an event with a data key gets the record's bytes as data.
--allow-ffi gives the library full native rights, scoped grant or not: its gate is cooperative, not a sandbox.
Building the bindings
The library needs panic = "unwind" (this crate's profiles set it). With dodo-bindgen-cli 2.0.0 installed, from this directory:
dodo-bindgen -o bindings/rtci_ffi.ts # release; -d for a debug build
deno fmt bindings/rtci_ffi.ts bindings/rust_type.ts
The CLI builds the cdylib, reads its DODO_META_* export table (it does not load the library), copies it to bindings/rtci_ffi.<target>.<ext> and writes bindings/rtci_ffi.ts and bindings/rust_type.ts. Its own deno fmt step fails when -o names a subdirectory, hence the second command.
Releases
A v<version> tag builds the library for Linux x64/arm64, macOS arm64/x64 and Windows x64 (.github/workflows/release.yml) and attaches to the tag's GitHub release: rtci_ffi.<target>.<so|dylib|dll>, its .sha256, rtci_ffi.ts and rust_type.ts, and a combined SHA256SUMS. Put the library beside the bindings it came with; the shim loads rtci_ffi.<target>.<ext> from there and refuses it unless its bytes match the checksum and buildId() is rtci-ffi/<version>.