diff --git a/.github/workflows/swift.yml b/.github/workflows/swift.yml index e12d884..51d684c 100644 --- a/.github/workflows/swift.yml +++ b/.github/workflows/swift.yml @@ -28,13 +28,15 @@ jobs: WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS: 1 steps: - uses: actions/checkout@v4 - - name: Install Cairo, FreeType, fontconfig and Wayland for Cacao, Mesa for GL, and WPE WebKit + - name: Install Cairo, FreeType, fontconfig and Wayland for Cacao, Mesa for GL, WPE WebKit, and GStreamer run: | apt-get update apt-get install -y --no-install-recommends cmake ninja-build git libcairo2-dev libfreetype-dev \ libfontconfig-dev libwayland-dev wayland-protocols fonts-dejavu-core \ libegl1 libegl-mesa0 libgles-dev libgl1-mesa-dri \ - libwpewebkit-2.0-1 libwpebackend-fdo-1.0-1 libwayland-server0 + libwpewebkit-2.0-1 libwpebackend-fdo-1.0-1 libwayland-server0 \ + libgstreamer1.0-0 libgstreamer-plugins-base1.0-0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good \ + gstreamer1.0-libav # Debian's SDL is 3.2; PureSwift/SDL needs 3.4. - name: Build SDL3 run: Scripts/build-sdl3.sh /usr -DCMAKE_INSTALL_LIBDIR=lib/$(uname -m)-linux-gnu diff --git a/Dockerfile b/Dockerfile index f1ff239..12de5c4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,9 @@ # Linux environment for building and testing the host: Swift 6.4.2 on # Debian 13, SDL3, Cairo, FreeType, fontconfig and Wayland for Cacao, a font, # Mesa's EGL and GLES 2.0 for GL surfaces (llvmpipe without a GPU), WPE WebKit -# and its FreeDesktop.org backend for web views, which the host loads at run -# time, Python for AppRuntime's scripts, and WABT for its wasm2c shim. +# and its FreeDesktop.org backend for web views and GStreamer for media, which +# the host loads at run time, Python for AppRuntime's scripts, and WABT for its +# wasm2c shim. # # Debian rather than Ubuntu: Ubuntu 26.04 doesn't package WPE WebKit. SDL is # built from source: Debian's is 3.2, and PureSwift/SDL needs 3.4. @@ -29,5 +30,13 @@ RUN cd /usr/share/wabt/wasm2c \ && echo "fb0f00fa46edd9bee433f42a8868c7d082d52e97a699a6a8e2b345a8cd695fcd wasm-rt-impl-tableops.inc" | sha256sum -c - \ && echo "cde415d8cc9299abc8c596892f051f3ec96dae2c84d73cec83a72c7cecad969f wasm-rt-mem-impl-helper.inc" | sha256sum -c - +# GStreamer, for media players: its base and good plugins, and libav's +# decoders for H.264 and AAC. A layer of its own, after SDL's build. +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + libgstreamer1.0-0 libgstreamer-plugins-base1.0-0 gstreamer1.0-plugins-base \ + gstreamer1.0-plugins-good gstreamer1.0-libav \ + && rm -rf /var/lib/apt/lists/* + # SDL's headless driver, for tests and screenshots without a display. ENV SDL_VIDEO_DRIVER=offscreen diff --git a/Documentation/Plan.md b/Documentation/Plan.md index 615002f..3da5b60 100644 --- a/Documentation/Plan.md +++ b/Documentation/Plan.md @@ -52,7 +52,7 @@ contracts. D-Bus is PureSwift/DBus, in Swift, without libdbus. | arm64 and x86_64 Linux with glibc (Debian 13, Ubuntu 24.04+) | armv7, musl | | Native slices, loaded by the runner | `App.wasm`, in an engine in the runner; wasm2c for a target a bundle lacks, before it's installed | | Wayland and X11 through SDL3; a headless driver for tests | Multiple windows | -| `Renderer`, `BluetoothCentral` and friends, GL surfaces, web views, files, settings, model stores, date and number formatting, HTTP, the device, location, documents, motion, NFC tags, the built-ins | | +| `Renderer`, `BluetoothCentral` and friends, GL surfaces, web views, files, settings, model stores, date and number formatting, HTTP, the device, location, documents, motion, NFC tags, media players, the built-ins | | ## 2. Process model @@ -105,8 +105,9 @@ timers for `schedule`. | `LinuxDocuments` | `Documents`: AppRuntime's `HostDocuments` with the desktop portal's file chooser, and bookmarks (§12) | | `LinuxMotion` | `MotionManager` and `Altimeter` over the kernel's IIO sensors in sysfs, and an unavailable `Pedometer` and `ActivityRecognizer` (§13) | | `LinuxNFC` | `NFCReader`, `NFCTag`, `NDEFMessage` and `NDEFRecord` over neard (§14) | +| `LinuxMedia` | `MediaPlayback` over GStreamer's `playbin`, loaded at run time; the player's `VideoPlayer` view shows its pictures (§15) | | `LinuxHostApp` | `main`: reads the app's keys, starts the host, and runs Cacao's SDL loop with one window showing the guest's first renderer | -| `LinuxPackager`, `linux-app` | The packager (§16, [Packager.md](Packager.md)) | +| `LinuxPackager`, `linux-app` | The packager (§17, [Packager.md](Packager.md)) | The package depends on AppRuntime without its `GuestExports` trait, like DarwinAppRuntime, so the slice's `rt_dispatch` and `rt_finalize` are the @@ -695,7 +696,74 @@ ISO 15693 protocol is `ISO-15693`, and there's no `TagFound` signal). `StartEmulation`) and peer-to-peer aren't part of the contract. It hasn't run against real neard and an adapter. -## 15. Testing +## 15. Media + +`LinuxMedia` is the media contracts (AppRuntime's `MediaPlayer.md`) over +GStreamer, and the player draws `VideoPlayer` nodes. The contract is +AppRuntime's `HostMediaPlayback`, which checks each source, finds files +through `HostFiles` and keeps the rules every host shares; this module +gives it a player per `MediaPlayback`, `GStreamerEngine`. + +- **No GStreamer at build time.** As WPE is (§8), the host opens + `libgstreamer-1.0`, `libgstapp-1.0`, GObject and GLib when the media + module registers, locally. Without them there are no players: every + load fails with `unavailable`, and `canPlay` says `no`. The development + image and CI install GStreamer's base and good plugins and libav's + decoders; a desktop has them, or its distro packages them. +- **A `playbin` per player.** Its pictures go to a bin of `videoconvert`, + `videoscale` and an `appsink` that takes RGBA with square pixels and + keeps at most one picture, dropping older ones, so decoding never waits + for the host. Its sound goes to `autoaudiosink`, the desktop's sound + server, through `scaletempo`, so a rate other than 1 keeps the pitch. +- **Polled, never called back.** While a player has a source, the main loop + takes the pipeline's bus messages every 10 ms, and the `appsink`'s latest + picture while a view shows the player. No GStreamer thread calls into the + host, so there are no signal handlers and nothing to hop threads. +- **The contract** maps onto the pipeline: + +| | GStreamer | +|---|---| +| A load | The `uri` (a file's from `gst_filename_to_uri`; `loadData`'s bytes written to a temporary file, removed with the source), then `PAUSED`. Its `ASYNC_DONE`, once prerolled, is `didLoad`: the duration, `n-video` and `n-audio`, and the size of the preroll's picture. A live source (`NO_PREROLL`) has no duration | +| `play`, `pause` | `PLAYING` and `PAUSED`, reported when the pipeline's `STATE_CHANGED` says so. A pause from the view's controls is the user's | +| `seek` | A flushing, accurate seek, at the rate; answered at its `ASYNC_DONE`. While paused the view shows the picture where it landed. A flushing seek while playing passes through `PAUSED`, which isn't reported | +| `setRate` | A seek where playback is, at the new rate | +| `setVolume`, `setMuted` | `volume`, `mute` | +| The end | `EOS`: `didEnd`, paused at the end; playing again starts from the start. Looping seeks to the start instead, so it isn't gapless | +| Time | `didChangeTime` at the interval while playing, from the pipeline's position | +| Buffering | A URL's `BUFFERING` messages: below 100% the pipeline pauses and the player is `buffering`; at 100% it plays again if it should. `didChangeBuffer` is the buffering query's range for a URL, and the rest of a file | +| Errors | The bus's `ERROR`, by `GError` domain and code: a resource not found, or a server's refusal, `notFound`; one that can't be read, `network` for a URL; a sink that won't open, `unavailable`; no type, no decoder or a missing plugin, `unsupportedFormat`; decoding and demuxing, `decoding` | + +- **`canPlay`** asks GStreamer's registry: a demuxer or parser for the MIME + type's container (`video/mp4` is `video/quicktime`, `audio/mpeg` MPEG-1 + audio), and decoders for the codecs `MediaPlayer.md` puts in it (H.264 + and AAC in MP4). Both is `probably`; the container alone `maybe`. A type + without a mapping is tried as GStreamer's own name. +- **The view** (`Sources/LinuxUI/HostVideoPlayer.swift`): the latest + picture as an `Image(pixels:)`, fitted, filled or stretched as the node's + `scaling` asks, on black. Unless `controls` is `none`, a bar over it has + play and pause, a scrubber that seeks when it's let go, and the time. + The player keeps playing when the view goes. The synced `NodeView` has + no `VideoPlayer` case yet, so `HostNodeViews` draws it; DarwinUI's later + revisions draw `GLSurface`, `WebView` and `VideoPlayer` through + providers, which a sync will have to set instead. +- **`audio`** asks for nothing, as everywhere. +- **Not yet**: + - What's playing outside the window (NowPlaying): MPRIS on the session + bus. The desktop doesn't send an app to the background, so a player + plays on with its window hidden, and `setPlaysInBackground` is refused. + - Interruptions and unplugged headphones: the sound server doesn't tell + a client, short of PulseAudio's corking. + - Hardware decoding: GStreamer's VA-API and V4L2 decoders would need the + sandbox's `/dev` (AppRuntime's §7.8). Pictures are copied once from + the `appsink` and drawn by Cairo, which is fine for a small video and + costly for 1080p. + - A frame for each of several views of one player: the last view to + appear gets the pictures. + - Sound has been played only into `fakesink`, and nothing has been heard + through a real sound server. The view has been laid out, not looked + at: no app here shows a video yet. + +## 16. Testing - `LinuxUI`: DarwinUI's tests, on Cacao (§5). - `LinuxBluetooth`: the contract against a fake `BlueZBus` that plays @@ -778,6 +846,17 @@ ISO 15693 protocol is `ISO-15693`, and there's no `TagFound` signal). write, a read-only tag, locking and raw commands. neard's records as NDEF and back, and the NDEF encoding. The packager accepts the contracts with `nfc`. +- `LinuxMedia`: the contract over real GStreamer, with sound into + `fakesink` and files the tests make: a WAV, and a second of Motion JPEG + in AVI that GStreamer encodes. Loading, playing before it's loaded, and + the end; pausing, seeking, and a seek replaced by another; the controls' + pause, which is the user's, and their seek; looping; the rate; bytes as a + file; what isn't media, a missing file, and a URL without `network`; a + video's size, its preroll's picture, pictures while playing and after a + seek; what the registry plays. GStreamer's errors and MIME types as the + contract has them. `VideoPlayer` nodes lay out in `LinuxUI`'s tests, + with and without controls. The packager accepts the contracts with + `audio`. - End to end: AppRuntime's `ExampleUI`, `ExampleGL` and `ExampleModel` bundles, their `linux-arm64` `libapp.so` loaded by `linux-app-host` and run headless with SDL's `offscreen` driver, each first frame saved with @@ -790,7 +869,7 @@ ISO 15693 protocol is `ISO-15693`, and there's no `TagFound` signal). `bluetoothd`. Real GeoClue needs a session with an agent, or the app allowed in `geoclue.conf`. -## 16. Phases +## 17. Phases 1. **Host runtime and player**: `LinuxHost`, `LinuxUI`, `LinuxBluetooth`, `LinuxHostApp`; `ExampleUI` runs in Docker. @@ -801,12 +880,12 @@ ISO 15693 protocol is `ISO-15693`, and there's no `TagFound` signal). 3. **More contracts**: formatting and HTTP are done: AppRuntime's `RuntimeFormatting` and `RuntimeNetworking` (§3), and so are the device (§10), location (§11), over GeoClue2, documents (§12), over - the desktop portal, motion (§13), over IIO, and NFC (§14), over - neard. + the desktop portal, motion (§13), over IIO, NFC (§14), over neard, + and media (§15), over GStreamer. 4. **Player**: what DarwinUI and Cacao add: Cacao's AT-SPI bridge, input replay for end-to-end tests. -## 17. Open questions +## 18. Open questions - **Permissions.** Desktop Linux has no prompts for Bluetooth; Flatpak's portals cover location and the camera. `Permissions.request` answers from diff --git a/Package.swift b/Package.swift index 5fedb54..eecab78 100644 --- a/Package.swift +++ b/Package.swift @@ -71,6 +71,7 @@ let package = Package( .library(name: "LinuxLocation", targets: ["LinuxLocation"]), .library(name: "LinuxMotion", targets: ["LinuxMotion"]), .library(name: "LinuxNFC", targets: ["LinuxNFC"]), + .library(name: "LinuxMedia", targets: ["LinuxMedia"]), .library(name: "LinuxHostApp", targets: ["LinuxHostApp"]), .executable(name: "linux-app-host", targets: ["LinuxAppHost"]), .executable(name: "linux-app", targets: ["LinuxAppTool"]), @@ -109,7 +110,7 @@ let package = Package( // over Cacao's SwiftUI. .target( name: "LinuxUI", - dependencies: ["LinuxHost", "LinuxGraphics", "LinuxWebKit", runtime("DynamicUI"), runtime("DynamicRuntime"), runtime("RuntimeNative")] + swiftUI, + dependencies: ["LinuxHost", "LinuxGraphics", "LinuxWebKit", "LinuxMedia", runtime("DynamicUI"), runtime("DynamicRuntime"), runtime("RuntimeNative")] + swiftUI, exclude: ["DARWINUI_REVISION"], swiftSettings: host ), @@ -221,6 +222,16 @@ let package = Package( swiftSettings: host ), + // MARK: - Media + + // GStreamer's playbin, opened at run time. + .target( + name: "LinuxMedia", + dependencies: ["LinuxHost", runtime("DynamicMedia"), runtime("DynamicRuntime"), runtime("RuntimeMedia"), runtime("RuntimeHost"), + runtime("RuntimeCore"), runtime("RuntimeNative")], + swiftSettings: host + ), + // MARK: - App // What the runner's process supplies that libc may not @@ -228,7 +239,7 @@ let package = Package( .target(name: "CLinuxHost"), .target( name: "LinuxHostApp", - dependencies: ["LinuxHost", "LinuxUI", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", "CLinuxHost", runtime("CRuntime"), runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), + dependencies: ["LinuxHost", "LinuxUI", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", "LinuxMedia", "CLinuxHost", runtime("CRuntime"), runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicGraphics"), .product(name: "CacaoSDL", package: "Cacao")], swiftSettings: host ), @@ -252,7 +263,7 @@ let package = Package( // doesn't build Cacao. .target( name: "LinuxPackager", - dependencies: ["LinuxHost", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicUI"), + dependencies: ["LinuxHost", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", "LinuxMedia", runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicUI"), .product(name: "Crypto", package: "swift-crypto")] ), .executableTarget( @@ -288,6 +299,8 @@ let package = Package( runtime("DynamicFiles"), runtime("RuntimeHost"), runtime("RuntimeNative"), .product(name: "DBus", package: "DBus")], swiftSettings: host), + .testTarget(name: "LinuxMediaTests", dependencies: ["LinuxMedia", runtime("DynamicMedia"), runtime("RuntimeMedia"), runtime("RuntimeHost")], + swiftSettings: host), .testTarget(name: "LinuxMotionTests", dependencies: ["LinuxMotion", runtime("DynamicMotion")], swiftSettings: host), .testTarget(name: "LinuxWebKitTests", dependencies: ["LinuxWebKit", runtime("DynamicWebKit")], swiftSettings: host), .testTarget(name: "LinuxPackagerTests", dependencies: ["LinuxPackager", "LinuxHostApp", runtime("RuntimeNetworking")]), diff --git a/README.md b/README.md index 3827284..bf64be6 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ added to its database between launches: | `LinuxDocuments` | `Documents`: AppRuntime's `HostDocuments` with the desktop portal's file chooser on the session bus, for opening, folders and saving, and bookmarks in the app's data ([plan](Documentation/Plan.md) §12) | | `LinuxMotion` | Motion: the accelerometer, gyroscope, magnetometer and barometer from the kernel's IIO sensors in sysfs, device motion fused from them, and a pedometer and activity recognizer that are unavailable ([plan](Documentation/Plan.md) §13) | | `LinuxNFC` | `NFCReader`, `NFCTag`, `NDEFMessage`, `NDEFRecord`: reading and writing NDEF tags through neard on the system bus; no raw commands or locking ([plan](Documentation/Plan.md) §14) | +| `LinuxMedia` | `MediaPlayback`: songs and videos through GStreamer's `playbin`, opened at run time, from files, bytes or URLs; the player's `VideoPlayer` view shows the pictures, with play, pause and a scrubber ([plan](Documentation/Plan.md) §15) | | `LinuxHostApp`, `linux-app-host` | The app's `main`: the host, and Cacao's window and loop. It also registers AppRuntime's `RuntimeFormatting`, dates and numbers over Swift Foundation, and `RuntimeNetworking`, HTTP over `URLSession` and libcurl ([plan](Documentation/Plan.md) §3) | | `LinuxPackager`, `linux-app` | The packager: validation, thinning a bundle to one target, the install tree, PortMaster ports | @@ -72,14 +73,17 @@ added to its database between launches: Swift 6.4.2 (`.swift-version`) on Debian 13; SDL 3.4, Cairo, FreeType, fontconfig and Wayland for Cacao; EGL and GLES 2.0, which GL surfaces load -at run time and apps that draw link (Mesa's draw without a GPU); and WPE -WebKit, which web views load at run time: +at run time and apps that draw link (Mesa's draw without a GPU); WPE +WebKit, which web views load at run time; and GStreamer, with its base and +good plugins and libav's decoders, which media players load at run time: ```sh apt-get install cmake ninja-build git libcairo2-dev libfreetype-dev libfontconfig-dev \ libwayland-dev wayland-protocols fonts-dejavu-core \ libegl1 libegl-mesa0 libgles-dev libgl1-mesa-dri \ - libwpewebkit-2.0-1 libwpebackend-fdo-1.0-1 libwayland-server0 + libwpewebkit-2.0-1 libwpebackend-fdo-1.0-1 libwayland-server0 \ + libgstreamer1.0-0 libgstreamer-plugins-base1.0-0 gstreamer1.0-plugins-base \ + gstreamer1.0-plugins-good gstreamer1.0-libav Scripts/build-sdl3.sh /usr -DCMAKE_INSTALL_LIBDIR=lib/$(uname -m)-linux-gnu swift build swift test diff --git a/Scripts/sync-darwinui.sh b/Scripts/sync-darwinui.sh index 742f7ef..1dbe40a 100755 --- a/Scripts/sync-darwinui.sh +++ b/Scripts/sync-darwinui.sh @@ -8,8 +8,8 @@ # - `#if os(macOS)` code, which is for any platform but iOS: Linux is # neither; # - NodeView, which asks `HostNodeViews` (HostNodeViews.swift) for a type -# it doesn't know before giving up on it: `GLSurface` and `WebView` are -# this host's. +# it doesn't know before giving up on it: `GLSurface`, `WebView` and +# `VideoPlayer` are this host's. # # Files named Host*.swift are this host's own, and stay. # diff --git a/Sources/LinuxHost/LinuxFiles.swift b/Sources/LinuxHost/LinuxFiles.swift index ab029f2..8bcab84 100644 --- a/Sources/LinuxHost/LinuxFiles.swift +++ b/Sources/LinuxHost/LinuxFiles.swift @@ -30,6 +30,18 @@ public enum LinuxFiles: HostModule { /// directories come from the app's identifier and `LinuxBundle`, which /// `AppHost` sets up first. public static func register(in registrar: some ContractRegistrar) { + configureIfNeeded() + HostFilesModule.register(in: registrar) + } + + /// Whether `HostFiles` knows where the app's files are. + nonisolated(unsafe) public private(set) static var isConfigured = false + + /// Says where the app's files are, once: for `Files`, and for modules + /// that find the app's files without it, such as media. + public static func configureIfNeeded() { + guard !isConfigured else { return } + isConfigured = true let identifier = LinuxBundle.info.identifier do { let directories = try self.directories(identifier: identifier, resources: LinuxBundle.resources, environment: environment) @@ -39,7 +51,6 @@ public enum LinuxFiles: HostModule { // Every operation then fails, and says so through its callback. HostLog.error("files: \(error)") } - HostFilesModule.register(in: registrar) } /// The environment the directories come from; replaceable for tests. diff --git a/Sources/LinuxHostApp/HostApp.swift b/Sources/LinuxHostApp/HostApp.swift index 9ea6b50..2f6c463 100644 --- a/Sources/LinuxHostApp/HostApp.swift +++ b/Sources/LinuxHostApp/HostApp.swift @@ -10,6 +10,7 @@ import LinuxDevice import LinuxDocuments import LinuxGraphics import LinuxLocation +import LinuxMedia import LinuxMotion import LinuxNFC import LinuxWebKit @@ -39,11 +40,12 @@ public enum HostApp { /// Bluetooth, GL surfaces and web pages, which the player shows, the /// app's files, settings and model stores, AppRuntime's date and number /// formatting and its HTTP client over Swift Foundation, the device, - /// location, the user's documents, motion sensors and NFC tags. + /// location, the user's documents, motion sensors, NFC tags, and media + /// players, whose pictures the player shows. public static let modules: [any HostModule.Type] = [ DarwinUI.self, LinuxBluetooth.self, LinuxGraphics.self, LinuxWebKit.self, LinuxFiles.self, LinuxDefaults.self, LinuxModelStore.self, HostFormattingModule.self, HostNetworkingModule.self, LinuxDeviceModule.self, LinuxLocation.self, - LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self, + LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self, LinuxMedia.self, ] /// Points AppRuntime's modules at this host: networking's callbacks, diff --git a/Sources/LinuxMedia/GStreamer.swift b/Sources/LinuxMedia/GStreamer.swift new file mode 100644 index 0000000..ee44593 --- /dev/null +++ b/Sources/LinuxMedia/GStreamer.swift @@ -0,0 +1,289 @@ +#if canImport(Glibc) +import Glibc +#elseif canImport(Darwin) +import Darwin +#endif +import LinuxHost + +/// GStreamer, opened at run time (`Plan.md` §15), as WPE WebKit is. +/// +/// Each player is a `playbin`, whose pictures go to an `appsink` as RGBA +/// and whose sound goes to the desktop's sound server. GStreamer decodes +/// and keeps time on its own threads; the host only polls: the pipeline's +/// bus for what happened, and the `appsink` for the latest picture. No +/// GStreamer thread calls into the host. Without GStreamer installed, +/// every load fails with `unavailable`. +final class GStreamer { + + typealias Pointer = UnsafeMutableRawPointer + + typealias CString = UnsafePointer + + // MARK: GStreamer + + let elementFactoryMake: @convention(c) (CString, CString?) -> Pointer? + let elementFactoryFind: @convention(c) (CString) -> Pointer? + let parseBinFromDescription: @convention(c) (CString, Int32, UnsafeMutablePointer?) -> Pointer? + let parseLaunch: @convention(c) (CString, UnsafeMutablePointer?) -> Pointer? + let binGetByName: @convention(c) (Pointer, CString) -> Pointer? + let objectRefSink: @convention(c) (Pointer) -> Pointer? + let objectUnref: @convention(c) (Pointer) -> Void + let elementSetState: @convention(c) (Pointer, Int32) -> Int32 + let elementGetBus: @convention(c) (Pointer) -> Pointer? + let busPop: @convention(c) (Pointer) -> Pointer? + let miniObjectUnref: @convention(c) (Pointer) -> Void + let messageParseError: @convention(c) (Pointer, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> Void + let messageParseStateChanged: @convention(c) (Pointer, UnsafeMutablePointer?, UnsafeMutablePointer?, + UnsafeMutablePointer?) -> Void + let messageParseBuffering: @convention(c) (Pointer, UnsafeMutablePointer?) -> Void + let elementSeek: @convention(c) (Pointer, Double, Int32, Int32, Int32, Int64, Int32, Int64) -> Int32 + let elementQueryPosition: @convention(c) (Pointer, Int32, UnsafeMutablePointer?) -> Int32 + let elementQueryDuration: @convention(c) (Pointer, Int32, UnsafeMutablePointer?) -> Int32 + let elementQuery: @convention(c) (Pointer, Pointer) -> Int32 + let queryNewBuffering: @convention(c) (Int32) -> Pointer? + let queryParseBufferingRange: @convention(c) (Pointer, UnsafeMutablePointer?, UnsafeMutablePointer?, + UnsafeMutablePointer?, UnsafeMutablePointer?) -> Void + let filenameToURI: @convention(c) (CString, UnsafeMutablePointer?) -> UnsafeMutablePointer? + let sampleGetBuffer: @convention(c) (Pointer) -> Pointer? + let sampleGetCaps: @convention(c) (Pointer) -> Pointer? + let capsGetStructure: @convention(c) (Pointer, UInt32) -> Pointer? + let capsFromString: @convention(c) (CString) -> Pointer? + let structureGetInt: @convention(c) (Pointer, CString, UnsafeMutablePointer) -> Int32 + let bufferMap: @convention(c) (Pointer, Pointer, Int32) -> Int32 + let bufferUnmap: @convention(c) (Pointer, Pointer) -> Void + let factoryListGetElements: @convention(c) (UInt64, Int32) -> Pointer? + let factoryListFilter: @convention(c) (Pointer?, Pointer, Int32, Int32) -> Pointer? + let pluginFeatureListFree: @convention(c) (Pointer?) -> Void + + // MARK: The app sink + + let appSinkTryPullSample: @convention(c) (Pointer, UInt64) -> Pointer? + let appSinkTryPullPreroll: @convention(c) (Pointer, UInt64) -> Pointer? + + // MARK: GLib and GObject + + let valueInit: @convention(c) (Pointer, UInt) -> Pointer? + let valueUnset: @convention(c) (Pointer) -> Void + let valueSetDouble: @convention(c) (Pointer, Double) -> Void + let valueSetBoolean: @convention(c) (Pointer, Int32) -> Void + let valueSetString: @convention(c) (Pointer, CString?) -> Void + let valueSetObject: @convention(c) (Pointer, Pointer?) -> Void + let valueGetInt: @convention(c) (Pointer) -> Int32 + let objectSetProperty: @convention(c) (Pointer, CString, Pointer) -> Void + let objectGetProperty: @convention(c) (Pointer, CString, Pointer) -> Void + let free: @convention(c) (Pointer?) -> Void + let errorFree: @convention(c) (Pointer) -> Void + let quarkToString: @convention(c) (UInt32) -> CString? + + // MARK: Constants + + /// GstState, and GstStateChangeReturn. + static let null: Int32 = 1, paused: Int32 = 3, playing: Int32 = 4 + static let changeFailure: Int32 = 0, changeSuccess: Int32 = 1, changeAsync: Int32 = 2, changeNoPreroll: Int32 = 3 + + /// GstMessageType. + static let messageEOS: Int32 = 1, messageError: Int32 = 2, messageBuffering: Int32 = 32, + messageStateChanged: Int32 = 64, messageAsyncDone: Int32 = 1 << 21 + + /// GST_FORMAT_TIME and GST_FORMAT_PERCENT, and GST_FORMAT_PERCENT_MAX. + static let formatTime: Int32 = 3, formatPercent: Int32 = 4, percentMax: Int64 = 1_000_000 + + /// GstSeekFlags: FLUSH and ACCURATE; GstSeekType: NONE and SET. + static let seekFlushAccurate: Int32 = 1 | 2, seekNone: Int32 = 0, seekSet: Int32 = 1 + + /// GstElementFactoryListType: decoders, and what reads a container + /// (demuxers and parsers); GST_RANK_MARGINAL; GST_PAD_SINK. + static let decoders: UInt64 = 1, readers: UInt64 = 32 | 64, rankMarginal: Int32 = 64, padSink: Int32 = 2 + + /// GST_MAP_READ. + static let mapRead: Int32 = 1 + + /// GLib's fundamental types. + static let typeBoolean: UInt = 20, typeInt: UInt = 24, typeDouble: UInt = 60, typeString: UInt = 64, typeObject: UInt = 80 + + /// `GstMessage`'s `type` and `src`, after its `GstMiniObject`; a + /// `GstMapInfo`'s `data` and `size`, and its size; `GError`'s + /// `message`; a `GValue`'s size. Checked against GStreamer 1.26's + /// headers. + static let messageTypeOffset = 64, messageSourceOffset = 80 + static let mapInfoSize = 104, mapDataOffset = 16, mapSizeOffset = 24 + static let errorMessageOffset = 8, valueSize = 24 + + /// GStreamer, initialized; nil when it isn't installed. + static let shared: GStreamer? = GStreamer() + + private init?() { + let names = ["libgstreamer-1.0.so.0", "libgstapp-1.0.so.0", "libgobject-2.0.so.0", "libglib-2.0.so.0"] + // Local, so GStreamer's libraries never stand in for others of the + // same names in the process. + let libraries = names.map { dlopen($0, RTLD_NOW | RTLD_LOCAL) } + guard let gst = libraries[0], let app = libraries[1], let gobject = libraries[2], let glib = libraries[3] else { + HostLog.debug("media: GStreamer isn't installed") + return nil + } + var missing: [String] = [] + func bind(_ library: Pointer, _ name: String, _: T.Type) -> T { + guard let symbol = dlsym(library, name) else { + missing.append(name) + return unsafeBitCast(GStreamer.missingFunction, to: T.self) + } + return unsafeBitCast(symbol, to: T.self) + } + let initCheck = bind(gst, "gst_init_check", (@convention(c) (Pointer?, Pointer?, UnsafeMutablePointer?) -> Int32).self) + elementFactoryMake = bind(gst, "gst_element_factory_make", (@convention(c) (CString, CString?) -> Pointer?).self) + elementFactoryFind = bind(gst, "gst_element_factory_find", (@convention(c) (CString) -> Pointer?).self) + parseBinFromDescription = bind(gst, "gst_parse_bin_from_description", + (@convention(c) (CString, Int32, UnsafeMutablePointer?) -> Pointer?).self) + parseLaunch = bind(gst, "gst_parse_launch", (@convention(c) (CString, UnsafeMutablePointer?) -> Pointer?).self) + binGetByName = bind(gst, "gst_bin_get_by_name", (@convention(c) (Pointer, CString) -> Pointer?).self) + objectRefSink = bind(gst, "gst_object_ref_sink", (@convention(c) (Pointer) -> Pointer?).self) + objectUnref = bind(gst, "gst_object_unref", (@convention(c) (Pointer) -> Void).self) + elementSetState = bind(gst, "gst_element_set_state", (@convention(c) (Pointer, Int32) -> Int32).self) + elementGetBus = bind(gst, "gst_element_get_bus", (@convention(c) (Pointer) -> Pointer?).self) + busPop = bind(gst, "gst_bus_pop", (@convention(c) (Pointer) -> Pointer?).self) + miniObjectUnref = bind(gst, "gst_mini_object_unref", (@convention(c) (Pointer) -> Void).self) + messageParseError = bind(gst, "gst_message_parse_error", + (@convention(c) (Pointer, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> Void).self) + messageParseStateChanged = bind(gst, "gst_message_parse_state_changed", + (@convention(c) (Pointer, UnsafeMutablePointer?, UnsafeMutablePointer?, + UnsafeMutablePointer?) -> Void).self) + messageParseBuffering = bind(gst, "gst_message_parse_buffering", (@convention(c) (Pointer, UnsafeMutablePointer?) -> Void).self) + elementSeek = bind(gst, "gst_element_seek", (@convention(c) (Pointer, Double, Int32, Int32, Int32, Int64, Int32, Int64) -> Int32).self) + elementQueryPosition = bind(gst, "gst_element_query_position", (@convention(c) (Pointer, Int32, UnsafeMutablePointer?) -> Int32).self) + elementQueryDuration = bind(gst, "gst_element_query_duration", (@convention(c) (Pointer, Int32, UnsafeMutablePointer?) -> Int32).self) + elementQuery = bind(gst, "gst_element_query", (@convention(c) (Pointer, Pointer) -> Int32).self) + queryNewBuffering = bind(gst, "gst_query_new_buffering", (@convention(c) (Int32) -> Pointer?).self) + queryParseBufferingRange = bind(gst, "gst_query_parse_buffering_range", + (@convention(c) (Pointer, UnsafeMutablePointer?, UnsafeMutablePointer?, + UnsafeMutablePointer?, UnsafeMutablePointer?) -> Void).self) + filenameToURI = bind(gst, "gst_filename_to_uri", (@convention(c) (CString, UnsafeMutablePointer?) -> UnsafeMutablePointer?).self) + sampleGetBuffer = bind(gst, "gst_sample_get_buffer", (@convention(c) (Pointer) -> Pointer?).self) + sampleGetCaps = bind(gst, "gst_sample_get_caps", (@convention(c) (Pointer) -> Pointer?).self) + capsGetStructure = bind(gst, "gst_caps_get_structure", (@convention(c) (Pointer, UInt32) -> Pointer?).self) + capsFromString = bind(gst, "gst_caps_from_string", (@convention(c) (CString) -> Pointer?).self) + structureGetInt = bind(gst, "gst_structure_get_int", (@convention(c) (Pointer, CString, UnsafeMutablePointer) -> Int32).self) + bufferMap = bind(gst, "gst_buffer_map", (@convention(c) (Pointer, Pointer, Int32) -> Int32).self) + bufferUnmap = bind(gst, "gst_buffer_unmap", (@convention(c) (Pointer, Pointer) -> Void).self) + factoryListGetElements = bind(gst, "gst_element_factory_list_get_elements", (@convention(c) (UInt64, Int32) -> Pointer?).self) + factoryListFilter = bind(gst, "gst_element_factory_list_filter", (@convention(c) (Pointer?, Pointer, Int32, Int32) -> Pointer?).self) + pluginFeatureListFree = bind(gst, "gst_plugin_feature_list_free", (@convention(c) (Pointer?) -> Void).self) + appSinkTryPullSample = bind(app, "gst_app_sink_try_pull_sample", (@convention(c) (Pointer, UInt64) -> Pointer?).self) + appSinkTryPullPreroll = bind(app, "gst_app_sink_try_pull_preroll", (@convention(c) (Pointer, UInt64) -> Pointer?).self) + valueInit = bind(gobject, "g_value_init", (@convention(c) (Pointer, UInt) -> Pointer?).self) + valueUnset = bind(gobject, "g_value_unset", (@convention(c) (Pointer) -> Void).self) + valueSetDouble = bind(gobject, "g_value_set_double", (@convention(c) (Pointer, Double) -> Void).self) + valueSetBoolean = bind(gobject, "g_value_set_boolean", (@convention(c) (Pointer, Int32) -> Void).self) + valueSetString = bind(gobject, "g_value_set_string", (@convention(c) (Pointer, CString?) -> Void).self) + valueSetObject = bind(gobject, "g_value_set_object", (@convention(c) (Pointer, Pointer?) -> Void).self) + valueGetInt = bind(gobject, "g_value_get_int", (@convention(c) (Pointer) -> Int32).self) + objectSetProperty = bind(gobject, "g_object_set_property", (@convention(c) (Pointer, CString, Pointer) -> Void).self) + objectGetProperty = bind(gobject, "g_object_get_property", (@convention(c) (Pointer, CString, Pointer) -> Void).self) + free = bind(glib, "g_free", (@convention(c) (Pointer?) -> Void).self) + errorFree = bind(glib, "g_error_free", (@convention(c) (Pointer) -> Void).self) + quarkToString = bind(glib, "g_quark_to_string", (@convention(c) (UInt32) -> CString?).self) + guard missing.isEmpty else { + HostLog.error("media: GStreamer lacks \(missing.joined(separator: ", "))") + return nil + } + var error: Pointer? + guard initCheck(nil, nil, &error) != 0 else { + HostLog.error("media: GStreamer didn't start: \(error.map { Self.message(of: $0) } ?? "no reason")") + return nil + } + } + + private static let missingFunction: @convention(c) () -> Void = { } + + /// A `GError`'s message. + static func message(of error: Pointer) -> String { + error.load(fromByteOffset: errorMessageOffset, as: UnsafePointer?.self).map { String(cString: $0) } ?? "" + } + + // MARK: Properties + + func set(_ object: Pointer, _ name: String, double value: Double) { + withValue(Self.typeDouble, { valueSetDouble($0, value) }) { objectSetProperty(object, name, $0) } + } + + func set(_ object: Pointer, _ name: String, bool value: Bool) { + withValue(Self.typeBoolean, { valueSetBoolean($0, value ? 1 : 0) }) { objectSetProperty(object, name, $0) } + } + + func set(_ object: Pointer, _ name: String, string value: String?) { + withValue(Self.typeString, { pointer in + if let value { + value.withCString { valueSetString(pointer, $0) } + } else { + valueSetString(pointer, nil) + } + }) { objectSetProperty(object, name, $0) } + } + + func set(_ object: Pointer, _ name: String, object value: Pointer?) { + withValue(Self.typeObject, { valueSetObject($0, value) }) { objectSetProperty(object, name, $0) } + } + + func int(_ object: Pointer, _ name: String) -> Int32 { + var result: Int32 = 0 + withValue(Self.typeInt, { objectGetProperty(object, name, $0) }) { result = valueGetInt($0) } + return result + } + + /// A `GValue` of `type`, zeroed as `G_VALUE_INIT`, filled and used, + /// then unset. + private func withValue(_ type: UInt, _ fill: (Pointer) -> Void, _ use: (Pointer) -> Void) { + let value = Pointer.allocate(byteCount: Self.valueSize, alignment: 8) + value.initializeMemory(as: UInt8.self, repeating: 0, count: Self.valueSize) + defer { value.deallocate() } + _ = valueInit(value, type) + fill(value) + use(value) + valueUnset(value) + } + + // MARK: Messages + + /// A message's `GstMessageType`, and the object that posted it. + func type(of message: Pointer) -> Int32 { + message.load(fromByteOffset: Self.messageTypeOffset, as: Int32.self) + } + + func source(of message: Pointer) -> Pointer? { + message.load(fromByteOffset: Self.messageSourceOffset, as: Pointer?.self) + } + + /// An error message's `GError`: its domain's name, its code and its + /// text. + func error(in message: Pointer) -> (domain: String, code: Int32, message: String) { + var error: Pointer? + var debug: UnsafeMutablePointer? + messageParseError(message, &error, &debug) + free(debug) + guard let error else { return ("", 0, "") } + let domain = quarkToString(error.load(as: UInt32.self)).map { String(cString: $0) } ?? "" + let code = error.load(fromByteOffset: 4, as: Int32.self) + let text = Self.message(of: error) + errorFree(error) + return (domain, code, text) + } + + // MARK: The registry + + /// Whether an element of `kinds` takes `caps` on its sink pad. + func hasElement(_ kinds: UInt64, accepting caps: String) -> Bool { + guard let parsed = capsFromString(caps) else { return false } + defer { miniObjectUnref(parsed) } + let all = factoryListGetElements(kinds, Self.rankMarginal) + defer { pluginFeatureListFree(all) } + let matching = factoryListFilter(all, parsed, Self.padSink, 0) + defer { pluginFeatureListFree(matching) } + return matching != nil + } + + /// Whether GStreamer has an element called `name`. + func hasFactory(_ name: String) -> Bool { + guard let factory = elementFactoryFind(name) else { return false } + objectUnref(factory) + return true + } +} diff --git a/Sources/LinuxMedia/GStreamerEngine.swift b/Sources/LinuxMedia/GStreamerEngine.swift new file mode 100644 index 0000000..f678cb7 --- /dev/null +++ b/Sources/LinuxMedia/GStreamerEngine.swift @@ -0,0 +1,579 @@ +import DynamicMedia +import Foundation +import LinuxHost +import RuntimeMedia + +/// One picture of a video: RGBA, `width * 4` bytes a row. +public struct VideoFrame: Sendable { + + public var data: Data + + public var width: Int + + public var height: Int +} + +/// `HostMediaPlayback`'s engine: a GStreamer `playbin`, one source at a +/// time (`Plan.md` §15). Main loop only. +/// +/// GStreamer decodes, keeps time and syncs sound to picture on its own +/// threads. While there's a source, the main loop polls the pipeline's bus +/// for what happened, and reports it to the `HostMediaPlayback` this was +/// made for; a `VideoPlayer` view that shows it gets the latest picture at +/// each turn. +public final class GStreamerEngine: MediaEngine { + + private let gst: GStreamer + + private weak var playback: HostMediaPlayback? + + /// The `playbin`, and the `appsink` its pictures go to. + private let pipeline: GStreamer.Pointer + + private let frames: GStreamer.Pointer? + + private let bus: GStreamer.Pointer? + + /// What was last reported: `nil` while a source loads, and without one. + private var reported: MediaState? + + /// Whether a source is loading. + private var loading = false + + /// The state asked of the pipeline: paused or playing. + private var target = GStreamer.paused + + /// A pause this engine asked for, rather than the view's controls. + private var expectsPause = false + + /// Waiting for data: the pipeline is paused while `target` is playing. + private var buffering = false + + /// At the end, and not looping: playing starts again from the start. + private var atEnd = false + + private var isNetwork = false + + private var rate: Float = 1 + + private var looping = false + + private var interval: Int64 = 500_000_000 + + private var lastTime: Int64 = 0 + + private var lastBuffer: Double? + + private var seekCompletion: ((Bool) -> Void)? + + private var duration: Double? + + /// `loadData`'s bytes, as a file GStreamer reads. + private var temporaryFile: String? + + private var timer: MainLoop.TimerToken? + + /// How often the main loop polls while there's a source. + static let pollInterval: Int64 = 10_000_000 + + /// The picture's size in pixels; zero for sound alone. + public private(set) var videoSize = (width: 0, height: 0) + + /// The latest picture, while a view shows this player, and the one + /// shown when playback last stopped. + public private(set) var frame: VideoFrame? + + /// Called with each new picture while a view shows this player. + public var display: ((VideoFrame) -> Void)? { + didSet { + if display != nil, let frame { + display?(frame) + } + } + } + + /// Called when what the player's controls show changes: whether it's + /// playing, its time, its duration. + public var changed: (() -> Void)? + + init?(playback: HostMediaPlayback) { + guard let gst = GStreamer.shared, let playbin = gst.elementFactoryMake("playbin", nil) else { + return nil + } + self.gst = gst + self.playback = playback + pipeline = gst.objectRefSink(playbin) ?? playbin + // Pictures as RGBA, square pixels, at most one waiting: one that + // isn't taken in time is dropped, and decoding never waits for the + // main loop. + let description = "videoconvert ! videoscale ! appsink name=frames max-buffers=1 drop=true enable-last-sample=false " + + "caps=\"video/x-raw,format=RGBA,pixel-aspect-ratio=1/1\"" + var error: GStreamer.Pointer? + if let sink = gst.parseBinFromDescription(description, 1, &error) { + frames = gst.binGetByName(sink, "frames") + gst.set(pipeline, "video-sink", object: sink) + } else { + frames = nil + HostLog.error("media: no picture sink: \(error.map { GStreamer.message(of: $0) } ?? "")") + if let error { gst.errorFree(error) } + } + if let audio = LinuxMedia.audioSink, let sink = gst.parseBinFromDescription(audio, 1, nil) { + gst.set(pipeline, "audio-sink", object: sink) + } + // The contract's rates keep the pitch. + if let tempo = gst.elementFactoryMake("scaletempo", nil) { + gst.set(pipeline, "audio-filter", object: tempo) + } + bus = gst.elementGetBus(pipeline) + } + + deinit { + stopPolling() + _ = gst.elementSetState(pipeline, GStreamer.null) + if let frames { gst.objectUnref(frames) } + if let bus { gst.objectUnref(bus) } + gst.objectUnref(pipeline) + removeTemporaryFile() + } + + // MARK: Loading + + public func load(_ source: HostMediaSource) { + clear() + let uri: String + switch source { + case .url(let url): + uri = url + isNetwork = true + case .file(let path): + guard let found = fileURI(path) else { + playback?.failed(MediaError(.notFound, message: "not a path GStreamer opens")) + return + } + uri = found + case .data(let bytes, let mimeType): + let path = NSTemporaryDirectory() + "/media-\(UUID().uuidString).\(MediaValues.fileExtension(mimeType))" + guard FileManager.default.createFile(atPath: path, contents: Data(bytes)), let found = fileURI(path) else { + playback?.failed(MediaError(.unavailable, message: "couldn't keep the data")) + return + } + temporaryFile = path + uri = found + } + gst.set(pipeline, "uri", string: uri) + loading = true + target = GStreamer.paused + startPolling() + // Paused at the start: GStreamer prerolls, then says so. + switch gst.elementSetState(pipeline, GStreamer.paused) { + case GStreamer.changeSuccess: + finishLoading() + case GStreamer.changeNoPreroll: + // Live: nothing to preroll, and no duration. + finishLoading(live: true) + case GStreamer.changeFailure: + // The bus says why. + poll() + if loading { + fail(MediaError(.unknown, message: "GStreamer didn't open the source")) + } + default: + break + } + } + + public func unload() { + clear() + } + + private func clear() { + stopPolling() + _ = gst.elementSetState(pipeline, GStreamer.null) + // What the last source left on the bus is of no interest now. + if let bus { + while let message = gst.busPop(bus) { + gst.miniObjectUnref(message) + } + } + completeSeek(false) + reported = nil + loading = false + target = GStreamer.paused + expectsPause = false + buffering = false + atEnd = false + isNetwork = false + duration = nil + lastBuffer = nil + videoSize = (0, 0) + frame = nil + removeTemporaryFile() + changed?() + } + + private func fileURI(_ path: String) -> String? { + guard let uri = gst.filenameToURI(path, nil) else { return nil } + defer { gst.free(uri) } + return String(cString: uri) + } + + private func removeTemporaryFile() { + if let temporaryFile { + try? FileManager.default.removeItem(atPath: temporaryFile) + self.temporaryFile = nil + } + } + + /// The source has prerolled: what it holds is known. + private func finishLoading(live: Bool = false) { + guard loading else { return } + loading = false + let videos = gst.int(pipeline, "n-video") + let audios = gst.int(pipeline, "n-audio") + duration = live ? nil : queryDuration() + if let frames, let sample = gst.appSinkTryPullPreroll(frames, 0) { + take(sample) + } + reported = .paused + // A live source's streams may not be known yet: it's taken to have + // sound. + playback?.loaded(duration: duration, width: videoSize.width, height: videoSize.height, + hasAudio: audios > 0 || (live && videos == 0), hasVideo: videos > 0 || videoSize.width > 0) + reportBuffer() + changed?() + } + + private func queryDuration() -> Double? { + var nanoseconds: Int64 = 0 + guard gst.elementQueryDuration(pipeline, GStreamer.formatTime, &nanoseconds) != 0, nanoseconds >= 0 else { + return nil + } + return Double(nanoseconds) / 1e9 + } + + private func fail(_ error: MediaError) { + loading = false + reported = .failed + completeSeek(false) + stopPolling() + _ = gst.elementSetState(pipeline, GStreamer.null) + playback?.failed(error) + changed?() + } + + // MARK: Playing + + public func play() { + guard let current = reported, current != .failed else { return } + if atEnd { + atEnd = false + seek(nanoseconds: 0) + } + expectsPause = false + target = GStreamer.playing + if !buffering { + _ = gst.elementSetState(pipeline, GStreamer.playing) + } + } + + public func pause() { + pause(requested: true) + } + + /// The player's controls: a pause the user asked for. + public func userPause() { + pause(requested: false) + } + + /// The player's controls: play, through the contract, so a source that + /// hasn't loaded starts when it has. + public func userPlay() { + playback?.play() + } + + private func pause(requested: Bool) { + guard target == GStreamer.playing else { return } + expectsPause = requested + target = GStreamer.paused + _ = gst.elementSetState(pipeline, GStreamer.paused) + if buffering { + // Already paused for data: no change of state will come. + report(.paused) + } + } + + /// Says a state, once. + private func report(_ state: MediaState) { + guard let current = reported, current != .failed, current != state else { return } + reported = state + reportTime() + if state == .paused { + let reason: MediaPauseReason = expectsPause ? .requested : .user + expectsPause = false + playback?.stateChanged(.paused, reason: reason) + } else { + playback?.stateChanged(state) + } + changed?() + } + + private func reachedEnd() { + guard reported != nil else { return } + if looping { + seek(nanoseconds: 0) + reportTime() + return + } + target = GStreamer.paused + _ = gst.elementSetState(pipeline, GStreamer.paused) + atEnd = true + reported = .paused + reportTime(rate: 0) + playback?.ended() + changed?() + } + + // MARK: Time + + public var currentTime: Double { + if atEnd, let duration { + return duration + } + var nanoseconds: Int64 = 0 + guard gst.elementQueryPosition(pipeline, GStreamer.formatTime, &nanoseconds) != 0, nanoseconds >= 0 else { + return 0 + } + return Double(nanoseconds) / 1e9 + } + + /// The source's duration, once it's loaded: `nil` for a live stream. + public var knownDuration: Double? { + duration + } + + /// Whether it's playing, or about to. + public var isPlaying: Bool { + target == GStreamer.playing + } + + public func seek(to position: Double, completion: @escaping (Bool) -> Void) { + guard reported != nil, reported != .failed else { + completion(false) + return + } + completeSeek(false) + atEnd = false + guard seek(nanoseconds: Int64(max(position, 0) * 1e9)) else { + completion(false) + return + } + seekCompletion = completion + } + + /// The player's controls: a seek the guest learns of from the time. + public func userSeek(to position: Double) { + seek(to: position) { [weak self] _ in + self?.reportTime() + self?.changed?() + } + } + + /// Flushes and goes exactly there, at the rate. + @discardableResult + private func seek(nanoseconds: Int64) -> Bool { + gst.elementSeek(pipeline, Double(rate), GStreamer.formatTime, GStreamer.seekFlushAccurate, + GStreamer.seekSet, nanoseconds, GStreamer.seekNone, -1) != 0 + } + + private func completeSeek(_ finished: Bool) { + if let completion = seekCompletion { + seekCompletion = nil + completion(finished) + } + } + + private func reportTime(rate: Float? = nil) { + lastTime = MainLoop.now() + playback?.timeChanged(position: currentTime, rate: rate ?? (reported == .playing ? self.rate : 0)) + } + + public func setTimeUpdateInterval(_ seconds: Double) { + interval = Int64(seconds * 1e9) + } + + /// Seconds loaded past the position: what the buffering query says for + /// a URL, and the rest of a file. + private func reportBuffer() { + let position = currentTime + var seconds: Double? + if isNetwork { + if let query = gst.queryNewBuffering(GStreamer.formatTime) { + if gst.elementQuery(pipeline, query) != 0 { + var format: Int32 = 0 + var stop: Int64 = -1 + gst.queryParseBufferingRange(query, &format, nil, &stop, nil) + if stop >= 0, format == GStreamer.formatTime { + seconds = Double(stop) / 1e9 - position + } else if stop >= 0, format == GStreamer.formatPercent, let duration { + seconds = Double(stop) / Double(GStreamer.percentMax) * duration - position + } + } + gst.miniObjectUnref(query) + } + } else if let duration { + seconds = duration - position + } + guard let seconds else { return } + let buffered = max(seconds, 0) + guard lastBuffer.map({ abs($0 - buffered) >= 0.25 }) ?? true else { return } + lastBuffer = buffered + playback?.bufferChanged(buffered) + } + + // MARK: Settings + + public func setRate(_ rate: Float) { + self.rate = rate + guard reported != nil, reported != .failed, !loading else { return } + // A seek where it is, at the new rate. + let position = Int64(currentTime * 1e9) + seek(nanoseconds: position) + reportTime() + } + + public func setVolume(_ volume: Float) { + gst.set(pipeline, "volume", double: Double(min(max(volume, 0), 1))) + } + + public func setMuted(_ muted: Bool) { + gst.set(pipeline, "mute", bool: muted) + } + + public func setLooping(_ looping: Bool) { + self.looping = looping + } + + // MARK: Polling + + private func startPolling() { + guard timer == nil else { return } + timer = MainLoop.shared.schedule(after: Self.pollInterval) { [weak self] in + guard let self else { return } + self.timer = nil + self.poll() + if self.reported != .failed, self.reported != nil || self.loading { + self.startPolling() + } + } + } + + private func stopPolling() { + if let timer { + MainLoop.shared.cancel(timer) + self.timer = nil + } + } + + /// What happened since the last turn, then the latest picture and the + /// time. + func poll() { + if let bus { + while let message = gst.busPop(bus) { + handle(message) + gst.miniObjectUnref(message) + if reported == .failed { return } + } + } + if display != nil, let frames, let sample = gst.appSinkTryPullSample(frames, 0) { + take(sample) + } + if reported == .playing, MainLoop.now() - lastTime >= interval { + reportTime() + reportBuffer() + changed?() + } + } + + private func handle(_ message: GStreamer.Pointer) { + switch gst.type(of: message) { + case GStreamer.messageError: + let error = gst.error(in: message) + HostLog.debug("media: \(error.domain) \(error.code): \(error.message)") + fail(MediaValues.error(domain: error.domain, code: error.code, message: error.message, network: isNetwork)) + case GStreamer.messageEOS: + reachedEnd() + case GStreamer.messageAsyncDone: + if loading { + finishLoading() + } else if seekCompletion != nil { + if target == GStreamer.paused, let frames, let sample = gst.appSinkTryPullPreroll(frames, 0) { + // The picture where the seek landed. + take(sample) + } + completeSeek(true) + reportBuffer() + } + case GStreamer.messageStateChanged: + guard gst.source(of: message) == pipeline, !loading else { return } + var new: Int32 = 0 + gst.messageParseStateChanged(message, nil, &new, nil) + if new == GStreamer.playing { + report(.playing) + } else if new == GStreamer.paused { + if target == GStreamer.paused { + report(.paused) + } else if buffering { + report(.buffering) + } + // Otherwise a flushing seek while playing, on its way back. + } + case GStreamer.messageBuffering: + var percent: Int32 = 100 + gst.messageParseBuffering(message, &percent) + buffering(percent) + default: + break + } + } + + /// A network source fills its buffer: it's paused while it does, and + /// plays again when it's full, if it should. + private func buffering(_ percent: Int32) { + guard isNetwork, !loading else { return } + if percent < 100, !buffering { + buffering = true + if target == GStreamer.playing { + _ = gst.elementSetState(pipeline, GStreamer.paused) + } + } else if percent >= 100, buffering { + buffering = false + if target == GStreamer.playing { + _ = gst.elementSetState(pipeline, GStreamer.playing) + } + } + } + + // MARK: Pictures + + /// Copies a sample's picture, and gives it to the view. + private func take(_ sample: GStreamer.Pointer) { + defer { gst.miniObjectUnref(sample) } + guard let caps = gst.sampleGetCaps(sample), let structure = gst.capsGetStructure(caps, 0), + let buffer = gst.sampleGetBuffer(sample) else { return } + var width: Int32 = 0 + var height: Int32 = 0 + guard gst.structureGetInt(structure, "width", &width) != 0, gst.structureGetInt(structure, "height", &height) != 0, + width > 0, height > 0 else { return } + let info = UnsafeMutableRawPointer.allocate(byteCount: GStreamer.mapInfoSize, alignment: 8) + defer { info.deallocate() } + guard gst.bufferMap(buffer, info, GStreamer.mapRead) != 0 else { return } + defer { gst.bufferUnmap(buffer, info) } + let size = Int(width) * Int(height) * 4 + guard let data = info.load(fromByteOffset: GStreamer.mapDataOffset, as: UnsafeRawPointer?.self), + info.load(fromByteOffset: GStreamer.mapSizeOffset, as: Int.self) >= size else { return } + videoSize = (Int(width), Int(height)) + let picture = VideoFrame(data: Data(bytes: data, count: size), width: Int(width), height: Int(height)) + frame = picture + display?(picture) + } +} diff --git a/Sources/LinuxMedia/LinuxMedia.swift b/Sources/LinuxMedia/LinuxMedia.swift new file mode 100644 index 0000000..468b379 --- /dev/null +++ b/Sources/LinuxMedia/LinuxMedia.swift @@ -0,0 +1,108 @@ +import DynamicMedia +import DynamicRuntime +import LinuxHost +import RuntimeCore +import RuntimeHost +import RuntimeMedia +import RuntimeNative + +/// The media contracts (`MediaPlayer.md`, `Plan.md` §15): `MediaPlayback` +/// and its delegate, over GStreamer, and the pictures the player's +/// `VideoPlayer` view shows. Main loop only. +/// +/// The contract is AppRuntime's `HostMediaPlayback`, which checks each +/// source, finds files through `HostFiles`, and keeps the rules every host +/// shares. This module gives it `playbin`s (`GStreamerEngine`). Without +/// GStreamer installed it has no players, and every load fails with +/// `unavailable`. +public enum LinuxMedia: HostModule { + + public static var contracts: [ContractDescriptor] { + HostMediaModule.contracts + } + + public static func register(in registrar: some ContractRegistrar) { + // A source in the bundle or the app's files is found through + // `HostFiles`, whether or not the app uses `Files` itself. + LinuxFiles.configureIfNeeded() + configure(clock: (registrar as? NativeRuntime)?.runtime.clock) + HostMediaModule.register(in: registrar) + } + + /// Points `HostMediaPlayback` at GStreamer, the guest's clock and the + /// app's capabilities. + public static func configure(clock: (any HostClock)?) { + HostMediaPlayback.platform = GStreamer.shared == nil ? nil : platform + HostMediaPlayback.clock = clock + HostMediaPlayback.allowsNetwork = networkOverride ?? HostPermissions.declared.contains(.network) + // The desktop doesn't send an app to the background, and nothing + // here shows what's playing outside its window yet. + HostMediaPlayback.allowsBackground = false + } + + public static func permissionProviders() -> [Capability: any PermissionProvider] { + HostMediaModule.permissionProviders() + } + + /// Whether GStreamer loads. + public static var isAvailable: Bool { + GStreamer.shared != nil + } + + /// The engine of the player a `VideoPlayer` node names. + public static func engine(for identifier: Int32) -> GStreamerEngine? { + HostMediaPlayback.player(for: identifier)?.engine as? GStreamerEngine + } + + // MARK: Settings + + /// A pipeline description for the sound, in place of GStreamer's + /// choice of the desktop's sound server: `fakesink sync=true` for + /// tests, where there's none. + nonisolated(unsafe) public static var audioSink: String? = nil + + /// In place of the app's capabilities, for tests: whether URLs play. + nonisolated(unsafe) public static var networkOverride: Bool? = nil + + nonisolated(unsafe) static let platform = GStreamerPlatform() +} + +/// `HostMediaPlayback`'s platform: GStreamer's players, and what its +/// registry can play. +final class GStreamerPlatform: MediaPlatform { + + func makeEngine(for player: HostMediaPlayback) -> any MediaEngine { + GStreamerEngine(playback: player) ?? UnavailableEngine(playback: player) + } + + func canPlay(_ mimeType: String) -> MediaSupport { + guard let gst = GStreamer.shared else { return .no } + return MediaValues.support(mimeType, reads: { gst.hasElement(GStreamer.readers, accepting: $0) }, + decodes: { gst.hasElement(GStreamer.decoders, accepting: $0) }) + } +} + +/// A player GStreamer couldn't make: every load fails. +final class UnavailableEngine: MediaEngine { + + private weak var playback: HostMediaPlayback? + + init(playback: HostMediaPlayback) { + self.playback = playback + } + + func load(_ source: HostMediaSource) { + playback?.failed(MediaError(.unavailable, message: "GStreamer has no playbin")) + } + + func unload() { } + func play() { } + func pause() { } + func seek(to position: Double, completion: @escaping (Bool) -> Void) { completion(false) } + var currentTime: Double { 0 } + func setRate(_ rate: Float) { } + func setVolume(_ volume: Float) { } + func setMuted(_ muted: Bool) { } + func setLooping(_ looping: Bool) { } + func setTimeUpdateInterval(_ seconds: Double) { } +} diff --git a/Sources/LinuxMedia/MediaValues.swift b/Sources/LinuxMedia/MediaValues.swift new file mode 100644 index 0000000..88a48be --- /dev/null +++ b/Sources/LinuxMedia/MediaValues.swift @@ -0,0 +1,107 @@ +import DynamicMedia +import Foundation + +/// What GStreamer says, as the contract has it: its errors, and which MIME +/// types it plays. +enum MediaValues { + + // MARK: Errors + + /// A `GError` from the pipeline's bus as a `MediaError`. `network` is + /// whether the source is a URL: a resource that can't be read there is + /// the connection, and in a file it's the file. + static func error(domain: String, code: Int32, message: String, network: Bool) -> MediaError { + switch (domain, code) { + // GstResourceError: NOT_FOUND, and NOT_AUTHORIZED, which is a + // server's 401 or 403. + case ("gst-resource-error-quark", 3), ("gst-resource-error-quark", 15): + return MediaError(.notFound, message: message) + // OPEN_WRITE and OPEN_READ_WRITE: the sound server or the device + // wouldn't open. + case ("gst-resource-error-quark", 6), ("gst-resource-error-quark", 7): + return MediaError(.unavailable, message: message) + case ("gst-resource-error-quark", _): + return MediaError(network ? .network : .notFound, message: message) + // GstStreamError: NOT_IMPLEMENTED, TYPE_NOT_FOUND, WRONG_TYPE, + // CODEC_NOT_FOUND and FORMAT; GstCoreError's MISSING_PLUGIN. + case ("gst-stream-error-quark", 3), ("gst-stream-error-quark", 4), ("gst-stream-error-quark", 5), + ("gst-stream-error-quark", 6), ("gst-stream-error-quark", 11), ("gst-core-error-quark", 12): + return MediaError(.unsupportedFormat, message: message) + // DECODE and DEMUX. + case ("gst-stream-error-quark", 7), ("gst-stream-error-quark", 9): + return MediaError(.decoding, message: message) + default: + return MediaError(.unknown, message: message) + } + } + + // MARK: Formats + + /// What GStreamer needs for a MIME type: caps a demuxer or parser + /// takes, and the caps of the codecs the contract expects inside it + /// (`MediaPlayer.md`'s formats). + struct Format: Equatable { + var container: String + var codecs: [String] + } + + static func format(_ mimeType: String) -> Format? { + let type = mimeType.split(separator: ";").first.map { $0.trimmingCharacters(in: .whitespaces).lowercased() } ?? "" + switch type { + case "video/mp4", "video/x-m4v", "video/quicktime": + return Format(container: "video/quicktime", codecs: [h264, aac]) + case "audio/mp4", "audio/x-m4a", "audio/m4a", "audio/aac": + return Format(container: "audio/x-m4a", codecs: [aac]) + case "audio/mpeg", "audio/mp3", "audio/mpeg3", "audio/x-mpeg-3": + return Format(container: "audio/mpeg, mpegversion=(int)1", codecs: ["audio/mpeg, mpegversion=(int)1, layer=(int)3"]) + case "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave": + return Format(container: "audio/x-wav", codecs: []) + case "application/vnd.apple.mpegurl", "application/x-mpegurl", "audio/mpegurl", "audio/x-mpegurl": + return Format(container: "application/x-hls", codecs: []) + case "video/webm", "audio/webm": + return Format(container: "video/webm", codecs: []) + case "audio/ogg", "video/ogg", "application/ogg": + return Format(container: "application/ogg", codecs: []) + case "audio/flac", "audio/x-flac": + return Format(container: "audio/x-flac", codecs: []) + case "": + return nil + default: + // GStreamer's own name for it, if it has one. + return Format(container: type, codecs: []) + } + } + + static let h264 = "video/x-h264, stream-format=(string)avc" + + static let aac = "audio/mpeg, mpegversion=(int)4" + + /// Whether GStreamer plays a MIME type, from whether it has what reads + /// the container and decodes what the contract puts inside: `probably` + /// with both, `maybe` with the container alone, since a file can hold + /// other codecs. + static func support(_ mimeType: String, reads: (String) -> Bool, decodes: (String) -> Bool) -> MediaSupport { + guard let format = format(mimeType), reads(format.container) else { + return .no + } + return format.codecs.allSatisfy(decodes) ? .probably : .maybe + } + + // MARK: Files + + /// An extension GStreamer's type finding is helped by, for bytes that + /// become a file. + static func fileExtension(_ mimeType: String) -> String { + switch format(mimeType)?.container { + case "video/quicktime": return "mp4" + case "audio/x-m4a": return "m4a" + case "audio/mpeg, mpegversion=(int)1": return "mp3" + case "audio/x-wav": return "wav" + case "application/x-hls": return "m3u8" + case "video/webm": return "webm" + case "application/ogg": return "ogg" + case "audio/x-flac": return "flac" + default: return "media" + } + } +} diff --git a/Sources/LinuxPackager/Validator.swift b/Sources/LinuxPackager/Validator.swift index a55cfd3..84a5e38 100644 --- a/Sources/LinuxPackager/Validator.swift +++ b/Sources/LinuxPackager/Validator.swift @@ -6,6 +6,7 @@ import LinuxDevice import LinuxDocuments import LinuxGraphics import LinuxLocation +import LinuxMedia import LinuxMotion import LinuxNFC import LinuxWebKit @@ -21,11 +22,11 @@ public enum HostContracts { /// The modules `linux-app-host` registers (`HostApp.modules`): the /// player's contracts, without building the player, Bluetooth, /// graphics, web views, files, settings, model stores, formatting, HTTP, - /// the device, location, documents, motion and NFC. + /// the device, location, documents, motion, NFC and media. nonisolated(unsafe) public static let modules: [any HostModule.Type] = [ PlayerContracts.self, LinuxBluetooth.self, LinuxGraphics.self, LinuxWebKit.self, LinuxFiles.self, LinuxDefaults.self, LinuxModelStore.self, HostFormattingModule.self, HostNetworkingModule.self, LinuxDeviceModule.self, LinuxLocation.self, - LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self, + LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self, LinuxMedia.self, ] public static var provided: [String: ContractDescriptor] { @@ -35,8 +36,9 @@ public enum HostContracts { /// Capabilities some contract here serves: `network` is what lets an /// HTTP session or a web view's page reach the network, `location` /// GeoClue's, `userFiles` the documents' pickers, `motion` the - /// altimeter, which asks nothing, and `nfc` neard's. - public static let capabilities: Set = [.bluetooth, .graphics, .network, .location, .userFiles, .motion, .nfc] + /// altimeter, which asks nothing, `nfc` neard's, and `audio` the media + /// players'. + public static let capabilities: Set = [.bluetooth, .graphics, .network, .location, .userFiles, .motion, .nfc, .audio] } /// The checks of `Packager.md` §1, which install makes before it copies an diff --git a/Sources/LinuxUI/HostNodeViews.swift b/Sources/LinuxUI/HostNodeViews.swift index f7d291b..fea275e 100644 --- a/Sources/LinuxUI/HostNodeViews.swift +++ b/Sources/LinuxUI/HostNodeViews.swift @@ -1,5 +1,6 @@ // Node types this host draws itself, ahead of DarwinUI: `GLSurface` -// (HostGLSurface.swift) and `WebView` (HostWebView.swift). +// (HostGLSurface.swift), `WebView` (HostWebView.swift) and `VideoPlayer` +// (HostVideoPlayer.swift). // Scripts/sync-darwinui.sh keeps this file and has NodeView ask // `HostNodeViews` before it gives up on a type. import DynamicUI @@ -24,6 +25,13 @@ enum HostNodeViews { #else return AnyView(Color.white) #endif + case "VideoPlayer": + #if os(Linux) + return AnyView(HostVideoPlayer(identifier: Int32(clamping: node.props["player"]?.int ?? 0), + scaling: node.props["scaling"]?.string, controls: node.props["controls"]?.string)) + #else + return AnyView(Color.black) + #endif default: return nil } diff --git a/Sources/LinuxUI/HostVideoPlayer.swift b/Sources/LinuxUI/HostVideoPlayer.swift new file mode 100644 index 0000000..e56330d --- /dev/null +++ b/Sources/LinuxUI/HostVideoPlayer.swift @@ -0,0 +1,169 @@ +// `VideoPlayer` nodes: a `GStreamerEngine`'s pictures, scaled as the node +// asks, with this host's controls (`MediaPlayer.md`). Scripts/sync-darwinui.sh +// keeps this file. +#if os(Linux) +import DynamicUI +import Foundation +import LinuxHost +import LinuxMedia +import SwiftUI + +/// A player's picture in the space the view is offered, and its controls +/// unless the node asks for none. +struct HostVideoPlayer: View { + + let identifier: Int32 + + /// `fit`, `fill` or `stretch`. + let scaling: String? + + /// `platform` or `none`. + let controls: String? + + @StateObject private var model = HostVideoPlayerModel() + + var body: some View { + ZStack(alignment: .bottom) { + Color.black + picture + if controls != "none" { + HostVideoControls(model: model) + } + } + .clipped() + .onAppear { model.attach(identifier) } + .onDisappear { model.detach() } + } + + @ViewBuilder + private var picture: some View { + if let frame = model.frame { + let image = Image(pixels: frame.data, width: frame.width, height: frame.height, bytesPerRow: frame.width * 4) + .resizable() + switch scaling { + case "fill": + image.aspectRatio(CGFloat(frame.width) / CGFloat(frame.height), contentMode: .fill) + case "stretch": + image + default: + image.aspectRatio(CGFloat(frame.width) / CGFloat(frame.height), contentMode: .fit) + } + } + } +} + +/// Play and pause, where playback is, and a scrubber when the duration is +/// known. +struct HostVideoControls: View { + + @ObservedObject var model: HostVideoPlayerModel + + var body: some View { + HStack(spacing: 12) { + Button(action: model.toggle) { + if model.isPlaying { + HStack(spacing: 4) { + Rectangle().frame(width: 4, height: 14) + Rectangle().frame(width: 4, height: 14) + } + } else { + Text("▶") + } + } + .foregroundColor(.white) + if let duration = model.duration, duration > 0 { + Slider(value: Binding(get: { model.position }, set: { model.scrub(to: $0) }), in: 0...duration, + onEditingChanged: { editing in model.scrubbing(editing) }) + Text(HostVideoPlayerModel.time(model.position) + " / " + HostVideoPlayerModel.time(duration)) + .foregroundColor(.white) + } else { + Spacer() + Text(HostVideoPlayerModel.time(model.position)) + .foregroundColor(.white) + } + } + .padding(8) + .background(Color.black.opacity(0.5)) + } +} + +/// The view's player, its latest picture and what its controls show. +final class HostVideoPlayerModel: ObservableObject { + + @Published private(set) var frame: VideoFrame? + + @Published private(set) var isPlaying = false + + @Published private(set) var position = 0.0 + + @Published private(set) var duration: Double? + + private var engine: GStreamerEngine? + + /// Where the user is dragging the scrubber to: it seeks when they let + /// go. + private var scrubbed: Double? + + func attach(_ identifier: Int32) { + guard engine == nil else { return } + guard let engine = LinuxMedia.engine(for: identifier) else { + HostLog.warning("media: no player \(identifier) for a VideoPlayer") + return + } + self.engine = engine + engine.changed = { [weak self] in self?.refresh() } + engine.display = { [weak self] frame in self?.frame = frame } + refresh() + } + + func detach() { + engine?.display = nil + engine?.changed = nil + engine = nil + } + + private func refresh() { + guard let engine else { return } + isPlaying = engine.isPlaying + duration = engine.knownDuration + if scrubbed == nil { + position = engine.currentTime + } + if engine.videoSize.width == 0 { + frame = nil + } + } + + func toggle() { + guard let engine else { return } + if engine.isPlaying { + engine.userPause() + } else { + engine.userPlay() + } + refresh() + } + + func scrub(to position: Double) { + scrubbed = position + self.position = position + } + + func scrubbing(_ editing: Bool) { + guard !editing, let target = scrubbed else { return } + scrubbed = nil + engine?.userSeek(to: target) + } + + /// `m:ss`, or `h:mm:ss` from an hour. + static func time(_ seconds: Double) -> String { + let total = Int(max(seconds, 0).rounded(.down)) + let (hours, minutes, rest) = (total / 3600, total / 60 % 60, total % 60) + let padded = rest < 10 ? "0\(rest)" : "\(rest)" + if hours > 0 { + return "\(hours):" + (minutes < 10 ? "0\(minutes)" : "\(minutes)") + ":" + padded + } + return "\(minutes):" + padded + } +} +#endif diff --git a/Tests/LinuxMediaTests/GStreamerTests.swift b/Tests/LinuxMediaTests/GStreamerTests.swift new file mode 100644 index 0000000..ee85af6 --- /dev/null +++ b/Tests/LinuxMediaTests/GStreamerTests.swift @@ -0,0 +1,297 @@ +import DynamicMedia +import Foundation +import LinuxHost +import RuntimeMedia +import Testing +@testable import LinuxMedia + +/// The contract over real GStreamer: `HostMediaPlayback` and its engine, +/// with sound going nowhere, and files the tests make. +@Suite(.serialized, .enabled(if: LinuxMedia.isAvailable, "GStreamer isn't installed")) +final class GStreamerTests { + + let directory: String + + init() throws { + directory = NSTemporaryDirectory() + "/linux-media-\(UUID().uuidString)" + try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true) + // No sound server here; the clock still runs. + LinuxMedia.audioSink = "fakesink sync=true" + LinuxMedia.networkOverride = false + LinuxMedia.configure(clock: nil) + // The tests' files are absolute paths. + HostMediaPlayback.findFile = { _, path in path } + } + + deinit { + HostMediaPlayback.reset() + LinuxMedia.audioSink = nil + LinuxMedia.networkOverride = nil + try? FileManager.default.removeItem(atPath: directory) + } + + // MARK: Helpers + + /// Runs the main loop until `done`, for up to `seconds`: a timer wakes + /// it then, since nothing else may. + func run(for seconds: Double = 5, until done: () -> Bool) { + var expired = false + let timer = MainLoop.shared.schedule(after: Int64(seconds * 1e9)) { expired = true } + defer { MainLoop.shared.cancel(timer) } + MainLoop.shared.run { done() || expired } + } + + func wait(_ seconds: Double) { + run(for: seconds) { false } + } + + /// A mono 16-bit WAV of silence. + static func wav(seconds: Double, rate: Int = 8000) -> [UInt8] { + let samples = Int(Double(rate) * seconds) + var bytes: [UInt8] = [] + func append(_ value: UInt32, _ size: Int) { + for index in 0..> (8 * index))) } + } + bytes += Array("RIFF".utf8); append(UInt32(36 + samples * 2), 4); bytes += Array("WAVE".utf8) + bytes += Array("fmt ".utf8); append(16, 4); append(1, 2); append(1, 2); append(UInt32(rate), 4) + append(UInt32(rate * 2), 4); append(2, 2); append(16, 2) + bytes += Array("data".utf8); append(UInt32(samples * 2), 4) + bytes += [UInt8](repeating: 0, count: samples * 2) + return bytes + } + + func file(_ name: String, _ bytes: [UInt8]) -> String { + let path = directory + "/" + name + FileManager.default.createFile(atPath: path, contents: Data(bytes)) + return path + } + + /// A second of 64 by 48 pictures, ten a second, as Motion JPEG in AVI, + /// which GStreamer makes. + func video() throws -> String { + let path = directory + "/video.avi" + let gst = try #require(GStreamer.shared) + let description = "videotestsrc num-buffers=10 ! video/x-raw,width=64,height=48,framerate=10/1 ! jpegenc ! avimux ! filesink location=\(path)" + let pipeline = try #require(gst.parseLaunch(description, nil)) + defer { + _ = gst.elementSetState(pipeline, GStreamer.null) + gst.objectUnref(pipeline) + } + let bus = try #require(gst.elementGetBus(pipeline)) + defer { gst.objectUnref(bus) } + _ = gst.elementSetState(pipeline, GStreamer.playing) + var finished = false + run { + while !finished, let message = gst.busPop(bus) { + let type = gst.type(of: message) + finished = type == GStreamer.messageEOS || type == GStreamer.messageError + gst.miniObjectUnref(message) + } + return finished + } + #expect(finished) + return path + } + + // MARK: Sound + + @Test func aFileLoadsPlaysAndEnds() { + let path = file("second.wav", Self.wav(seconds: 1)) + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.setTimeUpdateInterval(0.1) + player.loadFile(1, path: path) + // Remembered until it has loaded. + player.play() + run { delegate.ended } + let loaded = delegate.loaded.first + #expect(loaded.map { abs($0.duration - 1) < 0.05 } == true, "\(String(describing: loaded))") + #expect(loaded?.hasAudio == true && loaded?.hasVideo == false && loaded?.width == 0) + #expect(delegate.states.prefix(3).map(\.state) == [1, 2, 3], "loading, paused, playing") + #expect(delegate.states.last.map { $0.state == 2 && $0.reason == 4 } == true, "paused at the end") + #expect(delegate.times.count >= 3, "times while playing") + #expect(delegate.times.contains { $0.rate == 1 }) + #expect(delegate.failures.isEmpty) + } + + @Test func pausingAndSeeking() { + let path = file("long.wav", Self.wav(seconds: 3)) + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.loadFile(1, path: path) + player.play() + run { delegate.states.last?.state == 3 } + wait(0.3) + player.pause() + run { delegate.states.last?.state == 2 } + #expect(delegate.states.last?.reason == 0, "the app asked") + let paused = player.engine?.currentTime ?? 0 + #expect(paused > 0.1 && paused < 1.5, "\(paused)") + player.seek(2, request: 7) + run { !delegate.seeks.isEmpty } + #expect(delegate.seeks.first.map { $0.request == 7 && $0.finished } == true) + #expect(delegate.times.last.map { abs($0.position - 2) < 0.05 && $0.rate == 0 } == true, "\(String(describing: delegate.times.last))") + // Two seeks at once: the first is replaced. + player.seek(0.5, request: 8) + player.seek(1, request: 9) + run { delegate.seeks.count == 3 } + #expect(delegate.seeks.dropFirst().map(\.request) == [8, 9]) + #expect(delegate.seeks.dropFirst().map(\.finished) == [false, true]) + #expect(delegate.failures.isEmpty) + } + + @Test func theControlsPauseAsTheUser() throws { + let path = file("controls.wav", Self.wav(seconds: 2)) + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.loadFile(1, path: path) + run { delegate.states.last?.state == 2 } + let engine = try #require(player.engine as? GStreamerEngine) + engine.userPlay() + run { delegate.states.last?.state == 3 } + engine.userPause() + run { delegate.states.last?.state == 2 } + #expect(delegate.states.last?.reason == 1, "the user's") + engine.userSeek(to: 1.5) + run { delegate.times.last.map { abs($0.position - 1.5) < 0.05 } == true } + #expect(delegate.seeks.isEmpty, "no request of the guest's") + } + + @Test func loopingStartsAgain() { + let path = file("loop.wav", Self.wav(seconds: 0.4)) + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.setLooping(true) + player.loadFile(1, path: path) + player.play() + wait(1.3) + #expect(!delegate.ended, "looping") + #expect(delegate.states.last?.state == 3) + player.setLooping(false) + run { delegate.ended } + #expect(delegate.ended) + } + + @Test func rateIsReported() { + let path = file("rate.wav", Self.wav(seconds: 3)) + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.loadFile(1, path: path) + player.play() + run { delegate.states.last?.state == 3 } + player.setRate(2) + let start = player.engine?.currentTime ?? 0 + wait(0.5) + let advanced = (player.engine?.currentTime ?? 0) - start + #expect(delegate.times.contains { $0.rate == 2 }) + #expect(advanced > 0.7, "twice as fast: \(advanced)") + } + + @Test func bytesPlayAsAFile() { + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.loadData(Self.wav(seconds: 0.5), mimeType: "audio/wav") + run { !delegate.loaded.isEmpty || !delegate.failures.isEmpty } + #expect(delegate.loaded.first.map { abs($0.duration - 0.5) < 0.05 } == true) + player.unload() + #expect(delegate.states.last?.state == 0) + } + + // MARK: Failures + + @Test func whatIsntMediaFails() { + let path = file("noise.wav", Array("this is not a sound".utf8)) + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.loadFile(1, path: path) + run { !delegate.failures.isEmpty } + #expect(delegate.failures.first?.code == MediaError.Code.unsupportedFormat.rawValue, "\(delegate.failures)") + #expect(delegate.states.last?.state == 5) + } + + @Test func aMissingFileIsntFound() { + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.loadFile(1, path: directory + "/nothing.wav") + run { !delegate.failures.isEmpty } + #expect(delegate.failures.first?.code == MediaError.Code.notFound.rawValue, "\(delegate.failures)") + } + + @Test func urlsNeedTheNetwork() { + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.loadURL("https://example.com/song.mp3") + #expect(delegate.failures.first?.code == MediaError.Code.notPermitted.rawValue) + } + + // MARK: Pictures + + @Test func aVideoHasItsSizeAndPictures() throws { + let path = try video() + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.loadFile(1, path: path) + run { !delegate.loaded.isEmpty || !delegate.failures.isEmpty } + let loaded = try #require(delegate.loaded.first, "\(delegate.failures)") + #expect(loaded.width == 64 && loaded.height == 48 && loaded.hasVideo && !loaded.hasAudio) + #expect(abs(loaded.duration - 1) < 0.15, "\(loaded.duration)") + let engine = try #require(LinuxMedia.engine(for: player.identifier())) + let first = try #require(engine.frame, "the preroll's picture") + #expect(first.width == 64 && first.height == 48 && first.data.count == 64 * 48 * 4) + var shown = 0 + engine.display = { _ in shown += 1 } + #expect(shown == 1, "what's there, at once") + player.play() + run { delegate.ended } + #expect(shown >= 5, "pictures as it plays: \(shown)") + // Seeking while paused shows where it landed. + shown = 0 + player.seek(0.5, request: 1) + run { !delegate.seeks.isEmpty } + #expect(shown == 1) + engine.display = nil + } + + @Test func whatGStreamerPlays() { + #expect(HostMediaPlayback.canPlay("audio/wav") == MediaSupport.probably.rawValue) + #expect(HostMediaPlayback.canPlay("audio/mpeg") == MediaSupport.probably.rawValue) + #expect(HostMediaPlayback.canPlay("video/mp4") != MediaSupport.no.rawValue) + #expect(HostMediaPlayback.canPlay("application/x-nothing-plays-this") == MediaSupport.no.rawValue) + } +} + +/// What a player tells the guest. +final class RecordingPlaybackDelegate: MediaPlaybackDelegate { + + var loaded: [(duration: Double, width: Int32, height: Int32, hasAudio: Bool, hasVideo: Bool)] = [] + + var states: [(state: Int32, reason: Int32)] = [] + + var times: [(position: Double, rate: Float)] = [] + + var buffers: [Double] = [] + + var seeks: [(request: Int32, finished: Bool)] = [] + + var ended = false + + var failures: [(code: Int32, message: String)] = [] + + func didLoad(_ duration: Double, width: Int32, height: Int32, hasAudio: Bool, hasVideo: Bool) { + loaded.append((duration, width, height, hasAudio, hasVideo)) + } + + func didChangeState(_ state: Int32, reason: Int32) { states.append((state, reason)) } + + func didChangeTime(_ position: Double, timestamp: Int64, rate: Float) { times.append((position, rate)) } + + func didChangeBuffer(_ seconds: Double) { buffers.append(seconds) } + + func didSeek(_ request: Int32, finished: Bool) { seeks.append((request, finished)) } + + func didEnd() { ended = true } + + func didFail(_ code: Int32, message: String) { failures.append((code, message)) } + + func didReceiveCommand(_ command: Int32) { } +} diff --git a/Tests/LinuxMediaTests/MediaValuesTests.swift b/Tests/LinuxMediaTests/MediaValuesTests.swift new file mode 100644 index 0000000..fe801a7 --- /dev/null +++ b/Tests/LinuxMediaTests/MediaValuesTests.swift @@ -0,0 +1,46 @@ +import DynamicMedia +import Testing +@testable import LinuxMedia + +@Suite struct MediaValuesTests { + + @Test func gstreamersErrorsAsTheContractsCodes() { + func code(_ domain: String, _ value: Int32, network: Bool = false) -> MediaError.Code { + MediaValues.error(domain: domain, code: value, message: "", network: network).code + } + let resource = "gst-resource-error-quark", stream = "gst-stream-error-quark" + #expect(code(resource, 3) == .notFound) + #expect(code(resource, 15, network: true) == .notFound, "a server's 401 or 403") + #expect(code(resource, 5, network: true) == .network, "a URL that can't be read is the connection") + #expect(code(resource, 5) == .notFound, "a file that can't be read is the file") + #expect(code(resource, 6) == .unavailable, "the sound server wouldn't open") + #expect(code(stream, 4) == .unsupportedFormat, "type not found") + #expect(code(stream, 6) == .unsupportedFormat, "no decoder") + #expect(code("gst-core-error-quark", 12) == .unsupportedFormat, "a missing plugin") + #expect(code(stream, 7) == .decoding) + #expect(code(stream, 9) == .decoding, "demuxing") + #expect(code("gst-library-error-quark", 1) == .unknown) + #expect(MediaValues.error(domain: resource, code: 3, message: "Not found", network: false).message == "Not found") + } + + @Test func mimeTypesAsWhatGStreamerReads() { + #expect(MediaValues.format("video/mp4; codecs=\"avc1.42E01E\"") == MediaValues.Format( + container: "video/quicktime", codecs: [MediaValues.h264, MediaValues.aac])) + #expect(MediaValues.format("Audio/WAV")?.container == "audio/x-wav") + #expect(MediaValues.format("application/vnd.apple.mpegurl")?.container == "application/x-hls") + #expect(MediaValues.format("audio/x-unheard")?.container == "audio/x-unheard", "GStreamer's own name") + #expect(MediaValues.format("") == nil) + #expect(MediaValues.fileExtension("audio/mpeg") == "mp3") + #expect(MediaValues.fileExtension("application/x-unknown") == "media") + } + + @Test func supportIsTheContainerAndTheContractsCodecs() { + let all: (String) -> Bool = { _ in true } + let none: (String) -> Bool = { _ in false } + #expect(MediaValues.support("video/mp4", reads: all, decodes: all) == .probably) + #expect(MediaValues.support("video/mp4", reads: all, decodes: { $0 == MediaValues.aac }) == .maybe, "no H.264") + #expect(MediaValues.support("video/mp4", reads: none, decodes: all) == .no) + #expect(MediaValues.support("audio/wav", reads: all, decodes: none) == .probably, "PCM needs no decoder") + #expect(MediaValues.support("", reads: all, decodes: all) == .no) + } +} diff --git a/Tests/LinuxPackagerTests/PackagerTests.swift b/Tests/LinuxPackagerTests/PackagerTests.swift index 62d568d..805b95d 100644 --- a/Tests/LinuxPackagerTests/PackagerTests.swift +++ b/Tests/LinuxPackagerTests/PackagerTests.swift @@ -110,6 +110,15 @@ import Testing #expect(try diagnostics(fixture).map(\.message) == []) } + @Test func mediaIsImplemented() throws { + let fixture = try Fixture(contracts: [ + ("org.pureswift.ui.Renderer", 1, "contract"), + ("org.pureswift.media.Playback", 1, "contract"), + ("org.pureswift.media.PlaybackDelegate", 1, "callback"), + ], capabilities: ["audio", "network"]) + #expect(try diagnostics(fixture).map(\.message) == []) + } + /// AppRuntime's `RuntimeNetworking`, over `FoundationNetworking`. @Test func networkingIsImplemented() throws { let fixture = try Fixture(contracts: [ @@ -180,7 +189,7 @@ import Testing } @Test func capabilitiesWithoutSupportWarn() throws { - let messages = try diagnostics(Fixture(capabilities: ["bluetooth", "location", "motion", "nfc", "notifications"])) + let messages = try diagnostics(Fixture(capabilities: ["audio", "bluetooth", "location", "motion", "nfc", "notifications"])) #expect(messages == [.warning("the app declares notifications, which the Linux host doesn't support yet")]) } diff --git a/Tests/LinuxUITests/RenderingTests.swift b/Tests/LinuxUITests/RenderingTests.swift index aacf90e..da4204b 100644 --- a/Tests/LinuxUITests/RenderingTests.swift +++ b/Tests/LinuxUITests/RenderingTests.swift @@ -153,6 +153,9 @@ struct RenderingTests { node("ContextMenu", [:], [label("Pressed"), node("Button", [:], [label("Copy")]), node("Divider")]), node("Refreshable", ["refreshing": false], [node("List", [:], [label("Pull")])]), node("NavLevel", ["title": "Loose level"], [label("level")]), + // No such players: black, with and without the controls. + node("VideoPlayer", ["player": 999, "scaling": "fill"]), + node("VideoPlayer", ["player": 998, "scaling": "stretch", "controls": "none"]), node("SomeFutureView", ["value": 1], [label("never shown")]), ] let toolbar = [