Home/docs/guide/Rust integration

Rust integration

Rust Embedding

A Rust host uses Player or PresenterRuntime from the erika crate directly. The host observes state changes through an event channel and subscribes to decoded video frames, audio samples, and subtitles as needed.

Dependencies and build#

Cargo.toml

[dependencies]
erika = { git = "https://github.com/AimesSoft/liberika", tag = "v0.3.8" }

Before you build from source for the first time on Apple platforms, Windows, Android, or OpenHarmony, use xtask to compile the preset LGPL native dependencies (FFmpeg, libass, dav1d, and others):

shell

cargo run -p xtask -- deps build --all --profile lgpl
cargo build -p erika

Playback lifecycle#

src/main.rs

use std::time::Duration;
use erika::{MediaRequest, Player, PlayerConfig, PlayerState};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let player = Player::new(PlayerConfig::default());

    /* 1. Open the media synchronously: probing and track parsing finish before it returns, and the state is already Ready */
    player.open(MediaRequest::new("/path/to/video.mp4"))?;

    /* 2. Start background decoding and clock-driven playback */
    player.play()?;

    /* 3. Playback control: seek posts a command to the worker thread and returns immediately */
    player.pause()?;
    player.seek(Duration::from_millis(1500))?;
    player.set_playback_rate(1.25)?;
    player.stop()?;

    /* 4. Close the player: safely terminates the background worker thread */
    player.close()?;
    Ok(())
}

Method semantics:

  • open probes synchronously: Player::open() demuxes the media, probes stream information, and extracts tracks synchronously. Before it returns Ok(()), it publishes initial events such as DurationChanged and TracksChanged and sets the state to Ready.
  • play starts an asynchronous playback loop: play() wakes the background worker thread to start decoding and synchronizing the audio and video clocks, and the state moves to Playing.
  • seek is non-blocking: seek() posts the target time to the command queue and returns immediately. The background thread then locates the keyframe, whether playback is paused or playing.
  • close reclaims resources safely: close() waits for the background decoding thread to exit before it returns. After that, you can safely drop the Player instance.

MediaRequest supports HTTP(S) URLs and custom request headers:

Network media request with headers

let request = MediaRequest::new("https://example.com/stream.m3u8")
    .with_http_headers(vec![
        ("User-Agent".into(), "CustomPlayer/1.0".into()),
        ("Referer".into(), "https://example.com".into()),
    ]);
player.open(request)?;

Event subscription#

Call player.subscribe() before open() to receive the initial events emitted during open and all later state changes:

Event consumption loop

use erika::{PlayerEvent, PlayerState};

let events = player.subscribe();

while let Ok(event) = events.recv() {
    match event {
        PlayerEvent::StateChanged(PlayerState::Closed) => {
            println!("Player fully closed");
            break;
        }
        PlayerEvent::StateChanged(state) => {
            println!("State changed: {:?}", state);
        }
        PlayerEvent::DurationChanged(duration) => {
            println!("Duration: {:?}", duration);
        }
        PlayerEvent::PositionChanged(pos) => {
            println!("Position: {:?}", pos);
        }
        PlayerEvent::BufferingChanged(is_buffering) => {
            println!("Buffering: {}", is_buffering);
        }
        PlayerEvent::TracksChanged(tracks) => {
            println!("Available tracks: {}", tracks.len());
        }
        PlayerEvent::Error(err) => {
            eprintln!("Player error: {:?}", err);
        }
        _ => {}
    }
}

Frame subscriptions and Presenter hosting#

A Rust host with its own rendering pipeline can subscribe to decoded frames directly:

Subscribe to video, audio, and subtitle frames

let video_rx = player.subscribe_video_frames();
let audio_rx = player.subscribe_audio_frames();
let subtitle_rx = player.subscribe_subtitle_frames();

/* Pull without blocking in the host render loop */
if let Ok(video_frame) = video_rx.try_recv() {
    /* video_frame: pixel format, size, PTS, and a texture handle or CPU memory block */
}
if let Ok(audio_frame) = audio_rx.try_recv() {
    /* audio_frame: PCM samples and channel parameters */
}

Frame subscription channels apply back-pressure: when a queue is full, the new frame waiting to be sent is dropped so playback stays smooth. If you want the kernel to manage the entire GPU presentation path (Metal / D3D11 / wgpu) and the audio clock, use PresenterRuntime directly:

Presentation managed by PresenterRuntime

use erika::presenter::{PresenterConfig, PresenterRuntime};

let mut presenter = PresenterRuntime::new(PresenterConfig::default())?;
presenter.open(MediaRequest::new("/path/to/video.mp4"))?;
presenter.play()?;

/* Call from the display clock callback */
let stats = presenter.render_tick(host_time_seconds)?;

Configuration#

FieldDefaultDescription
name"Erika"Player instance name, used to identify instances in logs.
event_channel_capacity1024Capacity of the internal playback control command queue. Despite its name, this field does not bound subscribed event queues.
playbackPlaybackSessionConfigLow-level decoder and playback session configuration (hardware acceleration preferences, buffer depth, and so on).
rendererAutoPreferred rendering backend.
video_frame_queue_capacity3Buffer depth of the video output frame queue.
audio_frame_queue_capacity192Depth of the audio output frame queue.
subtitle_frame_queue_capacity16Depth of the subtitle event frame queue.

HTTP cache#

httpReadAheadBytes sets how many bytes to read ahead (default 2 MiB). httpBackBufferBytes sets how much already-played data to keep (default 16 MiB). Omit either field or pass 0 to use its default. You can also set the read-ahead default with ERIKA_HTTP_READAHEAD_BYTES.

Backward seeks within the back buffer reuse data that is already downloaded. High-bitrate video needs a larger budget: keeping about 10 seconds of an 80 Mbit/s video takes about 100 MB. The cache is limited by bytes, so it does not correspond to a fixed number of playback seconds.

Rust

let request = MediaRequest::new("https://example.com/video.mp4")
    .with_http_read_ahead_bytes(8 * 1024 * 1024)
    .with_http_back_buffer_bytes(128 * 1024 * 1024);
player.open(request)?;

Version 0.3.1 adds MediaRequest::with_start_position, PlayerEvent::Ended on natural completion, PresenterRuntime::set_subtitle_delay, danmaku-inclusive capture and native frame texture export. An explicit stop does not emit Ended.

External Linux workspaces and dma-buf#

Enable wgpu and explicitly add the matching HAL patch to the consumer workspace root Cargo.toml: Cargo does not inherit a dependency repository’s patch. The Linux SoundTouch build also needs the consumer’s own PIC configuration; see the Linux guide for the complete setup.

Cargo.toml

[dependencies]
erika = { git = "https://github.com/AimesSoft/liberika", tag = "v0.3.8", features = ["wgpu"] }

[patch.crates-io]
wgpu-hal = { git = "https://github.com/AimesSoft/liberika", tag = "v0.3.8" }

Linux integration and PIC setup

export_frame_dmabuf(w, h, scale) drives playback and composites video, subtitles and danmaku, then uses one same-device GPU copy to produce linear RGBA8. GTK / EGL / Wayland hosts need no Vulkan device of their own. Import using raw_fd(), stride() and offset(); fourcc is ABGR8888 and modifier is 0. Slots are reused after three exports, so finish consuming and close the descriptor before reuse. This differs from the independently retained immutable export_frame_texture. The C API has no new dma-buf entry point.

liberika v0.3.8 Section Guide License MPL-2.0