Home/docs/guide/Swift integration

Swift integration

Swift & Apple Platforms

liberika-swift is the official SwiftPM library for Apple platforms (macOS 11+, iOS 13+, tvOS 13+). The SDK provides ErikaPlayerView for SwiftUI and ErikaVideoView for AppKit / UIKit. Both manage Metal layer binding and display frame clock scheduling for you.

Installation and import#

Add the package dependency in Xcode:

Xcode Package URL

https://github.com/AimesSoft/liberika-swift

Or add it to the dependencies in Package.swift:

Package.swift

dependencies: [
    .package(url: "https://github.com/AimesSoft/liberika-swift", from: "0.3.8")
]

Import the module in your code:

Swift

import Erika

SwiftPM automatically fetches the prebuilt core binary erika-swift-core-0.3.8.xcframework.zip (macOS universal, iOS device and simulator, tvOS device and simulator). You do not need to configure any native C/C++ dependencies.

Views, threads, and lifecycle#

Two lifecycle rules apply when you use the liberika player:

  • Hold the player strongly: ErikaPlayerView and ErikaVideoView keep only a weak reference to ErikaPlayer. Your ObservableObject, @Observable view model, or view controller must hold the ErikaPlayer instance with a strong reference.
  • Run on the main thread: ErikaPlayer is marked @MainActor, so all playback control and state queries run on the main thread. The SDK serializes calls to the underlying C kernel handle for you.

SwiftUI integration example

import SwiftUI
import Erika

@MainActor
final class VideoPlayerModel: ObservableObject {
    let player: ErikaPlayer

    init() {
        /* Use ErikaPlayer.Configuration to set the output mode, EDR headroom, and upscaling */
        do {
            self.player = try ErikaPlayer(configuration: .init(outputMode: .automatic))
        } catch {
            fatalError("Failed to create player: \(error)")
        }
    }

    func startPlayback() {
        do {
            /* Accepts a URL or local path; you can pass custom HTTP headers */
            try player.open(
                "https://example.com/stream.m3u8",
                httpHeaders: ["User-Agent": "MyApp/1.0"]
            )
            try player.play()
        } catch {
            print("Playback failed: \(error)")
        }
    }

    func pausePlayback() {
        try? player.pause()
    }
}

struct VideoScreen: View {
    @StateObject private var model = VideoPlayerModel()

    var body: some View {
        ErikaPlayerView(player: model.player)
            .aspectRatio(16 / 9, contentMode: .fit)
            .onAppear {
                model.startPlayback()
            }
            .onDisappear {
                model.pausePlayback()
            }
    }
}

Pause playback when the page is temporarily hidden. Call close() when you no longer need the player. To play again after closing, create a new player.

In a UIKit or AppKit project, use ErikaVideoView directly:

UIKit / AppKit integration

let videoView = ErikaVideoView()
videoView.player = model.player
videoView.onError = { error in
    print("Layer rendering error: \(error)")
}
view.addSubview(videoView)

Playback control API#

ErikaPlayer provides type-safe native methods:

MethodSignatureDescription
openopen(_ source: String/URL, httpHeaders: [String: String], httpReadAheadBytes: UInt64, httpBackBufferBytes: UInt64)Synchronously probes the media and parses its tracks, then sets the state to ready.
playplay()Starts background hardware decoding and audio and video presentation.
pause / stoppause() / stop()Pause or stop playback.
seekseek(to seconds: TimeInterval)Seeks to the given time, in seconds.
setPlaybackRatesetPlaybackRate(_ rate: Double)Sets the playback rate (for example, 1.25).
setVolumesetVolume(_ volume: Double)Sets the volume (0.0 to 1.0).
closeclose()Stops the background thread and closes the playback session.

Event polling#

Call pollEvent() to consume the events the player has queued:

Event polling example

func drainEvents() {
    while let event = try? player.pollEvent() {
        switch event.kind {
        case .stateChanged:
            print("Playback state changed: \(event.state)") /* .idle / .opening / .ready / .playing etc. */
        case .durationChanged:
            let seconds = Double(event.durationMicros) / 1_000_000.0
            print("Duration: \(seconds) s")
        case .positionChanged:
            let seconds = Double(event.positionMicros) / 1_000_000.0
            print("Position: \(seconds) s")
        case .bufferingChanged:
            print("Buffering: \(event.buffering)")
        case .error:
            print("Player error: \(event.error ?? event.message ?? \"\")")
        default:
            break
        }
    }
}

Tracks, subtitles, danmaku, and upscaling#

CategorySwift APIDescription
Track managementtracks() / selectAudioTrack(id:) / selectSubtitleTrack(id:)Queries the track list ([ErikaTrack]) and selects the audio and subtitle tracks by ID (pass nil to disable).
External subtitlesaddExternalSubtitle(_ uri:) / removeSubtitleTrack(id:) / setSubtitleScale(_ scale:)Loads external SRT/ASS subtitle files and adjusts the font scale.
DanmakuloadDanmaku(from:) / loadDanmaku(json:) / addDanmakuTrack(from:name:offset:) / danmakuTracks() / clearDanmaku()Loads Bilibili XML or JSON danmaku, with multi-track overlay and timeline offset. For the JSON contract, see the specification.
Neural upscalingsetUpscaler(_ upscaler:)Enables ArtCNN anime 2× upscaling on Apple Silicon (.artCNNC4F16 / .artCNNC4F16DS).
ScreenshotcaptureFrame(width:height:)Captures raw RGBA frame pixel data of the given size from the current rendering pipeline (ErikaFrame).
DiagnosticspresenterStats() / outputStatus() / resourceStatus()Queries decode and render FPS, dropped frame count, Metal memory usage, and EDR headroom status in real time.

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 parameter 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.

Swift

try player.open(
    "https://example.com/video.mp4",
    httpReadAheadBytes: 8 * 1024 * 1024,
    httpBackBufferBytes: 128 * 1024 * 1024
)
liberika v0.3.8 Section Guide License MPL-2.0