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:
ErikaPlayerViewandErikaVideoViewkeep only aweakreference toErikaPlayer. YourObservableObject,@Observableview model, or view controller must hold theErikaPlayerinstance with a strong reference. - Run on the main thread:
ErikaPlayeris 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:
| Method | Signature | Description |
|---|---|---|
| open | open(_ source: String/URL, httpHeaders: [String: String], httpReadAheadBytes: UInt64, httpBackBufferBytes: UInt64) | Synchronously probes the media and parses its tracks, then sets the state to ready. |
| play | play() | Starts background hardware decoding and audio and video presentation. |
| pause / stop | pause() / stop() | Pause or stop playback. |
| seek | seek(to seconds: TimeInterval) | Seeks to the given time, in seconds. |
| setPlaybackRate | setPlaybackRate(_ rate: Double) | Sets the playback rate (for example, 1.25). |
| setVolume | setVolume(_ volume: Double) | Sets the volume (0.0 to 1.0). |
| close | close() | 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高度な機能#
| Category | Swift API | Description |
|---|---|---|
| Track management | tracks() / selectAudioTrack(id:) / selectSubtitleTrack(id:) | Queries the track list ([ErikaTrack]) and selects the audio and subtitle tracks by ID (pass nil to disable). |
| External subtitles | addExternalSubtitle(_ uri:) / removeSubtitleTrack(id:) / setSubtitleScale(_ scale:) | Loads external SRT/ASS subtitle files and adjusts the font scale. |
| Danmaku | loadDanmaku(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 upscaling | setUpscaler(_ upscaler:) | Enables ArtCNN anime 2× upscaling on Apple Silicon (.artCNNC4F16 / .artCNNC4F16DS). |
| Screenshot | captureFrame(width:height:) | Captures raw RGBA frame pixel data of the given size from the current rendering pipeline (ErikaFrame). |
| Diagnostics | presenterStats() / 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
)