rtciv0.5.0

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.

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.

  • functionbuildId(out, cap)(build_id)
    :;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    The library's version (rtci-ffi/0.1.0), for the shim's check that it loaded the build it was made for: written to out (capacity cap), its length returned ([buf]).

  • constructornew Engine(options)(new)
    :;options: JsStr→ string;returns Engine

    Starts an engine of its own (its own thread). options is JSON ({}, or { "logLevel": "warn" }). It can't throw: if the options are invalid or a thread can't start, the engine is poisoned (isPoisoned()) and lastError() says why.

  • staticEngine.shared(options)(shared)
    :;options: JsStr→ string;returns Engine

    A handle on the process-wide engine, started by the first such handle and shared by every thread that asks (the main thread and its workers run one engine thread). The handle has its own events, gate and resources; options as new (the log level is process-wide anyway).

  • methodid()(id)
    :;returns number

    The id the waker is called with.

  • methodisPoisoned()(is_poisoned)
    :;returns boolean

    Whether the engine failed (a panic, or a thread that couldn't start), or this handle did: every call then fails with POISONED (-10).

  • methodlastErrorCode()(last_error_code)
    :;returns number

    The calling thread's last error code (0 before any error).

  • methodlastError(out, cap)(last_error)
    :;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    The calling thread's last error message, into out ([buf]).

  • methodtakeResult(out, cap)(take_result)
    :;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    Copies this thread's result that didn't fit its buffer (a call returned a length over its capacity) into out: its length (still kept when cap is too small again), or BAD_RESOURCE (-9) when none waits. The slot holds one result: take it before the next call.

  • methodsetWaker(waker)(set_waker)
    :;waker: extern "C" fn(u32)→ RustFnPtr<'extern "C" fn(u32)'>;returns void

    Registers the waker: a Deno.UnsafeCallback.threadSafe({ parameters: ["u32"], result: "void" }, onWake)'s pointer, called (from another thread) with id() when events are queued, at most once until the next drain. Never pass a null pointer; keep the callback alive (unref it while idle) for the engine's lifetime and don't close it.

  • methodclearWaker()(clear_waker)
    :;returns void

    Stops calling the waker (a call already started still completes).

  • methoddrainSize(max_bytes)(drain_size)
    :;max_bytes: u32→ number;returns number

    The 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 for drain. 0 when nothing is queued.

  • methoddrain(out, cap)(drain)
    :;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    Takes the queued events that fit in out (capacity cap), oldest first, written as one batch: u32 count, then per event u32 handle, u32 jsonLen, JSON, u32 binLen, payload (little-endian). An event whose JSON has a data key gets the payload as data; a null event 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 (over cap; nothing taken). A buffer of drainSize(n) bytes takes exactly that batch. Events left over wake JavaScript again.

  • methodpending()(pending)
    :;returns number

    How many events are queued.

  • methodwait(timeout_ms) → Promise(wait)
    :;timeout_ms: u32→ number;returns Promise<number>

    The fallback to the waker: waits up to timeoutMs (off JavaScript's thread) for an event, and resolves to how many are queued.

  • methodgateAttach()(gate_attach)
    :;returns number

    The shim answers gaterequest events from now on. Before this every address is refused and pcCreate fails (INVALID_STATE_ERROR): call it before creating connections. 0 or an error code.

  • methodgateAnswer(ticket, allow, message)(gate_answer)
    :;ticket: u32→ number;allow: bool→ boolean;message: JsStr→ string;returns number

    Answers the gaterequest ticket: allowed, or refused with message (the permission state, for the error text). 0, or BAD_RESOURCE (-9) when nothing waits for it any more (an unknown ticket, answered already, timed out, or its connection closed).

  • methodpcCreate(config)(pc_create)
    :;config: JsStr→ string;returns number

    new RTCPeerConnection(configuration): config is the JSON of the built-in op's ConfigArg (iceServers, iceTransportPolicy, bundlePolicy, certificates ids, network handle). The connection's handle, or an error code (INVALID_STATE_ERROR before gateAttach(): 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 an icecandidateerror).

  • methodpcCreateOffer(pc, ice_restart, out, cap)(pc_create_offer)
    :;pc: u32→ number;ice_restart: bool→ boolean;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    createOffer(): the SDP, into out ([buf]).

  • methodpcCreateAnswer(pc, out, cap)(pc_create_answer)
    :;pc: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    createAnswer(): the SDP, into out ([buf]).

  • methodpcSetLocalDescription(pc, kind, sdp)(pc_set_local_description)
    :;pc: u32→ number;kind: JsStr→ string;sdp: JsStr→ string;returns number

    setLocalDescription({ type, sdp }): 0 or an error code.

  • methodpcSetRemoteDescription(pc, kind, sdp)(pc_set_remote_description)
    :;pc: u32→ number;kind: JsStr→ string;sdp: JsStr→ string;returns number

    setRemoteDescription({ 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's opdone event for the id: no error when the description was applied, else { kind, message } (NotCapable for a refused address).

  • methodpcAddIceCandidate(pc, candidate)(pc_add_ice_candidate)
    :;pc: u32→ number;candidate: JsStr→ string;returns number

    addIceCandidate(candidate), two-phase as pcSetRemoteDescription: candidate is RTCIceCandidateInit as JSON. The operation's id, or an error code; the outcome is the opdone event for the id.

  • methodpcDescriptions(pc, out, cap)(pc_descriptions)
    :;pc: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    The four description slots (currentLocal, pendingLocal, currentRemote, pendingRemote, each [type, sdp] or null), JSON into out.

  • methodpcCreateDataChannel(pc, init, out, cap)(pc_create_data_channel)
    :;pc: u32→ number;init: JsStr→ string;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    createDataChannel(label, init): init is the built-in op's DataChannelArg as JSON. { channel, id } as JSON (channel is the engine's handle for it, id the stream id or null), into out.

  • methodpcGetStats(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;returns number

    getStats(selector): with selected, key names 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), into out.

  • methodpcClose(pc)(pc_close)
    :;pc: u32→ number;returns number

    close(): removes and closes the connection (an unknown handle is ignored). Its events end with a null event. 0 or an error code.

  • methodpcSelectedPair(pc, out, cap)(pc_selected_pair)
    :;pc: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    The selected pair's [local, remote, "udp" | "tcp"] addresses once the connection has sent on one, else null, as JSON into out.

  • methodpcIceSelectedPair(pc, out, cap)(pc_ice_selected_pair)
    :;pc: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    getSelectedCandidatePair(): { local, remote } with each candidate's fields, or null, as JSON into out.

  • methodpcSetIceServers(pc, config)(pc_set_ice_servers)
    :;pc: u32→ number;config: JsStr→ string;returns number

    setConfiguration()'s ICE servers and policy for the next gathering (config as in pcCreate; the servers are asked of the gate when used). 0 or an error code.

  • methoddcSend(pc, channel, text, data, len)(dc_send)
    :;pc: u32→ number;channel: u32→ number;text: bool→ boolean;data: InBuf→ Uint8Array<ArrayBuffer>;len: u32→ number;returns number

    send(data): data is len bytes ([buf]). The channel's buffered amount after it, or an error code (a number, as the amount can pass i32).

  • methoddcId(pc, channel)(dc_id)
    :;pc: u32→ number;channel: u32→ number;returns number

    RTCDataChannel.id while 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).

  • methoddcSetLowThreshold(pc, channel, threshold)(dc_set_low_threshold)
    :;pc: u32→ number;channel: u32→ number;threshold: u32→ number;returns number

    bufferedAmountLowThreshold = threshold. 0 or an error code.

  • methoddcClose(pc, channel)(dc_close)
    :;pc: u32→ number;channel: u32→ number;returns number

    close() on a channel. 0 or an error code.

  • methodpcAddTransceiver(pc, arg)(pc_add_transceiver)
    :;pc: u32→ number;arg: JsStr→ string;returns number

    addTransceiver() / addTrack()'s new transceiver: arg is the built-in op's TransceiverArg as JSON (kind, track, direction, streams, sendEncodings, codec, addTrack). Its key, or an error code.

  • methodpcAttachTrack(pc, key, track, streams)(pc_attach_track)
    :;pc: u32→ number;key: u32→ number;track: JsStr→ string;streams: JsStr→ string;returns number

    A track for a transceiver's sender (addTrack() reusing one, replaceTrack()): track is { id, label }, streams an array of stream ids, both JSON. 0 or an error code.

  • methodpcTransceivers(pc, out, cap)(pc_transceivers)
    :;pc: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    getTransceivers(): the TransceiverInfos as a JSON array into out (empty once the connection is closed).

  • methodtransceiverSetDirection(pc, key, direction)(transceiver_set_direction)
    :;pc: u32→ number;key: u32→ number;direction: JsStr→ string;returns number

    transceiver.direction = direction. 0 or an error code.

  • methodtransceiverStop(pc, key)(transceiver_stop)
    :;pc: u32→ number;key: u32→ number;returns number

    transceiver.stop(). 0 or an error code.

  • methodtransceiverSetCodecPreferences(pc, key, codecs)(transceiver_set_codec_preferences)
    :;pc: u32→ number;key: u32→ number;codecs: JsStr→ string;returns number

    transceiver.setCodecPreferences(codecs): codecs a JSON array of { mimeType, clockRate, channels?, sdpFmtpLine? }. 0 or an error code.

  • methodtransceiverSetHeaderExtensions(pc, key, uris)(transceiver_set_header_extensions)
    :;pc: u32→ number;key: u32→ number;uris: JsStr→ string;returns number

    transceiver.setHeaderExtensionsToNegotiate(), by URI (a JSON array). 0 or an error code.

  • methodpcSetNegotiationOptions(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;returns number

    RTCConfiguration.rtpHeaderEncryptionPolicy and alwaysNegotiateDataChannels. 0 or an error code.

  • methodsenderSetTrackCodec(pc, key, codec)(sender_set_track_codec)
    :;pc: u32→ number;key: u32→ number;codec: JsStr→ string;returns number

    The sender's track is an encoded track of codec (JSON { mimeType, clockRate, ... }), or null: another track or none. 0 or an error code.

  • methodsenderSetPaused(pc, key, paused)(sender_set_paused)
    :;pc: u32→ number;key: u32→ number;paused: bool→ boolean;returns number

    Whether a sender sends (a disabled or ended track pauses it). 0 or an error code.

  • methodsenderSetStreams(pc, key, streams)(sender_set_streams)
    :;pc: u32→ number;key: u32→ number;streams: JsStr→ string;returns number

    sender.setStreams(): stream ids as a JSON array. 0 or an error code.

  • methodsenderParameters(pc, key, out, cap)(sender_parameters)
    :;pc: u32→ number;key: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    sender.getParameters()'s negotiated part, JSON into out.

  • methodreceiverParameters(pc, key, out, cap)(receiver_parameters)
    :;pc: u32→ number;key: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    receiver.getParameters(), JSON into out.

  • methodreceiverSources(pc, key, contributing, out, cap)(receiver_sources)
    :;pc: u32→ number;key: u32→ number;contributing: bool→ boolean;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    receiver.getSynchronizationSources() (or, with contributing, getContributingSources()), a JSON array into out.

  • methodsenderWriteRtp(pc, key, data, len)(sender_write_rtp)
    :;pc: u32→ number;key: u32→ number;data: InBuf→ Uint8Array<ArrayBuffer>;len: u32→ number;returns number

    Writes an RTP packet (header included, len bytes) for a sender: 1 when sent, 0 when not (nothing negotiated yet), or an error code.

  • methodsenderWriteFrame(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;returns number

    Writes an encoded frame (len bytes) for a sender (Deno.webrtc.EncodedMediaTrack): 1 when sent, 0 when not, or an error code.

  • methodsenderWriteFrameAt(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;returns number

    Writes an encoded transform's frame (len bytes) at the RTP timestamp it was given: 1 when sent, 0 when not, or an error code.

  • methodsenderWriteFake(pc, key, stereo)(sender_write_fake)
    :;pc: u32→ number;key: u32→ number;stereo: bool→ boolean;returns number

    Writes a fake capture device's next frame for a sender: 1 when sent, 0 when not, or an error code.

  • methodsenderFakeFrame(pc, key, stereo, out, cap)(sender_fake_frame)
    :;pc: u32→ number;key: u32→ number;stereo: bool→ boolean;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    A fake device's next frame for a sender with an encoded transform, into out as u32 jsonLen (little-endian), the JSON (the built-in op's FakeFrame with "data": null, or null when there is no frame yet), then the frame's bytes (its data).

  • methodreceiverTransform(pc, key, on)(receiver_transform)
    :;pc: u32→ number;key: u32→ number;on: bool→ boolean;returns number

    receiver.transform set or cleared: the receiver's frames come as encodedframe events while it is set. 0 or an error code.

  • methodreceiverReadRtp(pc, key, on)(receiver_read_rtp)
    :;pc: u32→ number;key: u32→ number;on: bool→ boolean;returns number

    Deno.webrtc.readRtp(): whether a receiver's RTP packets come as rtp events. 0 or an error code.

  • methodreceiverReadFrames(pc, key, on)(receiver_read_frames)
    :;pc: u32→ number;key: u32→ number;on: bool→ boolean;returns number

    Deno.webrtc.readFrames(): whether a receiver's frames are put together and come as mediaframe events. 0 or an error code.

  • methodreceiverMuted(pc, key, generation)(receiver_muted)
    :;pc: u32→ number;key: u32→ number;generation: u32→ number;returns number

    A receiver's track was muted (its remote side stopped sending): the next RTP packet unmutes it (trackunmute with generation). 0 or an error code.

  • methodsenderSendDtmf(pc, key, event, duration_ms)(sender_send_dtmf)
    :;pc: u32→ number;key: u32→ number;event: u32→ number;duration_ms: u32→ number;returns number

    RTCDTMFSender: one telephone event (event above 15 is 15): 1 when sent, 0 when not, or an error code.

  • methodreceiverRequestKeyFrame(pc, key)(receiver_request_key_frame)
    :;pc: u32→ number;key: u32→ number;returns number

    Asks a receiver's remote sender for a key frame (PLI): 1 when asked, 0 when not, or an error code.

  • methodiceCreate()(ice_create)
    :;returns number

    new RTCIceTransport(): a transport with fresh local parameters, gathering nothing until iceGather. Its handle, or an error code (INVALID_STATE_ERROR before gateAttach(), as pcCreate). Its events (icecandidate, gatheringcomplete, statechange, selectedcandidatepairchange, rolechange) come on its handle, null once it stops.

  • methodiceLocalParameters(ice, out, cap)(ice_local_parameters)
    :;ice: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    getLocalParameters(): [usernameFragment, password] as JSON into out.

  • methodiceGather(ice, servers, relay_only)(ice_gather)
    :;ice: u32→ number;servers: JsStr→ string;relay_only: bool→ boolean;returns number

    gather(options): servers is RTCIceServer[] as JSON (checked for syntax, not used yet, as the built-in op), relay_only the relay gather policy. The binds wait for the gate. 0 or an error code.

  • methodiceStart(ice, ufrag, pwd, controlling)(ice_start)
    :;ice: u32→ number;ufrag: JsStr→ string;pwd: JsStr→ string;controlling: bool→ boolean;returns number

    start(remoteParameters, role). 0 or an error code.

  • methodiceAddRemoteCandidate(ice, candidate)(ice_add_remote_candidate)
    :;ice: u32→ number;candidate: JsStr→ string;returns number

    addRemoteCandidate(candidate): the candidate-attribute value (the address is asked of the gate before it is used). 0 or an error code.

  • methodiceSelectedPair(ice, out, cap)(ice_selected_pair)
    :;ice: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    getSelectedCandidatePair()'s addresses, or null, as JSON into out.

  • methodiceStop(ice)(ice_stop)
    :;ice: u32→ number;returns number

    stop(): removes and stops the transport (an unknown handle is ignored); its events end with a null event. 0 or an error code.

  • methodgenerateCertificate(algorithm, expires_at_ms, out, cap) → Promise(generate_certificate)
    :;algorithm: JsStr→ string;expires_at_ms: f64→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns Promise<number>

    RTCPeerConnection.generateCertificate(keygenAlgorithm), off JavaScript's thread: algorithm is WebCrypto's dictionary as JSON, expiresAtMs the 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), to out and 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.

  • methodcertificateToPem(id, out, cap)(certificate_to_pem)
    :;id: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    Deno.webrtc.exportCertificate: the key and certificate as PEM, into out.

  • methodcertificateFromPem(pem, out, cap)(certificate_from_pem)
    :;pem: JsStr→ string;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    Imports an exported certificate: { id, expires, fingerprints } as JSON into out.

  • methodcertificateDrop(id)(certificate_drop)
    :;id: u32→ number;returns void

    Forgets certificate id (its RTCCertificate was collected); the connections given it keep their copy.

  • methodcapabilities(kind, sender, out, cap)(capabilities)
    :;kind: JsStr→ string;sender: bool→ boolean;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    RTCRtpSender/Receiver.getCapabilities(kind) as JSON (null for an unknown kind), into out.

  • methodfakeMediaDevices()(fake_media_devices)
    :;returns boolean

    Whether the fake capture devices are on (DENO_FAKE_MEDIA_DEVICES=1).

  • methodnetworkCreate(options, out, cap) → Promise(network_create)
    :;options: JsStr→ string;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns Promise<number>

    Deno.webrtc.createNetwork(options) (options as JSON), off JavaScript's thread: a port network binds its sockets before it resolves, each bind waiting for the gate's answer (answer the gaterequests 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_CAPABLE for a refused bind) to out and resolves to its length (sizes as generateCertificate).

  • methodnetworkAddresses(network, out, cap)(network_addresses)
    :;network: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    The network's shared UDP addresses (ip:port), a JSON array into out.

  • methodnetworkTcpAddresses(network, out, cap)(network_tcp_addresses)
    :;network: u32→ number;out: OutBuf→ Uint8Array<ArrayBuffer>;cap: u32→ number;returns number

    The network's ICE-TCP listener addresses, a JSON array into out.

  • methodnetworkClose(network)(network_close)
    :;network: u32→ number;returns number

    Closes a network (an unknown handle is ignored). 0 or an error code.

  • methodsetLogLevel(level)(set_log_level)
    :;level: JsStr→ string;returns number

    Deno.webrtc.setLogLevel(level): off, error, warn, info, debug or trace (process-wide; records go to standard error). 0 or TYPE_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 only Deno.dlopen and symbol calls, which --allow-ffi=<this library> permits (no pointer views):
    • strings in: dodo-bindgen's JsStr (a length-prefixed buffer);
    • bytes in: a Uint8Array and its length (dcSend(pc, ch, text, data, data.byteLength));
    • results out: a Uint8Array and its capacity, (out, cap) as the last two arguments; the call returns the result's length n. n <= cap: it is in out[0..n]. n > cap: nothing was written and the result waits in the calling thread's slot: takeResult(out, cap) with cap >= n copies it (returns n; still too small, it returns n and keeps it; nothing waiting, -9). The call never has to run twice.
    • generateCertificate(alg, expiresAtMs, out, cap) and networkCreate(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).
  • 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 in src/events.rs), or the size the oldest needs when it doesn't fit (nothing taken). Allocate drainSize(n) bytes and drain exactly that batch.
  • Waking: setWaker(threadSafeCallback.pointer): the callback gets the engine's id() when events are queued (once until the next drain). A Deno.UnsafeCallback needs a bare --allow-ffi; under a scoped grant, poll with wait(timeoutMs) (resolves to how many events are queued, as soon as one is) and pending().

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, the FakeFrame JSON with "data": null (or null: 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 switches receiverReadRtp, receiverReadFrames, receiverTransform(pc, key, on) (rtp, mediaframe, encodedframe events, 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

  1. gateAttach() (0, or an error code) once the shim can answer. Until then every address is refused and pcCreate fails with InvalidStateError: a connection asks for the interface list as it is made, and a refusal it gets is kept for its life.
  2. Each new question is a gaterequest event on handle 0: {"type":"gaterequest","ticket":7,"kind":"remoteCandidate","dir":"connect","proto":"udp","host":"192.0.2.7","port":4000,"resolvedFrom":null}. kind is iceServer, iceServerResolved, remoteCandidate, sendTo, tcpDial, bind, mdns or interfaces (whose dir, proto, host, port and resolvedFrom are null); port is null for a bind.
  3. 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

  • pcSetRemoteDescription and pcAddIceCandidate are 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's opdone event, {"type":"opdone","op":3} on success or {"type":"opdone","op":4,"error":{"kind":"NotCapable","message":"..."}}. kind is a W3C name (NotCapable for a refused address, InvalidStateError for an operation still waiting when the connection closed, ...). Operations finish in the order they were made.
  • networkCreate(options) resolves to {"network":3} once a port network's sockets are bound (each bind asked of the gate: answer the gaterequests 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>.