app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+70
View File
@@ -0,0 +1,70 @@
[package]
name = "rune-media"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Video and audio playback, zero-copy native surfaces (IOSurface, D3D shared textures, Linux dmabufs), and audio recording for Rune."
[features]
default = ["metal-backend", "ogg-audio", "rune-gpu/default"]
# macOS and iOS: interoperate with Rune's native Metal backend (zero-copy CVPixelBuffer import).
metal-backend = ["rune-gpu/metal-backend"]
# macOS: play Ogg (Vorbis, Opus) and WebM/Matroska audio, which AVFoundation can't read, by
# decoding it in Rust (symphonia, opuscule) and handing AVPlayer the PCM. Off, those clips
# fail at once with a clear message.
ogg-audio = ["dep:symphonia", "dep:opuscule"]
[dependencies]
bytemuck = { workspace = true }
rune-core = { workspace = true }
rune-gpu = { workspace = true }
rune-image = { workspace = true }
rune-staging = { workspace = true }
wgpu = { workspace = true, features = ["std", "parking_lot", "wgsl"] }
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
pollster = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wgpu = { workspace = true, features = ["webgpu"] }
[target.'cfg(target_vendor = "apple")'.dependencies]
# wgpu's Metal backend on Apple targets alone: off Apple, wgpu compiles neither `wgpu-hal/metal`
# nor `naga/msl-out`.
wgpu = { workspace = true, features = ["metal"] }
[target.'cfg(target_os = "macos")'.dependencies]
block2 = { workspace = true }
objc2 = { workspace = true }
# Video playback (`Player`) and recording (`Recorder`): AVFoundation, CoreVideo, CoreMedia and CoreGraphics.
objc2-av-foundation = { version = "0.3", default-features = false, features = ["std", "AVAsset", "AVAssetImageGenerator", "AVAssetTrack", "AVMediaFormat", "AVPlayer", "AVPlayerItem", "AVPlayerItemOutput", "objc2-core-foundation", "objc2-core-graphics", "objc2-core-media", "objc2-core-video"] }
objc2-core-foundation = { workspace = true, features = ["std", "CFCGTypes", "CFDictionary", "CFNumber", "CFString", "objc2"] }
objc2-core-graphics = { workspace = true, features = ["std", "CGBitmapContext", "CGColorSpace", "CGContext", "CGImage"] }
objc2-core-media = { version = "0.3", default-features = false, features = ["std", "CMTime"] }
objc2-core-video = { workspace = true, features = ["std", "CVBase", "CVBuffer", "CVHostTime", "CVImageBuffer", "CVMetalTexture", "CVMetalTextureCache", "CVPixelBuffer", "CVPixelBufferIOSurface", "CVReturn", "objc2", "objc2-io-surface", "objc2-metal"] }
objc2-foundation = { workspace = true, features = ["std", "NSArray", "NSData", "NSDictionary", "NSError", "NSObject", "NSString", "NSURL", "NSURLConnection", "NSURLRequest", "NSURLResponse", "NSValue"] }
# Unused by name: `objc2-core-foundation` gives IOSurfaceRef the CF `Type` impl objc2-core-video needs.
objc2-io-surface = { version = "0.3", default-features = false, features = ["std", "IOSurfaceRef", "objc2-core-foundation"] }
objc2-metal = { workspace = true, features = ["std", "MTLAllocation", "MTLDevice", "MTLPixelFormat", "MTLResource", "MTLTexture"] }
# Ogg and WebM audio (`ogg-audio`): pure-Rust demuxers and decoders.
symphonia = { version = "0.5.5", optional = true, default-features = false, features = ["ogg", "vorbis", "mkv"] }
opuscule = { version = "0.2.2", optional = true }
[target.'cfg(target_os = "windows")'.dependencies]
wgpu = { workspace = true, features = ["dx12"] }
# D3D12 shared textures (`native_surface::windows`), Media Foundation, D3D11 and WASAPI (`video::windows`):
# COM interfaces only; their DLLs load on the first clip through `GetProcAddress`, so the import table gains nothing.
windows = { workspace = true, features = ["Win32_Foundation", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D11", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", "Win32_Media_Audio", "Win32_Media_MediaFoundation", "Win32_Security", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_LibraryLoader", "Win32_System_Threading", "Win32_System_Variant", "Win32_UI_Shell_PropertiesSystem"] }
windows-sys = { workspace = true, features = ["Win32_Graphics_Dwm", "Win32_System_Performance"] }
[target.'cfg(target_os = "linux")'.dependencies]
# The window GPU's render node, for dmabuf producers (`native_surface::linux`): wgpu-hal's version.
ash = "0.38"
libc = { workspace = true }
# wgpu's Vulkan backend everywhere but Windows (D3D12 above) and Apple (Metal above).
[target.'cfg(all(not(target_vendor = "apple"), not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies]
wgpu = { workspace = true, features = ["vulkan"] }
[lints]
workspace = true
+21
View File
@@ -0,0 +1,21 @@
//! Media playback, zero-copy native video surfaces and audio recording for Rune. Apps normally
//! reach these types through `rune`, which re-exports them.
pub mod native_surface;
pub mod recorder;
pub mod video;
pub use native_surface::NativeSurface;
pub use native_surface::SurfaceFit;
pub use recorder::FakeMicrophone;
pub use recorder::Level;
pub use recorder::MicPermission;
pub use recorder::RecordFormat;
pub use recorder::Recorder;
pub use recorder::RecorderState;
pub use recorder::Recording;
pub use video::MediaRequest;
pub use video::MediaSource;
pub use video::Player;
pub use video::PlayerState;
pub use video::Video;
@@ -0,0 +1,314 @@
//! Dmabufs from another process, read on Rune's Vulkan device.
//!
//! The producer renders BGRA8 frames (`DRM_FORMAT_ARGB8888`) into single-plane, linear
//! (`DRM_FORMAT_MOD_LINEAR`) dmabufs on the GPU at [`import_target`]'s render node, and finishes
//! writing a frame before it pushes it. Rune imports each buffer once and copies a pushed frame
//! into a texture of its own the first time it draws it, then draws that copy as often as it
//! needs, in every window on the same device. Once the GPU has finished the copy, a thread of the
//! importer calls the frame's [`on_read`](Dmabuf::on_read) with `Ok` (no later frame or redraw is
//! needed for that), and the producer may write the buffer again. When the frame can't be shown
//! the callback gets the error instead. A frame replaced before it was drawn is never read and its
//! callback is dropped without running: the next frame's covers it.
use super::*;
use std::os::fd::{AsRawFd, OwnedFd};
use std::sync::Weak;
use std::sync::mpsc::Sender;
use std::time::Duration;
use wgpu::hal::api::Vulkan;
/// `DRM_FORMAT_ARGB8888`: B, G, R, A bytes in memory, the one format Rune imports.
pub const DRM_FORMAT_ARGB8888: u32 = u32::from_le_bytes(*b"AR24");
/// `DRM_FORMAT_MOD_LINEAR`, the one layout Rune imports.
pub const DRM_FORMAT_MOD_LINEAR: u64 = 0;
/// How many imported buffers an importer keeps, and how many of their bytes: a producer cycles a
/// few buffers per stream.
const OPENED: usize = 16;
const OPENED_BYTES: u64 = 512 << 20;
/// How long the importer waits for its copy to finish before it gives the frame up.
const READ_TIMEOUT: Duration = Duration::from_secs(10);
/// Where a dmabuf's one plane lies in its file, in bytes.
#[derive(Debug)]
pub struct DmabufPlane {
pub fd: OwnedFd,
pub offset: u32,
pub stride: u32,
pub modifier: u64,
}
/// One dmabuf a producer writes frames into, imported once and drawn from as often as it's pushed.
#[derive(Debug)]
pub struct DmabufBuffer {
plane: DmabufPlane,
size: [u32; 2],
}
impl DmabufBuffer {
/// A `size` (width, height) buffer of DRM format `fourcc` in `plane`. Only
/// [`DRM_FORMAT_ARGB8888`] with [`DRM_FORMAT_MOD_LINEAR`] imports; rows must hold the width and
/// the file the whole plane.
#[allow(unsafe_code)]
pub fn new(plane: DmabufPlane, size: [u32; 2], fourcc: u32) -> Result<Self, String> {
let [width, height] = size;
if fourcc != DRM_FORMAT_ARGB8888 {
return Err(format!("dmabuf format {fourcc:#x} isn't ARGB8888"));
}
if plane.modifier != DRM_FORMAT_MOD_LINEAR {
return Err(format!("dmabuf modifier {:#x} isn't linear", plane.modifier));
}
if width == 0 || height == 0 || width > 16384 || height > 16384 {
return Err("dmabuf size must be 1..16384".into());
}
if u64::from(plane.stride) < u64::from(width) * 4 {
return Err(format!("dmabuf rows of {} bytes can't hold {width} pixels", plane.stride));
}
// SAFETY: lseek on a descriptor this owns; a dmabuf's end is its size.
let len = unsafe { libc::lseek(plane.fd.as_raw_fd(), 0, libc::SEEK_END) };
// SAFETY: as above, back to the start.
unsafe { libc::lseek(plane.fd.as_raw_fd(), 0, libc::SEEK_SET) };
let needed = u64::from(plane.offset) + u64::from(plane.stride) * u64::from(height);
if len < 0 || (len as u64) < needed {
return Err(format!("dmabuf of {len} bytes can't hold {needed}"));
}
Ok(Self { plane, size })
}
fn bytes(&self) -> u64 {
u64::from(self.plane.stride) * u64::from(self.size[1])
}
}
type OnRead = Box<dyn FnOnce(Result<(), String>) + Send>;
/// Whether the producer has heard about its frame.
enum Release {
/// It didn't ask to.
Unasked,
Waiting(OnRead),
/// It has, and may be writing the buffer again.
Told,
}
/// A finished frame in a [`DmabufBuffer`].
///
/// ```no_run
/// use std::sync::Arc;
/// use rune_media::native_surface::linux::{DRM_FORMAT_ARGB8888, DRM_FORMAT_MOD_LINEAR, Dmabuf, DmabufBuffer, DmabufPlane};
/// # let fd: std::os::fd::OwnedFd = unimplemented!();
/// let plane = DmabufPlane { fd, offset: 0, stride: 5120, modifier: DRM_FORMAT_MOD_LINEAR };
/// let buffer = Arc::new(DmabufBuffer::new(plane, [1280, 720], DRM_FORMAT_ARGB8888).unwrap());
/// let frame = Dmabuf::new(buffer).on_read(|read| eprintln!("frame 42 read: {read:?}"));
/// rune_media::NativeSurface::new().push_dmabuf(frame, 42).unwrap();
/// ```
pub struct Dmabuf {
buffer: Arc<DmabufBuffer>,
release: Mutex<Release>,
/// Rune's copy on each device that has drawn the frame.
copies: Mutex<Vec<(wgpu::Device, wgpu::Texture)>>,
}
impl Dmabuf {
pub fn new(buffer: Arc<DmabufBuffer>) -> Self {
Self { buffer, release: Mutex::new(Release::Unasked), copies: Mutex::new(Vec::new()) }
}
/// Runs `f` once Rune's GPU has finished reading the frame (`Ok`), or with why it couldn't
/// (`Err`). It runs on a thread of Rune's.
pub fn on_read(self, f: impl FnOnce(Result<(), String>) + Send + 'static) -> Self {
*self.release.lock().unwrap() = Release::Waiting(Box::new(f));
self
}
pub(crate) fn size(&self) -> [u32; 2] {
self.buffer.size
}
/// Moves to `Told`, handing back the callback if one waited.
fn tell(&self) -> Option<OnRead> {
match std::mem::replace(&mut *self.release.lock().unwrap(), Release::Told) {
Release::Waiting(f) => Some(f),
Release::Unasked | Release::Told => None,
}
}
fn told(&self) -> bool {
matches!(*self.release.lock().unwrap(), Release::Told)
}
}
impl std::fmt::Debug for Dmabuf {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Dmabuf").field(&self.buffer).finish()
}
}
/// Where a producer renders frames Rune can import.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ImportTarget {
/// The render node of the GPU Rune draws windows on (`/dev/dri/renderD128`), when its driver
/// says (`VK_EXT_physical_device_drm`).
pub render_node: Option<String>,
}
static TARGET: Mutex<Option<ImportTarget>> = Mutex::new(None);
/// The GPU the last window Rune made draws on, once one has been made with a Vulkan device that
/// imports dmabufs (`VK_EXT_external_memory_dma_buf` and `VK_EXT_image_drm_format_modifier`);
/// None before, or when it can't.
pub fn import_target() -> Option<ImportTarget> {
TARGET.lock().unwrap().clone()
}
/// Remembers `device`'s GPU for [`import_target`].
pub(crate) fn note_device(device: &wgpu::Device) {
let target = device.features().contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF).then(|| ImportTarget { render_node: render_node(device) });
*TARGET.lock().unwrap() = target;
}
#[allow(unsafe_code)]
fn render_node(device: &wgpu::Device) -> Option<String> {
use ash::vk;
// SAFETY: the raw handles are only queried.
let hal = unsafe { device.as_hal::<Vulkan>() }?;
let instance = hal.shared_instance().raw_instance();
let physical = hal.raw_physical_device();
// SAFETY: plain queries on live handles; the DRM properties are only chained in when the
// device has the extension.
unsafe {
let extensions = instance.enumerate_device_extension_properties(physical).ok()?;
if !extensions.iter().any(|e| e.extension_name_as_c_str() == Ok(ash::ext::physical_device_drm::NAME)) {
return None;
}
let mut drm = vk::PhysicalDeviceDrmPropertiesEXT::default();
let mut props = vk::PhysicalDeviceProperties2::default().push_next(&mut drm);
instance.get_physical_device_properties2(physical, &mut props);
(drm.has_render == vk::TRUE).then(|| format!("/dev/dri/renderD{}", drm.render_minor))
}
}
/// `frame`'s picture on `device`, through the importer in `slot`. Tells the producer about every
/// failure.
pub(crate) fn import(slot: &mut Option<Importer>, device: &wgpu::Device, queue: &wgpu::Queue, frame: &Dmabuf) -> Result<[wgpu::Texture; 2], String> {
let result = if frame.size().iter().any(|v| *v > device.limits().max_texture_dimension_2d) {
Err("video dimensions exceed this GPU device's texture limit".into())
} else {
match slot {
Some(importer) => Ok(importer),
empty => Importer::new(device).map(|importer| empty.insert(importer)),
}
.and_then(|importer| importer.import(queue, frame))
};
if let Err(e) = &result
&& let Some(f) = frame.tell()
{
f(Err(e.clone()));
}
result
}
pub(crate) struct Importer {
device: wgpu::Device,
opened: Vec<(Weak<DmabufBuffer>, wgpu::Texture)>,
/// The thread that waits for each copy and tells its producer.
reads: Sender<(wgpu::SubmissionIndex, OnRead)>,
}
impl Importer {
fn new(device: &wgpu::Device) -> Result<Self, String> {
if !device.features().contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF) {
return Err("this GPU device doesn't import dmabufs".into());
}
let (reads, waits) = std::sync::mpsc::channel::<(wgpu::SubmissionIndex, OnRead)>();
let waiter = device.clone();
std::thread::Builder::new()
.name("rune-dmabuf-read".into())
.spawn(move || {
for (submission, f) in waits {
let done = rune_gpu::health::poll(&waiter, wgpu::PollType::Wait { submission_index: Some(submission), timeout: Some(READ_TIMEOUT) });
f(done.map(|_| ()).map_err(|e| format!("wait for the dmabuf copy: {e}")));
}
})
.map_err(|e| format!("start the dmabuf read thread: {e}"))?;
Ok(Self { device: device.clone(), opened: Vec::new(), reads })
}
/// Rune's copy of `frame` on this device, made the first time; the producer hears once the
/// GPU has finished it.
fn import(&mut self, queue: &wgpu::Queue, frame: &Dmabuf) -> Result<[wgpu::Texture; 2], String> {
if let Some((_, copy)) = frame.copies.lock().unwrap().iter().find(|(d, _)| *d == self.device) {
return Ok([copy.clone(), copy.clone()]);
}
if frame.told() {
return Err("the producer may be writing this dmabuf again; another GPU device read it first".into());
}
let (copy, submission) = self.copy(queue, &frame.buffer)?;
frame.copies.lock().unwrap().push((self.device.clone(), copy.clone()));
if let Some(f) = frame.tell() {
self.reads.send((submission, f)).ok();
}
Ok([copy.clone(), copy])
}
/// Lets go of buffers whose producer and frames are all gone.
pub(crate) fn forget_gone(&mut self) {
self.opened.retain(|(live, _)| live.strong_count() > 0);
}
fn copy(&mut self, queue: &wgpu::Queue, buffer: &Arc<DmabufBuffer>) -> Result<(wgpu::Texture, wgpu::SubmissionIndex), String> {
let source = self.source(buffer)?;
let [width, height] = buffer.size;
let mut desc = pipeline::descriptor(width, height, wgpu::TextureFormat::Bgra8Unorm);
desc.usage |= wgpu::TextureUsages::COPY_DST;
let owned = self.device.create_texture(&desc);
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("dmabuf copy") });
encoder.copy_texture_to_texture(source.as_image_copy(), owned.as_image_copy(), desc.size);
Ok((owned, queue.submit([encoder.finish()])))
}
/// `buffer` as a texture on this device, imported the first time it's drawn.
#[allow(unsafe_code)]
fn source(&mut self, buffer: &Arc<DmabufBuffer>) -> Result<wgpu::Texture, String> {
self.forget_gone();
if let Some((_, texture)) = self.opened.iter().find(|(live, _)| std::ptr::eq(live.as_ptr(), Arc::as_ptr(buffer))) {
return Ok(texture.clone());
}
let [width, height] = buffer.size;
let mut desc = pipeline::descriptor(width, height, wgpu::TextureFormat::Bgra8Unorm);
desc.usage = wgpu::TextureUsages::COPY_SRC;
let hal_desc = wgpu::hal::TextureDescriptor {
label: Some("dmabuf"),
size: desc.size,
mip_level_count: 1,
sample_count: 1,
dimension: desc.dimension,
format: desc.format,
usage: wgpu::TextureUses::COPY_SRC,
memory_flags: wgpu::hal::MemoryFlags::empty(),
view_formats: Vec::new(),
};
let plane = &buffer.plane;
let fd = plane.fd.try_clone().map_err(|e| format!("dup dmabuf: {e}"))?;
// SAFETY: only the raw device is borrowed, for the import.
let hal = unsafe { self.device.as_hal::<Vulkan>() }.ok_or("dmabufs need wgpu's Vulkan backend")?;
// SAFETY: `fd` is a linear single-plane ARGB8888 dmabuf of `width` × `height` whose rows,
// offset and length `DmabufBuffer::new` checked; the device has
// `VULKAN_EXTERNAL_MEMORY_DMA_BUF` (`Importer::new`).
let raw = unsafe { hal.texture_from_dmabuf_fd(fd, &hal_desc, plane.modifier, u64::from(plane.stride), u64::from(plane.offset)) }
.map_err(|e| format!("import dmabuf: {e}"))?;
drop(hal);
// The image is new, so its layout starts undefined. A linear buffer has no compression
// metadata, so the first transition keeps the producer's pixels, and as the producer only
// writes between reads the texture stays in the copy-source state wgpu leaves it in.
// SAFETY: `raw` was made on this device from `hal_desc`, which matches `desc`.
let texture = unsafe { self.device.create_texture_from_hal::<Vulkan>(raw, &desc, wgpu::TextureUses::UNINITIALIZED) };
self.opened.push((Arc::downgrade(buffer), texture.clone()));
let bytes = |opened: &[(Weak<DmabufBuffer>, wgpu::Texture)]| opened.iter().filter_map(|(b, _)| b.upgrade()).map(|b| b.bytes()).sum::<u64>();
while self.opened.len() > OPENED || (self.opened.len() > 1 && bytes(&self.opened) > OPENED_BYTES) {
self.opened.remove(0);
}
Ok(texture)
}
}
@@ -0,0 +1,330 @@
//! CoreVideo ownership boundary. Decoder output must be complete and immutable before handoff.
#![allow(unsafe_code)]
use super::*;
use objc2_core_foundation::{CFBoolean, CFDictionary, CFRetained, CFString, CFType};
use objc2_core_video::*;
use objc2_metal::{MTLPixelFormat, MTLTextureType};
use std::ptr::{NonNull, null_mut};
/// A retained, immutable CVPixelBuffer, normally supplied by VideoToolbox's output callback.
#[derive(Clone)]
pub struct PixelBuffer(CFRetained<CVPixelBuffer>);
// SAFETY: CoreVideo retain/release and read-only buffer access are thread-safe. Construction requires
// the caller to prohibit mutations, including through aliases, until the last owner is released.
unsafe impl Send for PixelBuffer {}
// SAFETY: CoreVideo retain/release and read-only pixel/attachment access are thread-safe while immutable.
unsafe impl Sync for PixelBuffer {}
impl PixelBuffer {
/// Retain a borrowed CVPixelBufferRef (does not consume the caller's retain).
///
/// # Safety
/// `raw` must be a live CVPixelBufferRef. Decoding/writes must be finished, and its pixels
/// and attachments must not be modified until every clone and GPU use has been released.
pub unsafe fn from_raw(raw: *mut std::ffi::c_void) -> Result<Self, String> {
let ptr = NonNull::new(raw.cast::<CVPixelBuffer>()).ok_or("null CVPixelBuffer")?;
// SAFETY: caller guarantees `raw` is a live, immutable `CVPixelBufferRef`; `retain` takes an owned reference.
Ok(Self(unsafe { CFRetained::retain(ptr) }))
}
/// Wrap an IOSurface without copying. The new CVPixelBuffer retains the surface.
///
/// # Safety
/// `raw` must be a live IOSurfaceRef containing complete BGRA/420v/420f pixels. It must
/// remain immutable through all GPU uses, including through aliases in other processes.
pub unsafe fn from_iosurface(raw: *mut std::ffi::c_void, color: ColorInfo) -> Result<Self, String> {
if raw.is_null() {
return Err("null IOSurface".into());
}
let mut out = null_mut();
check(
// SAFETY: caller guarantees `raw` is a non-null live `IOSurfaceRef`, and `out` is a valid out-pointer.
unsafe { CVPixelBufferCreateWithIOSurface(None, &*raw.cast(), None, NonNull::from(&mut out)) },
"CVPixelBufferCreateWithIOSurface",
)?;
// SAFETY: `CVPixelBufferCreateWithIOSurface` succeeded and transferred ownership of a retained `CVPixelBuffer` in `out`.
let buffer = Self(unsafe { CFRetained::from_raw(NonNull::new(out).ok_or("null pixel buffer")?) });
buffer.set_color(color);
buffer.info()?;
Ok(buffer)
}
fn set_color(&self, color: ColorInfo) {
// SAFETY: `self.0` is a live owned `CVPixelBuffer` and the CoreVideo attachment keys and values are static `CFString` constants.
unsafe {
self.0.set_attachment(
kCVImageBufferYCbCrMatrixKey,
match color.matrix {
Matrix::Bt601 => kCVImageBufferYCbCrMatrix_ITU_R_601_4,
Matrix::Bt709 => kCVImageBufferYCbCrMatrix_ITU_R_709_2,
}
.as_ref(),
CVAttachmentMode::ShouldPropagate,
);
self.0.set_attachment(
kCVImageBufferTransferFunctionKey,
match color.transfer {
Transfer::Srgb => kCVImageBufferTransferFunction_sRGB,
Transfer::Bt709 => kCVImageBufferTransferFunction_ITU_R_709_2,
}
.as_ref(),
CVAttachmentMode::ShouldPropagate,
);
}
}
#[allow(non_upper_case_globals)] // CoreVideo's public fourcc names.
pub(crate) fn info(&self) -> Result<([u32; 2], Format, ColorInfo), String> {
let b = &self.0;
let format = match CVPixelBufferGetPixelFormatType(b) {
kCVPixelFormatType_32BGRA => Format::Bgra,
kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange => Format::Nv12Video,
kCVPixelFormatType_420YpCbCr8BiPlanarFullRange => Format::Nv12Full,
other => return Err(format!("unsupported CVPixelBuffer format {other:#x}; use BGRA, 420v or 420f")),
};
let size = [CVPixelBufferGetWidth(b) as u32, CVPixelBufferGetHeight(b) as u32];
if size.contains(&0) || size.iter().any(|v| *v > 16384) {
return Err("invalid video dimensions".into());
}
if format != Format::Bgra
&& (!size[0].is_multiple_of(2) || !size[1].is_multiple_of(2) || CVPixelBufferGetPlaneCount(b) != 2)
{
return Err("NV12 requires two planes and even dimensions".into());
}
// An absent matrix follows the common SD/HD convention; explicit unsupported colour
// metadata is rejected instead of silently treating HDR/2020 as SDR/709.
// SAFETY: `b` is a live `CVPixelBuffer` and `kCVImageBufferYCbCrMatrixKey` is a static `CFString` constant.
let matrix = unsafe { b.attachment(kCVImageBufferYCbCrMatrixKey, null_mut()) };
let matrix = match matrix {
None => {
if size[1] <= 576 {
Matrix::Bt601
} else {
Matrix::Bt709
}
}
// SAFETY: `kCVImageBufferYCbCrMatrix_ITU_R_601_4` is an immutable static `CFString` constant.
Some(v) if unsafe { cf_equal(&v, kCVImageBufferYCbCrMatrix_ITU_R_601_4) } => Matrix::Bt601,
// SAFETY: `kCVImageBufferYCbCrMatrix_ITU_R_709_2` is an immutable static `CFString` constant.
Some(v) if unsafe { cf_equal(&v, kCVImageBufferYCbCrMatrix_ITU_R_709_2) } => Matrix::Bt709,
_ => return Err("unsupported YCbCr matrix; use BT.601 or BT.709".into()),
};
// SAFETY: `b` is a live `CVPixelBuffer` and `kCVImageBufferTransferFunctionKey` is a static `CFString` constant.
let transfer = unsafe { b.attachment(kCVImageBufferTransferFunctionKey, null_mut()) };
let transfer = match transfer {
None => {
if format == Format::Bgra {
Transfer::Srgb
} else {
Transfer::Bt709
}
}
// SAFETY: `kCVImageBufferTransferFunction_sRGB` is an immutable static `CFString` constant.
Some(v) if unsafe { cf_equal(&v, kCVImageBufferTransferFunction_sRGB) } => Transfer::Srgb,
// SAFETY: `kCVImageBufferTransferFunction_ITU_R_709_2` is an immutable static `CFString` constant.
Some(v) if unsafe { cf_equal(&v, kCVImageBufferTransferFunction_ITU_R_709_2) } => Transfer::Bt709,
_ => return Err("unsupported transfer function; use sRGB or BT.709 (HDR is not supported)".into()),
};
Ok((size, format, ColorInfo { matrix, transfer }))
}
/// Test source only: create a Metal-compatible IOSurface and fill it before publishing.
/// The production decoder path never locks, reads or copies pixel memory.
pub fn from_bytes(frame: &ByteFrame) -> Result<Self, String> {
// Reuse portable validation before touching an unsafe plane pointer.
let w = frame.width as usize;
let h = frame.height as usize;
if w == 0 || h == 0 || w > 16384 || h > 16384 {
return Err("invalid dimensions".into());
}
let nv12 = frame.format != Format::Bgra;
if nv12 && (!w.is_multiple_of(2) || !h.is_multiple_of(2)) {
return Err("odd NV12 dimensions".into());
}
if frame.planes[0].len() != w * h * if nv12 { 1 } else { 4 }
|| frame.planes[1].len() != if nv12 { w * h / 2 } else { 0 }
{
return Err("invalid plane length".into());
}
let empty = CFDictionary::<CFString, CFType>::from_slices(&[], &[]);
// SAFETY: `kCVPixelBufferIOSurfacePropertiesKey` and `kCVPixelBufferMetalCompatibilityKey` are immutable static `CFString` constants.
let attrs = unsafe {
CFDictionary::<CFString, CFType>::from_slices(
&[kCVPixelBufferIOSurfacePropertiesKey, kCVPixelBufferMetalCompatibilityKey],
&[AsRef::<CFType>::as_ref(&*empty), CFBoolean::new(true).as_ref()],
)
};
let format = match frame.format {
Format::Bgra => kCVPixelFormatType_32BGRA,
Format::Nv12Video => kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
Format::Nv12Full => kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
};
let mut raw = null_mut();
// SAFETY: `w`, `h`, and `attrs` are valid, and `raw` is a valid aligned out-pointer.
let status = unsafe { CVPixelBufferCreate(None, w, h, format, Some(attrs.as_opaque()), NonNull::from(&mut raw)) };
check(status, "CVPixelBufferCreate")?;
// SAFETY: `CVPixelBufferCreate` returned 0 and transferred ownership of a retained `CVPixelBuffer` in `raw`.
let buffer = Self(unsafe { CFRetained::from_raw(NonNull::new(raw).ok_or("null created pixel buffer")?) });
// SAFETY: `buffer` is uniquely owned and locked for CPU writes; `frame.planes` lengths match `w`/`h` (checked above)
// and each row fits within the plane's stride.
unsafe {
check(CVPixelBufferLockBaseAddress(&buffer.0, CVPixelBufferLockFlags(0)), "lock synthetic buffer")?;
for plane in 0..if nv12 { 2 } else { 1 } {
let (ptr, stride) = if nv12 {
(
CVPixelBufferGetBaseAddressOfPlane(&buffer.0, plane),
CVPixelBufferGetBytesPerRowOfPlane(&buffer.0, plane),
)
} else {
(CVPixelBufferGetBaseAddress(&buffer.0), CVPixelBufferGetBytesPerRow(&buffer.0))
};
let row_bytes = w * if nv12 { 1 } else { 4 };
let rows = if plane == 1 { h / 2 } else { h };
for row in 0..rows {
std::ptr::copy_nonoverlapping(
frame.planes[plane].as_ptr().add(row * row_bytes),
ptr.cast::<u8>().add(row * stride),
row_bytes,
);
}
}
CVPixelBufferUnlockBaseAddress(&buffer.0, CVPixelBufferLockFlags(0));
}
buffer.set_color(frame.color);
Ok(buffer)
}
}
pub(crate) struct Importer {
cache: CFRetained<CVMetalTextureCache>,
device: wgpu::Device,
/// Whether `device` is Rune's native Metal backend's rather than wgpu-hal's.
#[cfg_attr(not(feature = "metal-backend"), allow(dead_code))]
native: bool,
#[cfg(test)]
pub(super) live_planes: Arc<std::sync::atomic::AtomicUsize>,
}
// CVMetalTexture retains the IOSurface mapping. wgpu's drop guard, or on the native Metal
// backend the texture's owner, keeps it for as long as any bind group or submitted command uses
// that plane, rather than merely retaining MTLTexture.
struct PlaneOwner {
_texture: CFRetained<CVMetalTexture>,
_buffer: PixelBuffer,
#[cfg(test)]
live_planes: Arc<std::sync::atomic::AtomicUsize>,
}
// SAFETY: `CVMetalTexture` and `PixelBuffer` retain/release are thread-safe and the backing pixels are immutable.
unsafe impl Send for PlaneOwner {}
// SAFETY: `PlaneOwner` holds only immutable CoreVideo handles and an atomic counter.
unsafe impl Sync for PlaneOwner {}
impl Drop for PlaneOwner {
fn drop(&mut self) {
#[cfg(test)]
self.live_planes.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
}
}
impl Importer {
pub fn new(device: &wgpu::Device) -> Result<Self, String> {
let mut raw = null_mut();
let mut create = |metal: &objc2::runtime::ProtocolObject<dyn objc2_metal::MTLDevice>| {
// SAFETY: `metal` is a live `MTLDevice` and `raw` is a valid out-pointer.
check(unsafe { CVMetalTextureCache::create(None, None, metal, None, NonNull::from(&mut raw)) }, "CVMetalTextureCacheCreate")
};
// SAFETY: only borrows the underlying `MTLDevice` to create the `CVMetalTextureCache`; no HAL state is mutated.
let native = if let Some(metal) = unsafe { device.as_hal::<wgpu::hal::api::Metal>() } {
create(metal.raw_device())?;
false
} else {
#[cfg(feature = "metal-backend")]
let Some(metal) = rune_gpu::metal::raw_device(device) else {
return Err("NativeSurface needs a Metal device".into());
};
#[cfg(not(feature = "metal-backend"))]
return Err("NativeSurface needs wgpu's Metal backend".into());
#[cfg(feature = "metal-backend")]
{
create(metal)?;
true
}
};
// SAFETY: `CVMetalTextureCache::create` returned 0 and transferred ownership of a retained `CVMetalTextureCache` in `raw`.
let cache = unsafe { CFRetained::from_raw(NonNull::new(raw).ok_or("null texture cache")?) };
Ok(Self {
cache,
device: device.clone(),
native,
#[cfg(test)]
live_planes: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
})
}
pub fn flush(&self) {
self.cache.flush(0);
}
pub fn import(&self, buffer: &PixelBuffer, format: Format, size: [u32; 2]) -> Result<[wgpu::Texture; 2], String> {
let plane = |index: usize, width: u32, height: u32, metal_format, format| -> Result<wgpu::Texture, String> {
let mut raw = null_mut();
check(
// SAFETY: `self.cache` and `buffer.0` are live, `width`/`height`/`index` match `buffer.info()`, and `raw` is a valid out-pointer.
unsafe {
CVMetalTextureCache::create_texture_from_image(
None,
&self.cache,
&buffer.0,
None,
metal_format,
width as usize,
height as usize,
index,
NonNull::from(&mut raw),
)
},
"CVMetalTextureCacheCreateTextureFromImage (buffer must be IOSurface-backed)",
)?;
// SAFETY: `create_texture_from_image` returned 0 and transferred ownership of a retained `CVMetalTexture` in `raw`.
let cv = unsafe { CFRetained::from_raw(NonNull::new(raw).ok_or("null CVMetalTexture")?) };
let texture = CVMetalTextureGetTexture(&cv).ok_or("null MTLTexture")?;
let owner = PlaneOwner {
_texture: cv,
_buffer: buffer.clone(),
#[cfg(test)]
live_planes: self.live_planes.clone(),
};
#[cfg(test)]
self.live_planes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let desc = pipeline::descriptor(width, height, format);
#[cfg(feature = "metal-backend")]
if self.native {
return Ok(rune_gpu::metal::texture_from_raw(texture, &desc, std::sync::Arc::new(owner)));
}
// SAFETY: `texture` comes from this Metal device's `CVMetalTextureCache` with matching format/dimensions,
// and `owner` keeps the `CVMetalTexture` and `PixelBuffer` alive until dropped.
let hal = unsafe {
wgpu::hal::metal::Device::texture_from_raw(
texture,
format,
MTLTextureType::Type2D,
1,
1,
wgpu::hal::CopyExtent { width, height, depth: 1 },
Some(Box::new(move || drop(owner))),
)
};
// SAFETY: the raw texture comes from this device's CV cache and exactly matches `desc`.
Ok(unsafe {
self.device.create_texture_from_hal::<wgpu::hal::api::Metal>(hal, &desc, wgpu::TextureUses::RESOURCE)
})
};
if format == Format::Bgra {
let a = plane(0, size[0], size[1], MTLPixelFormat::BGRA8Unorm, wgpu::TextureFormat::Bgra8Unorm)?;
Ok([a.clone(), a])
} else {
Ok([
plane(0, size[0], size[1], MTLPixelFormat::R8Unorm, wgpu::TextureFormat::R8Unorm)?,
plane(1, size[0] / 2, size[1] / 2, MTLPixelFormat::RG8Unorm, wgpu::TextureFormat::Rg8Unorm)?,
])
}
}
}
fn check(status: i32, operation: &str) -> Result<(), String> {
if status == 0 { Ok(()) } else { Err(format!("{operation}: CoreVideo status {status}")) }
}
fn cf_equal(value: &CFType, string: &CFString) -> bool {
value == AsRef::<CFType>::as_ref(string)
}
@@ -0,0 +1,543 @@
//! Latest-wins video frames. macOS imports IOSurface-backed CoreVideo buffers without a copy;
//! Windows reads D3D shared textures from another process or API (`windows`), Linux dmabufs
//! (`linux`).
//! CPU byte frames provide a portable source and a reference for headless verification.
#[cfg(test)]
#[path = "tests.rs"]
mod gpu_tests;
#[cfg(target_os = "linux")]
pub mod linux;
#[cfg(test)]
mod place_tests;
#[cfg(target_os = "macos")]
pub mod macos;
mod pipeline;
#[cfg(target_os = "windows")]
pub mod windows;
pub use pipeline::SurfaceRenderer;
#[doc(hidden)]
pub use pipeline::Building;
#[doc(hidden)]
pub use rune_image::place;
pub use rune_image::place::SurfaceFit;
use rune_core::time::Instant;
use std::sync::{Arc, Mutex};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Matrix {
Bt601,
Bt709,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Transfer {
Srgb,
Bt709,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
Bgra,
Nv12Video,
Nv12Full,
}
#[derive(Clone, Copy, Debug)]
pub struct ColorInfo {
pub matrix: Matrix,
pub transfer: Transfer,
}
impl Default for ColorInfo {
fn default() -> Self {
Self { matrix: Matrix::Bt709, transfer: Transfer::Srgb }
}
}
/// Immutable packed planes. NV12 plane 0 is Y, plane 1 is interleaved CbCr.
pub struct ByteFrame {
pub width: u32,
pub height: u32,
pub format: Format,
pub color: ColorInfo,
pub planes: [Vec<u8>; 2],
}
pub(crate) enum Source {
Bytes(ByteFrame),
#[cfg(target_os = "macos")]
PixelBuffer(macos::PixelBuffer),
#[cfg(target_os = "windows")]
Shared(windows::SharedTexture),
/// A video decoder's NV12 picture and the fence value that marks it written.
#[cfg(target_os = "windows")]
Decoded(Arc<windows::DecodedPlanes>, u64),
#[cfg(target_os = "linux")]
Dmabuf(linux::Dmabuf),
}
#[doc(hidden)]
pub struct Frame {
pub id: u64,
pub(crate) source: Source,
/// Buffer size, before `orient`.
pub size: [u32; 2],
pub format: Format,
pub color: ColorInfo,
pub orient: Orient,
}
/// How a frame's buffer turns into its upright picture: a quarter-turn rotation and/or flip,
/// applied while sampling. The matrix maps centred upright coordinates to centred buffer
/// coordinates: `buffer = [m0 m1; m2 m3] * upright`.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Orient(pub [i8; 4]);
impl Default for Orient {
fn default() -> Self {
Self::UP
}
}
impl Orient {
pub const UP: Self = Self([1, 0, 0, 1]);
/// From an affine transform taking buffer to upright coordinates (`x' = a x + c y`,
/// `y' = b x + d y`), such as AVFoundation's `preferredTransform`. Anything but a quarter
/// turn or flip is drawn upright as is.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub fn from_transform(a: f64, b: f64, c: f64, d: f64) -> Self {
let m = [a, b, c, d].map(|v| v.round());
let unit = m.iter().all(|v| v.abs() <= 1.0) && m.iter().zip([a, b, c, d]).all(|(r, v)| (r - v).abs() < 1e-3);
let quarter = (m[0] != 0.0 && m[3] != 0.0 && m[1] == 0.0 && m[2] == 0.0) || (m[0] == 0.0 && m[3] == 0.0 && m[1] != 0.0 && m[2] != 0.0);
// Orthogonal, so the inverse is the transpose: [a b; c d].
if unit && quarter { Self(m.map(|v| v as i8)) } else { Self::UP }
}
/// Whether width and height trade places.
pub fn swaps(self) -> bool {
self.0[0] == 0
}
/// The upright size of a buffer of `size`.
pub fn upright(self, [w, h]: [u32; 2]) -> [u32; 2] {
if self.swaps() { [h, w] } else { [w, h] }
}
}
/// Submit is a CPU monotonic timestamp. Completion is callback-observed CPU time;
/// GPU start/end are render-pass timestamp-query seconds on the GPU clock, not `Instant`
/// or display time. Their difference is GPU duration; the epoch is backend-specific.
/// GPU times are absent when unsupported, overridden by caller timing, all timing slots are
/// in flight, or no drawn surface has an observer (`set_observer`). CPU submission/completion notifications are still delivered.
#[derive(Clone, Debug)]
pub struct FrameTiming {
pub frame_id: u64,
pub submitted_at: Instant,
pub completed_at: Option<Instant>,
pub gpu_start_seconds: Option<f64>,
pub gpu_end_seconds: Option<f64>,
}
pub type FrameObserver = Arc<dyn Fn(FrameTiming) + Send + Sync>;
#[derive(Default)]
struct State {
latest: Option<Arc<Frame>>,
waker: Option<rune_core::Waker>,
observer: Option<FrameObserver>,
timing: Option<FrameTiming>,
submitted: u64,
completed: u64,
error: Option<String>,
mirrored: bool,
/// The player feeding this surface, pulled once per frame that draws it.
video: Option<Arc<crate::video::Shared>>,
}
/// Clones share a single bounded slot; pushing never queues frames behind the decoder.
#[derive(Clone, Default)]
pub struct NativeSurface(Arc<Mutex<State>>, place::SurfacePlace);
impl std::fmt::Debug for NativeSurface {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("NativeSurface").field(&self.key()).finish()
}
}
impl NativeSurface {
pub fn new() -> Self {
Self::default()
}
/// A handle to the same frames that draws with `place`; the element sets it per draw.
#[doc(hidden)]
pub fn placed(&self, place: place::SurfacePlace) -> Self {
NativeSurface(self.0.clone(), place)
}
#[doc(hidden)]
pub fn place(&self) -> place::SurfacePlace {
self.1
}
pub(crate) fn with_video(video: Arc<crate::video::Shared>) -> Self {
let surface = Self::default();
surface.0.lock().unwrap().video = Some(video);
surface
}
#[doc(hidden)]
pub fn video(&self) -> Option<Arc<crate::video::Shared>> {
self.0.lock().unwrap().video.clone()
}
/// Pull this frame's picture from the surface's video, if it has one.
#[doc(hidden)]
pub fn pull_video(&self, clock: crate::video::Clock, wake: &Arc<rune_core::live::Wake>) -> Option<crate::video::Pulled> {
let video = self.video()?;
Some(video.pull(self, clock, wake))
}
pub fn set_waker(&self, waker: rune_core::Waker) {
// The replaced waker's captures drop after the lock: one may read this surface's counts
// and would deadlock here.
let old = self.0.lock().unwrap().waker.replace(waker);
drop(old);
}
pub fn set_observer(&self, observer: FrameObserver) {
let old = self.0.lock().unwrap().observer.replace(observer);
drop(old);
}
/// Whether an observer listens: only then does a draw read GPU times.
#[doc(hidden)]
pub fn observed(&self) -> bool {
self.0.lock().unwrap().observer.is_some()
}
pub fn timing(&self) -> Option<FrameTiming> {
self.0.lock().unwrap().timing.clone()
}
/// Counts draws submitted/completed (the same source frame may be drawn more than once).
pub fn counts(&self) -> (u64, u64) {
let s = self.0.lock().unwrap();
(s.submitted, s.completed)
}
pub fn last_error(&self) -> Option<String> {
self.0.lock().unwrap().error.clone()
}
pub fn clear(&self) {
let (old, wake) = {
let mut s = self.0.lock().unwrap();
(s.latest.take(), s.waker.clone())
};
drop(old);
if let Some(wake) = wake {
wake();
}
}
/// Flip the image horizontally at draw time, about its centre, for a front-camera preview.
/// Pixels are untouched, so stills taken from the same buffers stay unmirrored. Clones
/// share the flag. A change wakes the app and redraws the current frame; no push is needed.
///
/// ```
/// let preview = rune_media::NativeSurface::new();
/// preview.set_mirrored(true); // front camera
/// // el().native_surface(&preview, rune_media::SurfaceFit::Fill) fills and crops, mirrored.
/// assert!(preview.is_mirrored());
/// ```
pub fn set_mirrored(&self, mirrored: bool) {
let wake = {
let mut s = self.0.lock().unwrap();
if s.mirrored == mirrored {
return;
}
s.mirrored = mirrored;
s.waker.clone()
};
if let Some(wake) = wake {
wake();
}
}
pub fn is_mirrored(&self) -> bool {
self.0.lock().unwrap().mirrored
}
pub fn push_bytes(&self, frame: ByteFrame, frame_id: u64) -> Result<(), String> {
self.push_bytes_oriented(frame, frame_id, Orient::UP)
}
pub(crate) fn push_bytes_oriented(&self, frame: ByteFrame, frame_id: u64, orient: Orient) -> Result<(), String> {
let [w, h] = [frame.width, frame.height];
if w == 0 || h == 0 || w > 16384 || h > 16384 {
return Err("video size must be 1..16384".into());
}
let n = w as usize * h as usize;
let sizes = match frame.format {
Format::Bgra => [n * 4, 0],
_ => {
if !w.is_multiple_of(2) || !h.is_multiple_of(2) {
return Err("NV12 requires even dimensions".into());
}
[n, n / 2]
}
};
if frame.planes[0].len() != sizes[0] || frame.planes[1].len() != sizes[1] {
return Err("video plane length does not match dimensions".into());
}
self.replace(Frame {
id: frame_id,
size: [w, h],
format: frame.format,
color: frame.color,
orient,
source: Source::Bytes(frame),
});
Ok(())
}
#[cfg(target_os = "macos")]
pub fn push(&self, buffer: macos::PixelBuffer, frame_id: u64) -> Result<(), String> {
self.push_oriented(buffer, frame_id, Orient::UP)
}
#[cfg(target_os = "macos")]
pub(crate) fn push_oriented(&self, buffer: macos::PixelBuffer, frame_id: u64, orient: Orient) -> Result<(), String> {
let (size, format, color) = buffer.info()?;
self.replace(Frame { id: frame_id, source: Source::PixelBuffer(buffer), size, format, color, orient });
Ok(())
}
/// Shows the frame in a D3D shared texture (`windows::SharedTexture`), read on Rune's D3D12
/// device the first time it draws.
#[cfg(target_os = "windows")]
pub fn push_shared(&self, texture: windows::SharedTexture, frame_id: u64) -> Result<(), String> {
let size = texture.size();
if size.contains(&0) || size.iter().any(|v| *v > 16384) {
return Err("video size must be 1..16384".into());
}
self.replace(Frame {
id: frame_id,
size,
format: Format::Bgra,
color: ColorInfo::default(),
orient: Orient::UP,
source: Source::Shared(texture),
});
Ok(())
}
/// Shows the frame in a dmabuf (`linux::Dmabuf`), read on Rune's Vulkan device the first time
/// it draws.
#[cfg(target_os = "linux")]
pub fn push_dmabuf(&self, frame: linux::Dmabuf, frame_id: u64) -> Result<(), String> {
let size = frame.size();
if size.contains(&0) || size.iter().any(|v| *v > 16384) {
return Err("video size must be 1..16384".into());
}
self.replace(Frame {
id: frame_id,
size,
format: Format::Bgra,
color: ColorInfo::default(),
orient: Orient::UP,
source: Source::Dmabuf(frame),
});
Ok(())
}
/// Shows a decoded NV12 picture (`video::windows`), sampled in place once its fence reaches
/// `value`.
#[cfg(target_os = "windows")]
pub(crate) fn push_decoded(&self, planes: Arc<windows::DecodedPlanes>, value: u64, frame_id: u64, format: Format, color: ColorInfo, orient: Orient) {
let size = planes.size;
self.replace(Frame { id: frame_id, size, format, color, orient, source: Source::Decoded(planes, value) });
}
fn replace(&self, frame: Frame) {
let (old, wake) = {
let mut s = self.0.lock().unwrap();
(s.latest.replace(Arc::new(frame)), s.waker.clone())
};
drop(old); // CoreVideo release never runs under the mailbox lock.
if let Some(wake) = wake {
wake();
}
}
#[doc(hidden)]
pub fn latest(&self) -> Option<Arc<Frame>> {
self.0.lock().unwrap().latest.clone()
}
fn latest_mirrored(&self) -> Option<(Arc<Frame>, bool)> {
let s = self.0.lock().unwrap();
s.latest.clone().map(|f| (f, s.mirrored))
}
#[doc(hidden)]
pub fn key(&self) -> usize {
Arc::as_ptr(&self.0) as usize
}
#[cfg(not(target_arch = "wasm32"))]
fn report(&self, timing: FrameTiming) {
let observer = {
// Called from wgpu's work-done callbacks, where a panic could abort the process.
let mut s = self.0.lock().unwrap_or_else(|e| e.into_inner());
if timing.completed_at.is_some() {
s.completed += 1;
} else {
s.submitted += 1;
}
if s.timing.as_ref().is_none_or(|old| old.submitted_at <= timing.submitted_at) {
s.timing = Some(timing.clone());
}
s.observer.clone()
};
if let Some(f) = observer {
f(timing);
}
}
}
/// A device Rune made, `presented` when it draws a window: its GPU is the one shared-texture
/// producers render on (`windows::adapter_luid`, `linux::import_target`).
#[doc(hidden)]
pub fn note_device(device: &wgpu::Device, presented: bool) {
#[cfg(target_os = "windows")]
if presented {
windows::note_adapter(device);
}
#[cfg(target_os = "linux")]
if presented {
linux::note_device(device);
}
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
let _ = (device, presented);
}
/// Lets go of a removed D3D12 device that video decoding still holds (the last window's, and
/// the decoders' D3D11 device on it), so a new device can be made on its adapter: D3D12 gives
/// a process one device per adapter, and the removed one again while anything holds it. Rune
/// calls it before it makes a device. Nothing off Windows.
#[doc(hidden)]
pub fn release_removed_device() {
#[cfg(target_os = "windows")]
{
windows::release_removed_device();
crate::video::release_removed_device();
}
}
/// A node's video draw in painter order. Geometry is already in device pixels.
#[derive(Clone, Debug)]
pub struct SurfaceDraw {
pub surface: NativeSurface,
pub fit: SurfaceFit,
pub before_instance: u32,
pub rect: [f32; 4],
pub radii: [f32; 4],
pub clip: [f32; 4],
/// Packed as `render::Instance::fade`.
pub fade: [u32; 4],
pub opacity: f32,
}
/// Independent scalar colour oracle: encoded YCbCr -> linear RGB.
pub fn nv12_reference(y: u8, cb: u8, cr: u8, format: Format, color: ColorInfo) -> [f32; 3] {
let (y, u, v) = if format == Format::Nv12Video {
((y as f32 - 16.0) / 219.0, (cb as f32 - 128.0) / 224.0, (cr as f32 - 128.0) / 224.0)
} else {
(y as f32 / 255.0, (cb as f32 - 128.0) / 255.0, (cr as f32 - 128.0) / 255.0)
};
let (kr, kb) = match color.matrix {
Matrix::Bt601 => (0.299, 0.114),
Matrix::Bt709 => (0.2126, 0.0722),
};
let r = y + 2.0 * (1.0 - kr) * v;
let b = y + 2.0 * (1.0 - kb) * u;
let g = (y - kr * r - kb * b) / (1.0 - kr - kb);
[r, g, b].map(|x| linear(x.clamp(0.0, 1.0), color.transfer))
}
pub fn linear(x: f32, transfer: Transfer) -> f32 {
match transfer {
Transfer::Srgb => rune_core::color::srgb_decode(x),
Transfer::Bt709 => {
if x < 0.081 {
x / 4.5
} else {
((x + 0.099) / 1.099).powf(1.0 / 0.45)
}
}
}
}
/// Synthetic bars, gradient and one-pixel text-like strokes. No decoded content is copied by import.
pub fn synthetic(width: u32, height: u32, phase: u64) -> ByteFrame {
assert!(width > 0 && height > 0 && width.is_multiple_of(2) && height.is_multiple_of(2));
let bars = [
[235, 128, 128],
[210, 16, 146],
[170, 166, 16],
[145, 54, 34],
[106, 202, 222],
[81, 90, 240],
[41, 240, 110],
[16, 128, 128],
];
let mut y = vec![0; (width * height) as usize];
let mut uv = vec![128; (width * height / 2) as usize];
for row in 0..height {
for x in 0..width {
y[(row * width + x) as usize] = if row < height / 3 {
bars[(x * 8 / width) as usize][0]
} else if row < 2 * height / 3 {
(16 + x * 219 / width) as u8
} else if (x + phase as u32).is_multiple_of(8) || row.is_multiple_of(9) {
235
} else {
16
};
}
}
for row in 0..height / 6 {
for x in 0..width / 2 {
let bar = bars[(x * 16 / width) as usize];
let i = (row * width + x * 2) as usize;
uv[i] = bar[1];
uv[i + 1] = bar[2];
}
}
ByteFrame {
width,
height,
format: Format::Nv12Video,
color: ColorInfo { matrix: Matrix::Bt709, transfer: Transfer::Bt709 },
planes: [y, uv],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn latest_wins_and_releases_old_frames() {
let surface = NativeSurface::new();
surface.push_bytes(synthetic(16, 16, 0), 1).unwrap();
let held = surface.latest().unwrap();
let old = Arc::downgrade(&held);
let producer = surface.clone();
std::thread::spawn(move || {
for id in 2..100 {
producer.push_bytes(synthetic(16, 16, id), id).unwrap();
}
})
.join()
.unwrap();
assert_eq!(surface.latest().unwrap().id, 99);
assert!(old.upgrade().is_some());
drop(held);
assert!(old.upgrade().is_none());
let newest = Arc::downgrade(&surface.latest().unwrap());
surface.clear();
assert!(newest.upgrade().is_none());
}
#[test]
fn range_endpoints_and_neutral_chroma() {
for matrix in [Matrix::Bt601, Matrix::Bt709] {
for transfer in [Transfer::Srgb, Transfer::Bt709] {
let c = ColorInfo { matrix, transfer };
assert_eq!(nv12_reference(16, 128, 128, Format::Nv12Video, c), [0.0; 3]);
for v in nv12_reference(235, 128, 128, Format::Nv12Video, c) {
assert!((v - 1.0).abs() < 1e-6);
}
assert_eq!(nv12_reference(0, 128, 128, Format::Nv12Full, c), [0.0; 3]);
}
}
}
#[test]
fn srgb_linear_matches_reference_formula_bit_for_bit() {
let reference = |x: f32| if x <= 0.04045 { x / 12.92 } else { ((x + 0.055) / 1.055).powf(2.4) };
for v in 0..=255u8 {
let x = v as f32 / 255.0;
assert_eq!(linear(x, Transfer::Srgb).to_bits(), reference(x).to_bits(), "byte {v}");
}
for x in [-0.5, -0.0, 0.0, 0.04044, 0.04045, 0.04046, 0.5, 1.0, 1.5] {
assert_eq!(linear(x, Transfer::Srgb).to_bits(), reference(x).to_bits(), "float {x}");
}
}
}
@@ -0,0 +1,406 @@
mod frame;
use super::*;
use rune_core::Blend;
use std::collections::HashMap;
fn blend_state(blend: Blend) -> wgpu::BlendState {
match blend {
Blend::SourceOver => wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
Blend::PlusLighter => {
let add = wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
};
wgpu::BlendState { color: add, alpha: add }
}
}
}
/// A renderer whose pipeline compiles on a thread of its own (`SurfaceRenderer::build`).
#[doc(hidden)]
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub struct Building {
format: wgpu::TextureFormat,
layout: wgpu::BindGroupLayout,
/// The compiled pipeline, once sent; None when the thread couldn't start.
built: Option<std::sync::mpsc::Receiver<wgpu::RenderPipeline>>,
/// The punch pipeline (`SurfaceRenderer::set_punched`), compiled next on the same thread;
/// the renderer takes the receiver.
punch: std::sync::Mutex<Option<std::sync::mpsc::Receiver<wgpu::RenderPipeline>>>,
}
pub(crate) struct Imported {
frame: Arc<Frame>,
textures: [wgpu::Texture; 2],
}
struct Prepared {
drawn: std::sync::atomic::AtomicBool,
before: u32,
bind: wgpu::BindGroup,
uniform: wgpu::Buffer,
imported: Arc<Imported>,
surface: NativeSurface,
/// Bind groups this draw made for other textures, newest last: a decoder cycles a few, so
/// a new picture in one it drew before binds with no allocation.
binds: Vec<([wgpu::Texture; 2], wgpu::BindGroup)>,
/// Its place is punched out of the window's pixels, for the clip's own layer underneath.
punch: bool,
/// It was drawn inside an isolated layer, where a punch can't reach the window.
isolated: std::sync::atomic::AtomicBool,
}
/// Clears a video's place by its coverage, colour and alpha alike: the window's pixels there go
/// transparent and the clip's own layer underneath shows (`video::windows::layer`).
#[cfg(target_os = "windows")]
const PUNCH: wgpu::BlendState = wgpu::BlendState { color: CLEAR, alpha: CLEAR };
#[cfg(target_os = "windows")]
const CLEAR: wgpu::BlendComponent = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::Zero, dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add };
// Metal has a small limit on live counter sample buffers. Keep one query set and lease
// disjoint pairs until their deferred resolve/readback completes, rather than allocating
// a query set for every queued frame. Timing may be omitted; rendering never waits.
#[cfg(not(target_arch = "wasm32"))]
const TIMING_SLOTS: u32 = 8;
struct TimingPool {
queries: wgpu::QuerySet,
free: std::sync::Mutex<Vec<u32>>,
}
impl TimingPool {
fn take(self: &Arc<Self>) -> Option<Arc<TimingSlot>> {
self.free.lock().unwrap().pop().map(|start| Arc::new(TimingSlot { pool: self.clone(), start }))
}
}
struct TimingSlot {
pool: Arc<TimingPool>,
start: u32,
}
impl Drop for TimingSlot {
fn drop(&mut self) {
self.pool.free.lock().unwrap().push(self.start);
}
}
/// Standalone pipeline, also used by Rune's renderer. A frame must be submitted through `submit`
/// for timing notifications; texture lifetimes are safe even with ordinary wgpu submission.
pub struct SurfaceRenderer {
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
device: wgpu::Device,
timing_pool: Option<Arc<TimingPool>>,
queries: Option<Arc<TimingSlot>>,
queries_used: std::sync::atomic::AtomicBool,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(super) completion: std::sync::mpsc::SyncSender<()>,
/// The queue timestamp resolves go to, held here so their callbacks hold it weakly.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
timing_queue: std::sync::OnceLock<Arc<wgpu::Queue>>,
pipeline: wgpu::RenderPipeline,
format: wgpu::TextureFormat,
extra: Vec<(wgpu::TextureFormat, wgpu::RenderPipeline)>,
additive: Option<(wgpu::TextureFormat, wgpu::RenderPipeline)>,
layout: wgpu::BindGroupLayout,
sampler: wgpu::Sampler,
cache: HashMap<usize, Arc<Imported>>,
draws: Vec<Prepared>,
/// Surfaces whose place is punched out (by key), and the pipeline that does it: the video's
/// coverage, opacity and clip, writing `dst * (1 - coverage)` to colour and alpha alike.
punched: Vec<usize>,
punch: Option<wgpu::RenderPipeline>,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
punch_building: Option<std::sync::mpsc::Receiver<wgpu::RenderPipeline>>,
srgb_blend: bool,
/// The owning `Renderer`'s uploads, when it has one; queue writes otherwise.
staging: Option<rune_staging::Staging>,
#[cfg(target_os = "macos")]
importer: Option<macos::Importer>,
#[cfg(target_os = "windows")]
shared: Option<windows::Importer>,
#[cfg(target_os = "linux")]
dmabuf: Option<linux::Importer>,
}
impl SurfaceRenderer {
#[cfg(target_arch = "wasm32")]
pub fn new(_: &wgpu::Device, _: wgpu::TextureFormat) -> Self {
panic!("native surfaces are unsupported on web")
}
#[cfg(target_arch = "wasm32")]
#[doc(hidden)]
pub fn build(_: &wgpu::Device, _: wgpu::TextureFormat, _: Box<dyn FnOnce() + Send>) -> Building {
panic!("native surfaces are unsupported on web")
}
#[cfg(target_arch = "wasm32")]
#[doc(hidden)]
pub fn finish(_: &wgpu::Device, _: &Building) -> Option<Self> {
None
}
#[cfg(not(target_arch = "wasm32"))]
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
let layout = Self::bind_layout(device);
let pipeline = Self::pipeline(device, &layout, format, Blend::SourceOver);
Self::with_pipeline(device, format, layout, pipeline)
}
/// Starts compiling the renderer's pipeline on a thread of its own, and runs `done` once
/// it's ready. The shader compiler takes hundreds of milliseconds (FXC on Windows), which
/// on the UI thread froze a window's input and held the first picture back.
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn build(device: &wgpu::Device, format: wgpu::TextureFormat, done: Box<dyn FnOnce() + Send>) -> Building {
let layout = Self::bind_layout(device);
let (sender, built) = std::sync::mpsc::sync_channel(1);
let (punch_sender, punch) = std::sync::mpsc::sync_channel(1);
let (device_for, layout_for) = (device.clone(), layout.clone());
let spawned = std::thread::Builder::new().name("rune-video-pipeline".into()).spawn(move || {
sender.send(Self::pipeline(&device_for, &layout_for, format, Blend::SourceOver)).ok();
done();
// A clip's layer (Windows) needs the punch; it compiles once the pictures can show.
#[cfg(target_os = "windows")]
punch_sender.send(Self::pipeline_with(&device_for, &layout_for, format, PUNCH)).ok();
#[cfg(not(target_os = "windows"))]
drop(punch_sender);
});
let ok = spawned.is_ok();
Building { format, layout, built: ok.then_some(built), punch: std::sync::Mutex::new(ok.then_some(punch)) }
}
/// The renderer `building` made, once its pipeline is ready; a build whose thread couldn't
/// start compiles here.
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn finish(device: &wgpu::Device, building: &Building) -> Option<Self> {
let pipeline = match &building.built {
Some(built) => built.try_recv().ok()?,
None => Self::pipeline(device, &building.layout, building.format, Blend::SourceOver),
};
let mut renderer = Self::with_pipeline(device, building.format, building.layout.clone(), pipeline);
// The punch arrives on this later.
renderer.punch_building = building.punch.lock().unwrap().take();
Some(renderer)
}
#[cfg(not(target_arch = "wasm32"))]
fn with_pipeline(device: &wgpu::Device, format: wgpu::TextureFormat, layout: wgpu::BindGroupLayout, pipeline: wgpu::RenderPipeline) -> Self {
let timing_pool = device.features().contains(wgpu::Features::TIMESTAMP_QUERY).then(|| {
Arc::new(TimingPool {
queries: device.create_query_set(&wgpu::QuerySetDescriptor {
label: Some("video frame timestamps"),
ty: wgpu::QueryType::Timestamp,
count: TIMING_SLOTS * 2,
}),
free: std::sync::Mutex::new((0..TIMING_SLOTS).map(|i| i * 2).collect()),
})
});
let (completion, receiver) = std::sync::mpsc::sync_channel(1);
let poll_device = device.clone();
std::thread::Builder::new()
.name("rune-video-completion".into())
.spawn(move || {
// Nonblocking poll releases wgpu's snatch lock before sleeping. A fence wait here
// would keep that read lock and serialize queue.present's write lock behind GPU work.
// Wakeups are coalesced; the final frame still completes after the window goes idle.
// A lost device's work never finishes: the worker stops rather than poll it forever.
while receiver.recv().is_ok() {
loop {
match rune_gpu::health::poll(&poll_device, wgpu::PollType::Poll) {
Ok(wgpu::PollStatus::QueueEmpty) => break,
Ok(_) => std::thread::sleep(std::time::Duration::from_millis(1)),
Err(_) => return,
}
}
}
})
.expect("video completion thread");
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("video linear"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
Self {
device: device.clone(),
timing_pool,
queries: None,
queries_used: std::sync::atomic::AtomicBool::new(false),
completion,
timing_queue: std::sync::OnceLock::new(),
pipeline,
format,
extra: Vec::new(),
additive: None,
layout,
sampler,
cache: HashMap::new(),
draws: Vec::new(),
punched: Vec::new(),
punch: None,
punch_building: None,
srgb_blend: false,
staging: None,
#[cfg(target_os = "macos")]
importer: None,
#[cfg(target_os = "windows")]
shared: None,
#[cfg(target_os = "linux")]
dmabuf: None,
}
}
#[cfg(not(target_arch = "wasm32"))]
fn bind_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("video"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
texture_entry(1),
texture_entry(2),
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
})
}
pub fn set_srgb_blend(&mut self, enabled: bool) {
self.srgb_blend = enabled;
}
#[doc(hidden)]
pub fn set_staging(&mut self, staging: rune_staging::Staging) {
self.staging = Some(staging);
}
fn pipeline(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, format: wgpu::TextureFormat, blend: Blend) -> wgpu::RenderPipeline {
Self::pipeline_with(device, layout, format, blend_state(blend))
}
fn pipeline_with(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, format: wgpu::TextureFormat, blend: wgpu::BlendState) -> wgpu::RenderPipeline {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("video"),
source: wgpu::ShaderSource::Wgsl(include_str!("video.wgsl").into()),
});
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("video"),
bind_group_layouts: &[Some(layout)],
immediate_size: 0,
});
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("video"),
layout: Some(&pl),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleStrip, ..Default::default() },
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
}
#[doc(hidden)]
pub fn add_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) {
if format != self.format && !self.extra.iter().any(|(f, _)| *f == format) {
self.extra.push((format, Self::pipeline(device, &self.layout, format, Blend::SourceOver)));
}
}
#[doc(hidden)]
pub fn add_plus_lighter(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) {
if self.additive.as_ref().is_none_or(|(f, _)| *f != format) {
self.additive = Some((format, Self::pipeline(device, &self.layout, format, Blend::PlusLighter)));
}
}
#[cfg(all(test, target_os = "macos"))]
pub(super) fn live_planes(&self) -> usize {
self.importer.as_ref().map_or(0, |i| i.live_planes.load(std::sync::atomic::Ordering::SeqCst))
}
#[cfg(target_os = "windows")]
#[doc(hidden)]
/// Punches these surfaces' places out of the window's pixels from the next `prepare` on,
/// once the punch pipeline has compiled (`punch_ready`).
pub fn set_punched(&mut self, keys: Vec<usize>) {
self.punched = keys;
}
/// The punch pipeline has compiled. A renderer made without `build` starts compiling it here,
/// on a thread of its own as `build` does.
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub fn punch_ready(&mut self) -> bool {
if self.punch.is_some() {
return true;
}
if self.punch_building.is_none() {
let (sender, receiver) = std::sync::mpsc::sync_channel(1);
let (device, layout, format) = (self.device.clone(), self.layout.clone(), self.format);
let spawned = std::thread::Builder::new()
.name("rune-video-punch".into())
.spawn(move || drop(sender.send(Self::pipeline_with(&device, &layout, format, PUNCH))));
if spawned.is_err() {
return false;
}
self.punch_building = Some(receiver);
}
if let Some(p) = self.punch_building.as_ref().and_then(|b| b.try_recv().ok()) {
self.punch = Some(p);
self.punch_building = None;
}
self.punch.is_some()
}
}
pub(super) fn descriptor(width: u32, height: u32, format: wgpu::TextureFormat) -> wgpu::TextureDescriptor<'static> {
wgpu::TextureDescriptor {
label: Some("video plane"),
size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
}
}
#[cfg(not(target_arch = "wasm32"))]
fn texture_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
}
}
@@ -0,0 +1,530 @@
use super::super::*;
use super::{Imported, Prepared, SurfaceRenderer, TimingPool};
use bytemuck::{Pod, Zeroable};
use rune_core::Blend;
use wgpu::util::DeviceExt;
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct Uniforms {
viewport: [f32; 4],
node: [f32; 4],
image: [f32; 4],
radii: [f32; 4],
clip: [f32; 4],
fade: [u32; 4],
// format (0 BGRA, 1 video NV12, 2 full NV12), matrix (0 601, 1 709), transfer, alpha
color: [f32; 4],
// Exact mapping flag, source dimensions, horizontal mirror flag.
sampling: [f32; 4],
// `Orient`: centred upright to centred buffer coordinates.
orient: [f32; 4],
}
const _: () = {
assert!(std::mem::size_of::<Uniforms>() == 144);
assert!(std::mem::offset_of!(Uniforms, viewport) == 0);
assert!(std::mem::offset_of!(Uniforms, node) == 16);
assert!(std::mem::offset_of!(Uniforms, image) == 32);
assert!(std::mem::offset_of!(Uniforms, radii) == 48);
assert!(std::mem::offset_of!(Uniforms, clip) == 64);
assert!(std::mem::offset_of!(Uniforms, fade) == 80);
assert!(std::mem::offset_of!(Uniforms, color) == 96);
assert!(std::mem::offset_of!(Uniforms, sampling) == 112);
assert!(std::mem::offset_of!(Uniforms, orient) == 128);
};
/// Bind groups a draw keeps for textures it may show again (a video decoder's ring).
const KEPT_BINDS: usize = 8;
impl SurfaceRenderer {
fn write(&self, queue: &wgpu::Queue, buffer: &wgpu::Buffer, data: &[u8]) {
match &self.staging {
Some(s) => s.write_buffer(buffer, 0, data),
None => queue.write_buffer(buffer, 0, data),
}
}
pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, draws: &[SurfaceDraw], viewport: (u32, u32)) {
*self.queries_used.get_mut() = false;
// Release an unsubmitted preparation before acquiring its replacement. Submitted
// slots stay leased by their completion callbacks, including the deferred resolve.
self.queries = None;
// GPU times only for a surface someone watches: resolving them costs a submission a frame.
if draws.iter().any(|d| d.surface.observed()) {
self.queries = self.timing_pool.as_ref().and_then(TimingPool::take);
}
self.cache.retain(|key, _| draws.iter().any(|d| d.surface.key() == *key));
// Keep uniforms/bindings on unchanged frames. The source is latched here, after scene build.
let mut count = 0;
for d in draws {
let Some((frame, mirrored)) = d.surface.latest_mirrored() else {
self.cache.remove(&d.surface.key());
continue;
};
if d.rect[2] <= 0.0 || d.rect[3] <= 0.0 {
continue;
}
let key = d.surface.key();
let changed = self.cache.get(&key).is_none_or(|v| !Arc::ptr_eq(&v.frame, &frame));
if changed {
match self.import(device, queue, frame) {
Ok(imported) => {
self.cache.insert(key, Arc::new(imported));
d.surface.0.lock().unwrap().error = None;
}
Err(e) => {
d.surface.0.lock().unwrap().error = Some(e);
self.cache.remove(&key);
continue;
}
}
}
let imported = self.cache[&key].clone();
let f = &imported.frame;
let upright = f.orient.upright(f.size);
let image = super::super::place::image_rect(d.rect, upright, d.fit, d.surface.place());
let exact = (image[2] - upright[0] as f32).abs() < 0.001
&& (image[3] - upright[1] as f32).abs() < 0.001
&& (image[0] - image[0].round()).abs() < 0.001
&& (image[1] - image[1].round()).abs() < 0.001;
let u = Uniforms {
viewport: [viewport.0 as f32, viewport.1 as f32, 0.0, 0.0],
node: d.rect,
image,
radii: d.radii,
clip: d.clip,
fade: d.fade,
color: [
match f.format {
Format::Bgra => 0.0,
Format::Nv12Video => 1.0,
Format::Nv12Full => 2.0,
},
if f.color.matrix == Matrix::Bt709 { 1.0 } else { 0.0 },
if self.srgb_blend { 2.0 } else if f.color.transfer == Transfer::Srgb { 0.0 } else { 1.0 },
d.opacity,
],
sampling: [if exact { 1.0 } else { 0.0 }, f.size[0] as f32, f.size[1] as f32, if mirrored { 1.0 } else { 0.0 }],
orient: f.orient.0.map(f32::from),
};
// The same draw with a new picture keeps its uniform buffer, and its bind group too
// when the picture is in textures it bound before.
if let Some(p) = self.draws.get_mut(count).filter(|p| p.surface.key() == d.surface.key() || Arc::ptr_eq(&p.imported, &imported)) {
*p.drawn.get_mut() = false;
match &self.staging {
Some(s) => s.write_buffer(&p.uniform, 0, bytemuck::bytes_of(&u)),
None => queue.write_buffer(&p.uniform, 0, bytemuck::bytes_of(&u)),
}
if !Arc::ptr_eq(&p.imported, &imported) && p.imported.textures != imported.textures {
let old = std::mem::replace(&mut p.bind, match p.binds.iter().position(|(t, _)| *t == imported.textures) {
Some(i) => p.binds.remove(i).1,
None => bind_group(device, &self.layout, &self.sampler, &p.uniform, &imported.textures),
});
p.binds.push((p.imported.textures.clone(), old));
if p.binds.len() > KEPT_BINDS {
p.binds.remove(0);
}
}
p.imported = imported;
p.before = d.before_instance;
p.surface = d.surface.clone();
} else {
let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("video node"),
contents: bytemuck::bytes_of(&u),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let bind = bind_group(device, &self.layout, &self.sampler, &uniform, &imported.textures);
let p = Prepared {
drawn: std::sync::atomic::AtomicBool::new(false),
before: d.before_instance,
bind,
uniform,
imported,
surface: d.surface.clone(),
binds: Vec::new(),
punch: false,
isolated: std::sync::atomic::AtomicBool::new(false),
};
if count < self.draws.len() {
self.draws[count] = p;
} else {
self.draws.push(p);
}
}
let p = &mut self.draws[count];
p.punch = self.punch.is_some() && self.punched.contains(&key);
*p.isolated.get_mut() = false;
count += 1;
}
self.draws.truncate(count);
#[cfg(target_os = "windows")]
if let Some(shared) = &mut self.shared {
shared.forget_gone();
}
#[cfg(target_os = "linux")]
if let Some(dmabuf) = &mut self.dmabuf {
dmabuf.forget_gone();
}
#[cfg(target_os = "macos")]
if let Some(i) = &self.importer {
i.flush();
}
}
fn import(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame: Arc<Frame>) -> Result<Imported, String> {
let textures = match &frame.source {
// Checks the size itself, so every failure reaches the producer.
#[cfg(target_os = "linux")]
Source::Dmabuf(d) => linux::import(&mut self.dmabuf, device, queue, d)?,
_ if frame.size.iter().any(|v| *v > device.limits().max_texture_dimension_2d) => {
return Err("video dimensions exceed this GPU device's texture limit".into());
}
Source::Bytes(b) => {
let a = upload(
device,
queue,
b.width,
b.height,
if b.format == Format::Bgra {
wgpu::TextureFormat::Bgra8Unorm
} else {
wgpu::TextureFormat::R8Unorm
},
&b.planes[0],
);
let b = if b.format == Format::Bgra {
a.clone()
} else {
upload(device, queue, b.width / 2, b.height / 2, wgpu::TextureFormat::Rg8Unorm, &b.planes[1])
};
[a, b]
}
#[cfg(target_os = "macos")]
Source::PixelBuffer(b) => {
if self.importer.is_none() {
self.importer = Some(macos::Importer::new(device)?);
}
objc2::rc::autoreleasepool(|_| {
self.importer.as_ref().unwrap().import(b, frame.format, frame.size)
})?
}
#[cfg(target_os = "windows")]
Source::Shared(t) => {
if self.shared.is_none() {
self.shared = Some(windows::Importer::new(device)?);
}
self.shared.as_mut().unwrap().import(queue, t)?
}
#[cfg(target_os = "windows")]
Source::Decoded(planes, value) => {
if self.shared.is_none() {
self.shared = Some(windows::Importer::new(device)?);
}
self.shared.as_mut().unwrap().import_decoded(queue, planes, *value)?
}
};
Ok(Imported { frame, textures })
}
pub fn len(&self) -> usize {
self.draws.len()
}
pub fn is_empty(&self) -> bool {
self.draws.is_empty()
}
#[doc(hidden)]
pub fn draws_nothing(&self) -> bool {
self.draws.is_empty()
}
/// Include this in the containing render pass for hardware GPU timing.
/// Submit that encoder through [`Self::submit`] before the next [`Self::prepare`].
/// Plain `Queue::submit` does not retain the timing slot and may let it be reused
/// while the recorded pass is still in flight.
pub fn timestamp_writes(&self) -> Option<wgpu::RenderPassTimestampWrites<'_>> {
if self.draws.is_empty() {
return None;
}
self.queries.as_ref().map(|slot| {
self.queries_used.store(true, std::sync::atomic::Ordering::Relaxed);
wgpu::RenderPassTimestampWrites {
query_set: &slot.pool.queries,
beginning_of_pass_write_index: Some(slot.start),
end_of_pass_write_index: Some(slot.start + 1),
}
})
}
#[cfg(target_os = "windows")]
#[doc(hidden)]
/// Whether the last frame drew surface `key` inside an isolated layer, where a punch
/// can't reach the window; None when it didn't draw it.
pub fn drew_isolated(&self, key: usize) -> Option<bool> {
self.draws.iter().find(|d| d.surface.key() == key).map(|d| d.isolated.load(std::sync::atomic::Ordering::Relaxed))
}
/// Draws `index` in the window's own pass: punched out when asked, else as any other.
#[doc(hidden)]
pub fn draw_main(&self, pass: &mut wgpu::RenderPass<'_>, index: usize, format: wgpu::TextureFormat, blend: Blend) {
match (&self.punch, self.draws[index].punch) {
(Some(punch), true) => {
self.draws[index].drawn.store(true, std::sync::atomic::Ordering::Relaxed);
pass.set_pipeline(punch);
pass.set_bind_group(0, &self.draws[index].bind, &[]);
pass.draw(0..4, 0..1);
}
_ => self.draw_blended(pass, index, format, blend),
}
}
/// Draws `index` inside an isolated layer.
#[doc(hidden)]
pub fn draw_isolated(&self, pass: &mut wgpu::RenderPass<'_>, index: usize, format: wgpu::TextureFormat, blend: Blend) {
self.draws[index].isolated.store(true, std::sync::atomic::Ordering::Relaxed);
self.draw_blended(pass, index, format, blend);
}
pub fn before_instance(&self, index: usize) -> u32 {
self.draws[index].before
}
/// Reproject one draw into a bounded layer without moving its screen-space clip or UVs.
#[doc(hidden)]
pub fn target(&self, queue: &wgpu::Queue, index: usize, bounds: [f32; 4]) {
self.write(queue, &self.draws[index].uniform, bytemuck::cast_slice(&[bounds[2], bounds[3], bounds[0], bounds[1]]));
}
pub fn draw(&self, pass: &mut wgpu::RenderPass<'_>, index: usize) {
self.draw_format(pass, index, self.format);
}
#[doc(hidden)]
pub fn draw_format(&self, pass: &mut wgpu::RenderPass<'_>, index: usize, format: wgpu::TextureFormat) {
self.draw_blended(pass, index, format, Blend::SourceOver);
}
#[doc(hidden)]
pub fn draw_blended(&self, pass: &mut wgpu::RenderPass<'_>, index: usize, format: wgpu::TextureFormat, blend: Blend) {
self.draws[index].drawn.store(true, std::sync::atomic::Ordering::Relaxed);
pass.set_pipeline(if blend == Blend::PlusLighter {
let (f, pipeline) = self.additive.as_ref().expect("prepared dissolve surface");
assert_eq!(*f, format);
pipeline
} else if format == self.format { &self.pipeline } else {
&self.extra.iter().find(|(f, _)| *f == format).expect("SurfaceRenderer::add_format first").1
});
pass.set_bind_group(0, &self.draws[index].bind, &[]);
pass.draw(0..4, 0..1);
}
#[cfg(target_arch = "wasm32")]
pub fn submit(&self, queue: &wgpu::Queue, encoder: wgpu::CommandEncoder) -> wgpu::SubmissionIndex {
assert!(self.draws.is_empty(), "native video surfaces are unsupported on web");
queue.submit([encoder.finish()])
}
#[cfg(not(target_arch = "wasm32"))]
pub fn submit(&self, queue: &wgpu::Queue, encoder: wgpu::CommandEncoder) -> wgpu::SubmissionIndex {
let submitted_at = rune_core::time::now();
let frames: Vec<_> = self
.draws
.iter()
.filter(|p| p.drawn.load(std::sync::atomic::Ordering::Relaxed))
.map(|p| {
(
p.surface.clone(),
p.imported.clone(),
FrameTiming {
frame_id: p.imported.frame.id,
submitted_at,
completed_at: None,
gpu_start_seconds: None,
gpu_end_seconds: None,
},
)
})
.collect();
if frames.is_empty() {
return queue.submit([encoder.finish()]);
}
// Notify before installing the GPU handler: completion may race queue.submit returning.
for (surface, _, t) in &frames {
surface.report(t.clone());
}
// A caller may use Renderer::draw_timed with its own query set. Never resolve our
// unwritten counters in that case; CPU submission/completion notifications still work.
if let Some(queries) =
self.queries.as_ref().filter(|_| self.queries_used.load(std::sync::atomic::Ordering::Relaxed))
{
let resolve = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("video timestamps"),
size: 16,
usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let readback = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("video timestamp readback"),
size: 16,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let seconds_per_tick = queue.get_timestamp_period() as f64 * 1e-9;
let queries = queries.clone();
let device = self.device.clone();
// Weak: the queue keeps this closure until it runs, and a queue held by it would keep
// the queue (and the closure) alive for good if its device is lost first.
let queue = Arc::downgrade(self.timing_queue.get_or_init(|| Arc::new(queue.clone())));
let completion = self.completion.clone();
// Metal counter resolves can race the render pass's final fragment sample when
// encoded into the same command buffer. Resolve after its completion fence; this
// is timestamp metadata only, never a readback or wait on the video pixel path.
encoder.on_submitted_work_done(move || {
let completed_at = rune_core::time::now();
// The renderer is gone (its device lost and replaced, or the app closing): nothing
// resolves the times.
let Some(queue) = queue.upgrade() else {
for (s, _, mut t) in frames {
t.completed_at = Some(completed_at);
s.report(t);
}
return;
};
let mut timestamps = device.create_command_encoder(&Default::default());
timestamps.resolve_query_set(&queries.pool.queries, queries.start..queries.start + 2, &resolve, 0);
timestamps.copy_buffer_to_buffer(&resolve, 0, &readback, 0, 16);
let result = readback.clone();
timestamps.map_buffer_on_submit(&readback, wgpu::MapMode::Read, .., move |status| {
// Nothing in a wgpu callback may panic: a map aborted while a thread unwinds
// runs it then, and a second panic aborts the process.
let times = status.as_ref().ok().and_then(|_| result.slice(..).get_mapped_range().ok()).and_then(|bytes| {
let a = u64::from_le_bytes(bytes.get(0..8)?.try_into().ok()?);
let b = u64::from_le_bytes(bytes.get(8..16)?.try_into().ok()?);
(b >= a && b != 0).then_some((a as f64 * seconds_per_tick, b as f64 * seconds_per_tick))
});
if status.is_ok() {
result.unmap();
}
// The sample pair must survive both GPU submissions and CPU mapping.
drop(queries);
for (s, _, mut t) in frames {
t.completed_at = Some(completed_at);
if let Some((a, b)) = times {
t.gpu_start_seconds = Some(a);
t.gpu_end_seconds = Some(b);
}
s.report(t);
}
});
queue.submit([timestamps.finish()]);
completion.try_send(()).ok();
});
} else {
encoder.on_submitted_work_done(move || {
for (s, _, mut t) in frames {
t.completed_at = Some(rune_core::time::now());
s.report(t);
}
});
}
let index = queue.submit([encoder.finish()]);
self.release_decoded(queue);
self.completion.try_send(()).ok();
index
}
/// Decoded video pictures this submission drew may be written again once it's done.
#[cfg(not(target_arch = "wasm32"))]
fn release_decoded(&self, queue: &wgpu::Queue) {
#[cfg(target_os = "windows")]
for p in self.draws.iter().filter(|p| p.drawn.load(std::sync::atomic::Ordering::Relaxed)) {
if let Source::Decoded(planes, value) = &p.imported.frame.source {
windows::release_decoded(queue, planes, *value);
}
}
#[cfg(not(target_os = "windows"))]
let _ = queue;
}
}
fn upload(
device: &wgpu::Device,
queue: &wgpu::Queue,
width: u32,
height: u32,
format: wgpu::TextureFormat,
bytes: &[u8],
) -> wgpu::Texture {
let mut desc = super::descriptor(width, height, format);
desc.usage |= wgpu::TextureUsages::COPY_DST;
let texture = device.create_texture(&desc);
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytes,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(width * format.block_copy_size(None).unwrap()),
rows_per_image: None,
},
desc.size,
);
texture
}
fn bind_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, sampler: &wgpu::Sampler, uniform: &wgpu::Buffer, textures: &[wgpu::Texture; 2]) -> wgpu::BindGroup {
let views = textures.each_ref().map(|t| t.create_view(&Default::default()));
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("video frame"),
layout,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&views[0]) },
wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&views[1]) },
wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(sampler) },
],
})
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod abi_tests {
use super::Uniforms;
#[test]
fn wgsl_video_uniforms_layout_matches_rust() {
use wgpu::naga::{TypeInner, front::wgsl, proc::Layouter, valid::{Capabilities, ValidationFlags, Validator}};
let source = include_str!("../video.wgsl");
let module = wgsl::parse_str(source).unwrap_or_else(|e| panic!("{}", e.emit_to_string(source)));
Validator::new(ValidationFlags::all(), Capabilities::default() | Capabilities::SHADER_FLOAT16_IN_FLOAT32)
.validate(&module)
.expect("validate video.wgsl");
let mut layouter = Layouter::default();
layouter.update(module.to_ctx()).expect("layout video.wgsl");
let (handle, ty) = module
.types
.iter()
.find(|(_, t)| t.name.as_deref() == Some("Uniforms"))
.expect("WGSL struct Uniforms not found");
assert_eq!(layouter[handle].size as usize, std::mem::size_of::<Uniforms>());
let TypeInner::Struct { members, span } = &ty.inner else { panic!("Uniforms is not a struct") };
assert_eq!(*span as usize, std::mem::size_of::<Uniforms>());
let expected: &[(&str, usize)] = &[
("viewport", std::mem::offset_of!(Uniforms, viewport)),
("node", std::mem::offset_of!(Uniforms, node)),
("image", std::mem::offset_of!(Uniforms, image)),
("radii", std::mem::offset_of!(Uniforms, radii)),
("clip", std::mem::offset_of!(Uniforms, clip)),
("fade", std::mem::offset_of!(Uniforms, fade)),
("color", std::mem::offset_of!(Uniforms, color)),
("sampling", std::mem::offset_of!(Uniforms, sampling)),
("orient", std::mem::offset_of!(Uniforms, orient)),
];
assert_eq!(members.len(), expected.len());
for (member, &(field, offset)) in members.iter().zip(expected) {
assert_eq!(member.name.as_deref(), Some(field), "Uniforms.{field} name");
assert_eq!(member.offset as usize, offset, "Uniforms.{field} offset");
}
}
}
@@ -0,0 +1,90 @@
use super::gpu_tests::{Gpu, OFFSCREEN_FORMAT};
use super::place::{Align, SurfacePlace, image_rect};
use super::*;
use rune_image::pixels::fit;
const TOP_LEFT: SurfacePlace = SurfacePlace { anchor: [Align::Start; 2], unscaled: false };
const TOP_LEFT_1X: SurfacePlace = SurfacePlace { anchor: [Align::Start; 2], unscaled: true };
fn near(got: [f32; 4], want: [f32; 4], what: &str) {
assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3), "{what}: {got:?} vs {want:?}");
}
const STALE: [u32; 2] = [100, 50];
#[test]
fn centred_default_is_the_old_placement() {
let c = SurfacePlace::default();
assert_eq!(c, SurfacePlace::CENTRED);
assert_eq!(image_rect([0.0, 0.0, 120.0, 50.0], STALE, SurfaceFit::Fit, c), [10.0, 0.0, 100.0, 50.0]);
near(image_rect([0.0, 0.0, 120.0, 50.0], STALE, SurfaceFit::Fill, c), [0.0, -5.0, 120.0, 60.0], "fill wide");
assert_eq!(image_rect([0.0, 0.0, 80.0, 60.0], STALE, SurfaceFit::Fit, c), [0.0, 10.0, 80.0, 40.0]);
near(image_rect([0.0, 0.0, 80.0, 60.0], STALE, SurfaceFit::Fill, c), [-20.0, 0.0, 120.0, 60.0], "fill tall");
}
#[test]
fn top_left_anchor_pins_the_corner_under_fit_and_fill() {
let at = |node, f| image_rect(node, STALE, f, TOP_LEFT);
assert_eq!(at([0.0, 0.0, 120.0, 50.0], SurfaceFit::Fit), [0.0, 0.0, 100.0, 50.0], "gap on the right");
near(at([0.0, 0.0, 120.0, 50.0], SurfaceFit::Fill), [0.0, 0.0, 120.0, 60.0], "crops the bottom only");
assert_eq!(at([0.0, 0.0, 80.0, 60.0], SurfaceFit::Fit), [0.0, 0.0, 80.0, 40.0], "gap below");
near(at([0.0, 0.0, 80.0, 60.0], SurfaceFit::Fill), [0.0, 0.0, 120.0, 60.0], "crops the right only");
}
#[test]
fn unscaled_keeps_texels_and_loses_only_the_far_edges() {
let at = |node| image_rect(node, STALE, SurfaceFit::Fill, TOP_LEFT_1X);
assert_eq!(at([0.0, 0.0, 120.0, 50.0]), [0.0, 0.0, 100.0, 50.0], "grow: gap at the right");
assert_eq!(at([0.0, 0.0, 80.0, 60.0]), [0.0, 0.0, 100.0, 50.0], "shrink: node clips the right; gap below");
assert_eq!(image_rect([7.0, 9.0, 120.0, 50.0], STALE, SurfaceFit::Fit, TOP_LEFT_1X), [7.0, 9.0, 100.0, 50.0], "fit is ignored");
let end = SurfacePlace { anchor: [Align::End, Align::End], unscaled: true };
assert_eq!(image_rect([0.0, 0.0, 80.0, 60.0], STALE, SurfaceFit::Fit, end), [-20.0, 10.0, 100.0, 50.0]);
}
#[test]
fn pixels_follow_the_same_anchor() {
use SurfaceFit::{Fill, Fit};
let size = (100, 50);
let wide = [0.0, 0.0, 120.0, 50.0];
let tall = [0.0, 0.0, 80.0, 60.0];
assert_eq!(fit(Some(Fit), TOP_LEFT, wide, size), ([0.0, 0.0, 100.0, 50.0], [0.0, 0.0, 1.0, 1.0]));
assert_eq!(fit(Some(Fit), TOP_LEFT, tall, size), ([0.0, 0.0, 80.0, 40.0], [0.0, 0.0, 1.0, 1.0]));
let (rect, crop) = fit(Some(Fill), TOP_LEFT, tall, size);
assert_eq!((rect, crop[0], crop[1]), (tall, 0.0, 0.0));
assert!((crop[3] - 1.0).abs() < 1e-6);
assert!((crop[2] - 80.0 / 120.0).abs() < 1e-6, "keeps the left two thirds: {crop:?}");
let (rect, crop) = fit(Some(Fill), TOP_LEFT, wide, size);
assert_eq!((rect, crop[0], crop[1]), (wide, 0.0, 0.0));
assert!((crop[2] - 1.0).abs() < 1e-6);
assert!((crop[3] - 50.0 / 60.0).abs() < 1e-6, "drops the bottom: {crop:?}");
assert_eq!(fit(Some(Fill), TOP_LEFT_1X, wide, size), ([0.0, 0.0, 100.0, 50.0], [0.0, 0.0, 1.0, 1.0]));
assert_eq!(fit(Some(Fit), TOP_LEFT_1X, tall, size), ([0.0, 0.0, 80.0, 50.0], [0.0, 0.0, 0.8, 1.0]));
assert_eq!(fit(None, TOP_LEFT_1X, tall, size), (tall, [0.0, 0.0, 1.0, 1.0]), "a stretched image ignores placement");
}
#[test]
fn a_stale_frame_draws_pinned_top_left_on_the_gpu() {
let gpu = Gpu::headless_wgpu();
let mut renderer = SurfaceRenderer::new(&gpu.device, OFFSCREEN_FORMAT);
let (frame, src) = super::gpu_tests::bgra_ramp(8, 4);
let surface = NativeSurface::new();
surface.push_bytes(frame, 1).unwrap();
let mut d = super::gpu_tests::draw(&surface, [0.0, 0.0, 10.0, 6.0]);
d.surface = surface.placed(TOP_LEFT_1X);
d.fit = SurfaceFit::Fill;
let out = super::gpu_tests::render(&gpu, &mut renderer, &[d.clone()], (10, 6));
for y in 0..4 {
for x in 0..8 {
assert_eq!(super::gpu_tests::pixel(&out, 10, x, y), src[(y * 8 + x) as usize], "texel ({x},{y})");
}
}
for (x, y) in [(8, 0), (9, 3), (0, 4), (9, 5)] {
assert_eq!(super::gpu_tests::pixel(&out, 10, x, y)[3], 0, "empty at ({x},{y})");
}
d.rect = [0.0, 0.0, 6.0, 3.0];
let out = super::gpu_tests::render(&gpu, &mut renderer, &[d], (6, 3));
for y in 0..3 {
for x in 0..6 {
assert_eq!(super::gpu_tests::pixel(&out, 6, x, y), src[(y * 8 + x) as usize], "cropped texel ({x},{y})");
}
}
}
@@ -0,0 +1,995 @@
use super::*;
pub(super) const NO_CLIP: [f32; 4] = [-1e6, -1e6, 1e6, 1e6];
pub(super) const OFFSCREEN_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
static GPU_INIT: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// One test's GPU at a time on Windows, so the overlap probe's pending workload is timed alone,
/// not beside another test's GPU work.
#[cfg(target_os = "windows")]
static GPU_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// A test's GPU. A lost device (a GPU reset, a driver update, a GPU removed) fails the test that
/// owns it, at the latest when the test ends: a loss also completes work and fires callbacks,
/// which would otherwise read as the GPU having done what the test asked.
pub(super) struct Gpu {
pub adapter: wgpu::Adapter,
pub device: wgpu::Device,
pub queue: wgpu::Queue,
lost: Arc<std::sync::Mutex<Option<String>>>,
#[cfg(target_os = "windows")]
_serial: std::sync::MutexGuard<'static, ()>,
}
impl Drop for Gpu {
fn drop(&mut self) {
if !std::thread::panicking() {
self.assert_alive();
}
}
}
impl Gpu {
pub(super) fn new(instance: wgpu::Instance) -> Self {
#[cfg(target_os = "windows")]
let _serial = GPU_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let _init = GPU_INIT.lock().unwrap_or_else(|e| e.into_inner());
let pick = rune_gpu::pick::pick(&instance, None, false).expect("pick GPU adapter");
let required_features = pick.adapter.features() & (wgpu::Features::TIMESTAMP_QUERY | rune_gpu::backend::free_features(&pick.adapter));
let adapter_limits = pick.adapter.limits();
let required_limits = if adapter_limits.max_inter_stage_shader_variables < wgpu::Limits::default().max_inter_stage_shader_variables
|| adapter_limits.max_color_attachments < wgpu::Limits::default().max_color_attachments
|| adapter_limits.max_compute_workgroup_storage_size < wgpu::Limits::default().max_compute_workgroup_storage_size
{
wgpu::Limits::downlevel_defaults().using_resolution(adapter_limits.clone()).using_alignment(adapter_limits)
} else {
wgpu::Limits::default().using_resolution(adapter_limits.clone()).using_alignment(adapter_limits)
};
let (device, queue) = pollster::block_on(pick.adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("rune-media-test"),
required_features,
required_limits,
memory_hints: wgpu::MemoryHints::MemoryUsage,
..Default::default()
}))
.expect("request GPU device");
let lost = Arc::new(std::sync::Mutex::new(None));
let heard = lost.clone();
device.set_device_lost_callback(move |reason, message| {
if reason != wgpu::DeviceLostReason::Destroyed {
*heard.lock().unwrap_or_else(|e| e.into_inner()) = Some(format!("{reason:?}: {message}"));
}
});
Self {
adapter: pick.adapter,
device,
queue,
lost,
#[cfg(target_os = "windows")]
_serial,
}
}
/// Fails the test if its device was lost.
pub(super) fn assert_alive(&self) {
if rune_gpu::health::removed(&self.device) {
panic!("the GPU device was removed during this test, on {}: nothing it read from the GPU since counts", self.adapter.get_info().name);
}
if let Some(why) = self.lost.lock().unwrap_or_else(|e| e.into_inner()).clone() {
panic!("the GPU device was lost during this test ({why}), on {}: nothing it read from the GPU since counts", self.adapter.get_info().name);
}
}
/// What a GPU callback sends on `heard` within `within`, failing the test as soon as the
/// device is lost: a lost device's callbacks may never come.
pub(super) fn wait<T>(&self, heard: &std::sync::mpsc::Receiver<T>, within: std::time::Duration) -> Option<T> {
let until = rune_core::time::now() + within;
loop {
if let Ok(value) = heard.recv_timeout(std::time::Duration::from_millis(5)) {
self.assert_alive();
return Some(value);
}
self.assert_alive();
if rune_core::time::now() >= until {
return None;
}
}
}
pub(super) fn headless_wgpu() -> Self {
static INSTANCE: std::sync::OnceLock<wgpu::Instance> = std::sync::OnceLock::new();
let instance = INSTANCE.get_or_init(|| {
let _serial = GPU_INIT.lock().unwrap_or_else(|e| e.into_inner());
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
#[cfg(target_os = "windows")]
{
desc.backends = wgpu::Backends::DX12;
}
desc.flags &= !wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL;
wgpu::Instance::new(desc)
});
Self::new(instance.clone())
}
}
pub(super) struct Offscreen {
texture: wgpu::Texture,
pub view: wgpu::TextureView,
buffer: wgpu::Buffer,
width: u32,
height: u32,
padded_row: u32,
}
impl Offscreen {
pub(super) fn new(device: &wgpu::Device, width: u32, height: u32) -> Self {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("offscreen"),
size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: OFFSCREEN_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = texture.create_view(&Default::default());
let padded_row = (width * 4).div_ceil(256) * 256;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("readback"),
size: (padded_row * height) as u64,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
Self { texture, view, buffer, width, height, padded_row }
}
pub(super) fn copy(&self, encoder: &mut wgpu::CommandEncoder) {
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo { texture: &self.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::TexelCopyBufferInfo {
buffer: &self.buffer,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(self.padded_row), rows_per_image: Some(self.height) },
},
wgpu::Extent3d { width: self.width, height: self.height, depth_or_array_layers: 1 },
);
}
pub(super) fn read(&self, device: &wgpu::Device) -> Vec<u8> {
let slice = self.buffer.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).expect("poll");
let row = (self.width * 4) as usize;
let stride = self.padded_row as usize;
let out = {
let data = slice.get_mapped_range().expect("mapped range");
let mut out = Vec::with_capacity(row * self.height as usize);
for y in 0..self.height as usize {
out.extend_from_slice(&data[y * stride..y * stride + row]);
}
out
};
self.buffer.unmap();
out
}
}
/// Records, on drop, whether the surface's state lock was free: a callback that reads `counts`
/// would deadlock if it weren't.
struct CallbackProbe(NativeSurface, Arc<std::sync::Mutex<Vec<bool>>>);
impl Drop for CallbackProbe {
fn drop(&mut self) {
self.1.lock().unwrap().push(self.0.0.try_lock().is_ok());
}
}
/// A replaced callback's captures drop after the surface's lock, so one reading `counts` or
/// `last_error` can't deadlock there. // differs from dev: dev dropped it under the lock.
#[test]
fn a_replaced_callback_is_dropped_outside_the_surfaces_lock() {
let surface = NativeSurface::new();
let freed = Arc::new(std::sync::Mutex::new(Vec::new()));
let waker = CallbackProbe(surface.clone(), freed.clone());
surface.set_waker(Arc::new(move || {
let _ = &waker;
}));
surface.set_waker(Arc::new(|| {}));
let observer = CallbackProbe(surface.clone(), freed.clone());
surface.set_observer(Arc::new(move |_| {
let _ = &observer;
}));
surface.set_observer(Arc::new(|_| {}));
assert_eq!(*freed.lock().unwrap(), [true, true], "a callback dropped while the lock was held");
}
pub(super) fn draw(surface: &NativeSurface, rect: [f32; 4]) -> SurfaceDraw {
SurfaceDraw {
surface: surface.clone(),
fit: SurfaceFit::Fit,
before_instance: 0,
rect,
radii: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
opacity: 1.0,
}
}
pub(super) fn render(gpu: &Gpu, renderer: &mut SurfaceRenderer, draws: &[SurfaceDraw], size: (u32, u32)) -> Vec<u8> {
let (completed, completion) = std::sync::mpsc::channel();
for d in draws {
let completed = completed.clone();
d.surface.set_observer(Arc::new(move |t| {
if t.completed_at.is_some() {
completed.send(()).ok();
}
}));
}
renderer.prepare(&gpu.device, &gpu.queue, draws, size);
for d in draws {
assert_eq!(d.surface.last_error(), None);
}
let target = Offscreen::new(&gpu.device, size.0, size.1);
let mut encoder = gpu.device.create_command_encoder(&Default::default());
{
let mut pass = clear_pass(&mut encoder, &target.view, wgpu::Color::TRANSPARENT, renderer.timestamp_writes());
for i in 0..renderer.len() {
renderer.draw(&mut pass, i);
}
}
target.copy(&mut encoder);
renderer.submit(&gpu.queue, encoder);
let pixels = target.read(&gpu.device);
for _ in draws {
gpu.wait(&completion, std::time::Duration::from_secs(10)).expect("frame completion");
}
pixels
}
fn clear_pass<'e>(
encoder: &'e mut wgpu::CommandEncoder,
view: &wgpu::TextureView,
clear: wgpu::Color,
timestamp_writes: Option<wgpu::RenderPassTimestampWrites<'_>>,
) -> wgpu::RenderPass<'e> {
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(clear), store: wgpu::StoreOp::Store },
})],
timestamp_writes,
..Default::default()
})
}
/// A pixel test on wgpu, and with `metal-backend` on Rune's native Metal backend too.
macro_rules! on_each_backend {
($wgpu:ident, $metal:ident, $body:ident) => {
#[test]
fn $wgpu() {
$body(Gpu::headless_wgpu());
}
#[cfg(all(target_vendor = "apple", feature = "metal-backend"))]
#[test]
fn $metal() {
$body(Gpu::new(rune_gpu::metal::instance()));
}
};
}
fn srgb(x: f32) -> u8 {
let x = if x <= 0.0031308 { x * 12.92 } else { 1.055 * x.powf(1.0 / 2.4) - 0.055 };
(x.clamp(0.0, 1.0) * 255.0).round() as u8
}
/// Buffer destruction and queue.present both acquire wgpu-core's device snatch write lock.
/// Exercise that lock without a window: it must remain available while the completion
/// worker services a submission whose GPU workload is deliberately still running.
///
/// Checked by ordering, not wall-clock time: the lock was taken and released, and a poll
/// after it still found the GPU work pending. A worker that held the snatch read lock through
/// a fence wait would block `destroy` until the work completed, and the poll would then fire
/// its callback. An attempt whose workload finished before the probe (a loaded machine
/// delaying this thread) proves nothing either way, so it retries with more work.
///
/// The pending work is a queue of submissions of one fixed size, `CHUNK` loop iterations per
/// invocation (1.07 billion in all, about 30 ms on a Ryzen 9950X3D's integrated GPU), ahead of
/// the submission with the surface's draw and the callback: a worker that waited on the
/// submission it serves, or on all of them, holds the lock until every one is done. Nothing
/// measured changes a submission's size; a timing decides only how many are queued. The timing
/// tells a submission's fixed round trip (a small submission's time) from its work (a full one's
/// time beyond that), so an adapter with a slow round trip (Metal on an Apple M4: 6,094 us for
/// a 64th of the work) isn't taken for a slow GPU. An overestimate only queues less, and a
/// timed attempt's own run lowers it for the next; an adapter is never refused for being slow,
/// and nothing it measures can size one submission past `CHUNK`. Before anything is known only
/// `CHUNK / 64` is issued (about 1,400 us on that integrated GPU, round trip included, and 4,700
/// to 6,700 us on WARP); each larger size, up by fours, only once four times the size below's
/// whole time fits in `PLANNED_MOST`. An adapter too slow for that queues the smaller size, as
/// WARP does. Windows resets a
/// GPU whose one submission runs 2 s, and an AMD GPU preempts nothing smaller than a
/// submission: 68.7 billion iterations in one submission ran past that on the same integrated
/// GPU, and the reset's completion read as an overlap.
#[test]
fn completion_worker_preserves_cpu_gpu_overlap() {
use std::sync::mpsc::TryRecvError;
use std::time::Duration;
const INVOCATIONS: u32 = 1024 * 64;
const CHUNK: u32 = 16_384;
const PLANNED_MOST: Duration = Duration::from_millis(100);
const CHUNKS_MOST: u32 = 512;
/// However cheap a chunk's work measures, no attempt queues chunks whose full submit-to-done
/// times add up past this.
const QUEUED_MOST: Duration = Duration::from_secs(2);
let gpu = Gpu::headless_wgpu();
let surface = NativeSurface::new();
surface.push_bytes(synthetic(16, 16, 0), 1).unwrap();
let mut renderer = SurfaceRenderer::new(&gpu.device, OFFSCREEN_FORMAT);
let shader = gpu.device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("overlap workload"),
source: wgpu::ShaderSource::Wgsl(
r#"
@group(0) @binding(0) var<storage, read_write> result: array<u32>;
@group(0) @binding(1) var<uniform> iterations: vec4<u32>;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
var x = id.x;
for (var i = 0u; i < iterations.x; i++) {
x = (x ^ (x >> 13u)) * 1664525u + 1013904223u;
}
result[id.x] = x;
}
"#
.into(),
),
});
let compute = gpu.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("overlap workload"),
layout: None,
module: &shader,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
let buffer = gpu.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: u64::from(INVOCATIONS) * 4,
usage: wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
});
let bind_for = |iterations: u32| {
let work = gpu.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("overlap iterations"),
size: 16,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
gpu.queue.write_buffer(&work, 0, bytemuck::cast_slice(&[iterations, 0, 0, 0]));
gpu.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &compute.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: work.as_entire_binding() },
],
})
};
// A submission's sizes: `CHUNK / 64`, the only size issued before anything is known, then up
// by fours to `CHUNK`, each only when the one below predicts it fits (see the calibration).
let sizes = [CHUNK / 64, CHUNK / 16, CHUNK / 4, CHUNK];
let binds = sizes.map(bind_for);
let small = &binds[0];
let submit = |bind: &wgpu::BindGroup| {
let mut encoder = gpu.device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&compute);
pass.set_bind_group(0, bind, &[]);
pass.dispatch_workgroups(INVOCATIONS / 64, 1, 1);
}
gpu.queue.submit([encoder.finish()])
};
let time = |bind: &wgpu::BindGroup| {
let started = rune_core::time::now();
let index = submit(bind);
if gpu.device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: Some(Duration::from_secs(5)) }).is_err() {
gpu.assert_alive();
panic!("a calibration submission didn't complete in 5 s");
}
gpu.assert_alive();
started.elapsed()
};
// The first submission also pays for the pipeline's first use; it times nothing.
time(small);
let name = gpu.adapter.get_info().name;
let floor = time(small);
// Up by fours, while four times the last size's whole time (round trip and all, so an upper
// bound on the next size's time whatever the round trip is) fits in `PLANNED_MOST`. No
// submission is issued that a smaller one hasn't predicted fits. A software adapter (WARP)
// runs the work on the CPU, with no GPU to reset; it stays at the first size.
let software = gpu.adapter.get_info().device_type == wgpu::DeviceType::Cpu;
let mut step = (0, floor);
let mut steps = vec![floor.as_micros()];
while !software && step.0 + 1 < sizes.len() && step.1 * 4 <= PLANNED_MOST {
step = (step.0 + 1, time(&binds[step.0 + 1]));
steps.push(step.1.as_micros());
}
let (index, chunk_alone) = step;
let (chunk, size) = (&binds[index], sizes[index]);
// A chunk queued behind others pays for its work, not for another round trip: what it took
// beyond the first size's time, or all of it when it is the first size.
let mut per_chunk = if index == 0 { chunk_alone } else { chunk_alone.saturating_sub(floor).max(chunk_alone / 64) };
let chunks_most = ((QUEUED_MOST.as_secs_f64() / chunk_alone.as_secs_f64().max(1e-6)) as u32).clamp(1, CHUNKS_MOST);
let why = if size == CHUNK { "the full chunk".to_string() } else if software { "a software adapter".to_string() } else { format!("{} us x 4 would pass {} us", chunk_alone.as_micros(), PLANNED_MOST.as_micros()) };
eprintln!(
"overlap probe: on {name}, {} to {} iterations per invocation took {steps:?} us; queueing {size} per invocation ({why}), {} us alone, {} us of it work; at most {chunks_most} queued",
CHUNK / 64,
sizes[index],
chunk_alone.as_micros(),
per_chunk.as_micros()
);
let target = Offscreen::new(&gpu.device, 16, 16);
let mut outcomes = Vec::new();
for planned in [25, 50, 100, 100, 100].map(Duration::from_millis) {
let planned = planned.min(PLANNED_MOST);
let chunks = (planned.as_secs_f64() / per_chunk.as_secs_f64().max(1e-6)).ceil().clamp(1.0, f64::from(chunks_most)) as u32;
renderer.prepare(&gpu.device, &gpu.queue, &[draw(&surface, [0.0, 0.0, 16.0, 16.0])], (16, 16));
let probe = gpu.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("present lock probe"),
size: 4,
usage: wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let submitted = rune_core::time::now();
for _ in 0..chunks {
submit(chunk);
}
let mut encoder = gpu.device.create_command_encoder(&Default::default());
{
let mut pass = clear_pass(&mut encoder, &target.view, wgpu::Color::BLACK, renderer.timestamp_writes());
renderer.draw(&mut pass, 0);
}
let (done, completed) = std::sync::mpsc::channel();
encoder.on_submitted_work_done(move || {
done.send(rune_core::time::now()).ok();
});
renderer.submit(&gpu.queue, encoder);
// The worker has taken submit's wakeup once its one-slot channel has room again: it is
// in its polling loop, which only leaves once the queue is empty.
while renderer.completion.try_send(()).is_err() {
std::thread::yield_now();
}
std::thread::sleep(Duration::from_millis(1));
let (outcome, finished) = if let Ok(at) = completed.try_recv() {
("finished before the probe", at)
} else {
probe.destroy();
gpu.device.poll(wgpu::PollType::Poll).unwrap();
match completed.try_recv() {
Err(TryRecvError::Empty) => {
let at = gpu.wait(&completed, Duration::from_secs(30));
("overlapped", at.unwrap_or_else(|| panic!("{chunks} submissions planned at {} us never completed", planned.as_micros())))
}
Ok(at) => ("finished by the time the write lock returned", at),
Err(TryRecvError::Disconnected) => panic!("the GPU workload's callback was dropped"),
}
};
// A lost device completes its submissions too, which is no overlap.
gpu.assert_alive();
eprintln!("overlap probe: {chunks} submissions planned at {} us, submit to done {} us, {outcome}", planned.as_micros(), (finished - submitted).as_micros());
if outcome == "overlapped" {
return;
}
// Submit to done bounds the chunks' GPU time: the next plan can only come out shorter.
per_chunk = per_chunk.min((finished - submitted) / chunks);
outcomes.push(outcome);
}
// Five attempts, none overlapping: either the write lock waited for the work every time (the
// fault this test is for), or the work never stayed pending long enough to tell.
panic!("on {name}, no attempt found the snatch write lock free while GPU work was pending: {outcomes:?}");
}
fn publish(s: &NativeSurface, b: ByteFrame, id: u64, native: bool) {
#[cfg(target_os = "macos")]
if native {
s.push(macos::PixelBuffer::from_bytes(&b).unwrap(), id).unwrap();
return;
}
let _ = native;
s.push_bytes(b, id).unwrap();
}
on_each_backend!(queued_video_frames_then_readback, queued_video_frames_then_readback_on_metal, queued_video_frames_then_readback_on);
fn queued_video_frames_then_readback_on(gpu: Gpu) {
let mut renderer = SurfaceRenderer::new(&gpu.device, OFFSCREEN_FORMAT);
let surfaces: Vec<_> = (0..4).map(|_| NativeSurface::new()).collect();
let (done, completed) = std::sync::mpsc::channel();
let draws: Vec<_> = surfaces
.iter()
.enumerate()
.map(|(i, s)| {
publish(s, synthetic(640, 360, 0), 0, cfg!(target_os = "macos"));
let done = done.clone();
s.set_observer(Arc::new(move |t| {
if t.completed_at.is_some() {
done.send(t).ok();
}
}));
draw(s, [(i % 2) as f32 * 640.0, (i / 2) as f32 * 360.0, 640.0, 360.0])
})
.collect();
let target = Offscreen::new(&gpu.device, 1280, 720);
let mut expected = None;
// Headless --at 1 queues 61 frames but maps pixels only after the last one.
// Exercise multiple bursts so completion polling overlaps the next submission.
for _ in 0..8 {
for frame in 0..61 {
renderer.prepare(&gpu.device, &gpu.queue, &draws, (1280, 720));
let mut encoder = gpu.device.create_command_encoder(&Default::default());
{
let mut pass =
clear_pass(&mut encoder, &target.view, wgpu::Color::TRANSPARENT, renderer.timestamp_writes());
for i in 0..renderer.len() {
renderer.draw(&mut pass, i);
}
}
if frame == 60 {
target.copy(&mut encoder);
}
renderer.submit(&gpu.queue, encoder);
}
let pixels = target.read(&gpu.device);
if let Some(expected) = &expected {
assert_eq!(&pixels, expected, "unchanged queued frames must read back identically");
} else {
assert!(pixels.iter().any(|&v| v != 0));
expected = Some(pixels);
}
}
let mut timed = 0;
for _ in 0..8 * 61 * 4 {
let t = completed.recv_timeout(std::time::Duration::from_secs(10)).expect("queued frame completion");
assert_eq!(t.gpu_start_seconds.is_some(), t.gpu_end_seconds.is_some());
if let Some((start, end)) = t.gpu_start_seconds.zip(t.gpu_end_seconds) {
assert!(end >= start && end > 0.0, "invalid timestamps: {t:?}");
timed += 1;
}
}
if gpu.device.features().contains(wgpu::Features::TIMESTAMP_QUERY) {
assert!(timed > 0, "queued frames must still produce GPU timing samples");
}
}
on_each_backend!(video_gpu_colour_sharpness_geometry_and_lifetime, video_gpu_colour_sharpness_geometry_and_lifetime_on_metal, video_gpu_colour_sharpness_geometry_and_lifetime_on);
fn video_gpu_colour_sharpness_geometry_and_lifetime_on(gpu: Gpu) {
// Other renderers (including the parallel burst test) may own native planes.
// Their lifetime must not affect this renderer's ownership assertions.
#[cfg(target_os = "macos")]
let _unrelated = {
let surface = NativeSurface::new();
publish(&surface, synthetic(16, 16, 0), 0, true);
let mut renderer = SurfaceRenderer::new(&gpu.device, OFFSCREEN_FORMAT);
renderer.prepare(&gpu.device, &gpu.queue, &[draw(&surface, [0.0, 0.0, 16.0, 16.0])], (16, 16));
assert_eq!(renderer.live_planes(), 2);
renderer
};
let mut renderer = SurfaceRenderer::new(&gpu.device, OFFSCREEN_FORMAT);
let surface = NativeSurface::new();
let mut id = 0;
for native in [false, cfg!(target_os = "macos")] {
for format in [Format::Nv12Video, Format::Nv12Full] {
for matrix in [Matrix::Bt601, Matrix::Bt709] {
for transfer in [Transfer::Srgb, Transfer::Bt709] {
let color = ColorInfo { matrix, transfer };
for codes in [
[16, 128, 128],
[235, 128, 128],
[0, 128, 128],
[255, 128, 128],
[81, 90, 240],
[145, 54, 34],
[41, 240, 110],
[128, 128, 128],
] {
id += 1;
publish(
&surface,
ByteFrame {
width: 8,
height: 8,
format,
color,
planes: [vec![codes[0]; 64], [codes[1], codes[2]].repeat(16)],
},
id,
native,
);
let pixels = render(&gpu, &mut renderer, &[draw(&surface, [0.0, 0.0, 8.0, 8.0])], (8, 8));
let reference = nv12_reference(codes[0], codes[1], codes[2], format, color).map(srgb);
for pixel in pixels.chunks_exact(4) {
for c in 0..3 {
assert!(
pixel[c].abs_diff(reference[c]) <= 1,
"native={native} {format:?} {matrix:?} {transfer:?} {codes:?}: {pixel:?} != {reference:?}"
);
}
assert_eq!(pixel[3], 255);
}
}
}
}
}
// At matching device size every one-pixel stroke survives exactly. sRGB NV12 full
// neutral chroma is an identity; BGRA checks all 256 code values in all channels.
for format in [Format::Nv12Full, Format::Bgra] {
let mut b = ByteFrame {
width: 256,
height: 16,
format,
color: ColorInfo::default(),
planes: [Vec::new(), Vec::new()],
};
let mut expected = Vec::new();
for y in 0..16 {
for x in 0..256 {
let v = if y % 2 == 0 { x as u8 } else { if x % 2 == 0 { 0 } else { 255 } };
if format == Format::Bgra {
b.planes[0].extend_from_slice(&[v, 255 - v, v / 2, 255]);
expected.extend_from_slice(&[v / 2, 255 - v, v, 255]);
} else {
b.planes[0].push(v);
expected.extend_from_slice(&[v, v, v, 255]);
}
}
}
if format != Format::Bgra {
b.planes[1] = vec![128; 256 * 16 / 2];
}
id += 1;
publish(&surface, b, id, native);
let pixels = render(&gpu, &mut renderer, &[draw(&surface, [0.0, 0.0, 256.0, 16.0])], (256, 16));
assert_eq!(pixels, expected, "1:1 pixels changed for native={native}, format={format:?}");
}
}
let held = surface.latest().unwrap();
let weak = Arc::downgrade(&held);
drop(held);
surface.clear();
assert!(weak.upgrade().is_some(), "renderer must retain its current frame");
renderer.prepare(&gpu.device, &gpu.queue, &[], (256, 16));
gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
assert!(weak.upgrade().is_none(), "old frame leaked after completion and removal");
#[cfg(target_os = "macos")]
assert_eq!(renderer.live_planes(), 0, "CVMetalTexture ownership leaked");
let (submitted, completed) = surface.counts();
assert_eq!(submitted, completed);
let timing = surface.timing().unwrap();
assert_eq!(timing.frame_id, id);
assert!(timing.completed_at.unwrap() >= timing.submitted_at);
if gpu.device.features().contains(wgpu::Features::TIMESTAMP_QUERY) {
assert!(timing.gpu_end_seconds.is_some(), "timestamp query produced no times: {timing:?}");
assert!(timing.gpu_end_seconds.unwrap() >= timing.gpu_start_seconds.unwrap());
} else {
eprintln!("adapter has no timestamp queries: {:?}", gpu.adapter.get_info());
}
// Contain letterboxes, cover crops, and rounded clip remains local to the node.
publish(
&surface,
ByteFrame {
width: 16,
height: 8,
format: Format::Bgra,
color: ColorInfo::default(),
planes: [vec![255; 16 * 8 * 4], vec![]],
},
999,
false,
);
let mut d = draw(&surface, [0.0, 0.0, 16.0, 16.0]);
let p = render(&gpu, &mut renderer, &[d.clone()], (16, 16));
assert_eq!(&p[0..4], &[0; 4]);
assert_eq!(&p[8 * 16 * 4..8 * 16 * 4 + 4], &[255; 4]);
d.fit = SurfaceFit::Fill;
let p = render(&gpu, &mut renderer, &[d.clone()], (16, 16));
assert_eq!(&p[0..4], &[255; 4]);
d.radii = [8.0; 4];
d.clip[2] = 12.0;
let p = render(&gpu, &mut renderer, &[d], (16, 16));
assert_eq!(p[3], 0);
assert_eq!(p[(8 * 16 + 14) * 4 + 3], 0);
assert_eq!(p[(8 * 16 + 8) * 4 + 3], 255);
#[cfg(target_os = "macos")]
{
// Drop mailbox + renderer references while commands are encoded but unsubmitted.
// The wgpu HAL ownership guard, not a borrowed CoreVideo/Metal pointer, must survive.
surface.push(macos::PixelBuffer::from_bytes(&synthetic(16, 16, 0)).unwrap(), 1000).unwrap();
renderer.prepare(&gpu.device, &gpu.queue, &[draw(&surface, [0.0, 0.0, 16.0, 16.0])], (16, 16));
let target = Offscreen::new(&gpu.device, 16, 16);
let mut encoder = gpu.device.create_command_encoder(&Default::default());
{
let mut pass = clear_pass(&mut encoder, &target.view, wgpu::Color::TRANSPARENT, None);
renderer.draw(&mut pass, 0);
}
surface.clear();
renderer.prepare(&gpu.device, &gpu.queue, &[], (16, 16));
assert_eq!(renderer.live_planes(), 2, "encoded frames released too early");
target.copy(&mut encoder);
gpu.queue.submit([encoder.finish()]);
let p = target.read(&gpu.device);
assert_eq!(p[3], 255);
assert_eq!(renderer.live_planes(), 0, "submitted plane owners leaked");
}
}
/// BGRA whose every pixel differs, so any column swap shows. Returns the source and its RGBA readback.
pub(super) fn bgra_ramp(width: u32, height: u32) -> (ByteFrame, Vec<[u8; 4]>) {
let mut planes = Vec::new();
let mut rgba = Vec::new();
for y in 0..height {
for x in 0..width {
let v = (x * 13 + y * 61) as u8;
planes.extend_from_slice(&[v, 255 - v, (y * 40) as u8, 255]);
rgba.push([(y * 40) as u8, 255 - v, v, 255]);
}
}
(ByteFrame { width, height, format: Format::Bgra, color: ColorInfo::default(), planes: [planes, vec![]] }, rgba)
}
pub(super) fn pixel(p: &[u8], width: u32, x: u32, y: u32) -> [u8; 4] {
let i = ((y * width + x) * 4) as usize;
p[i..i + 4].try_into().unwrap()
}
/// A mirrored draw must equal the unmirrored draw with each row reversed (any centred image).
fn assert_row_reversed(mirrored: &[u8], plain: &[u8], size: (u32, u32), what: &str) {
for y in 0..size.1 {
for x in 0..size.0 {
let (a, b) = (pixel(mirrored, size.0, x, y), pixel(plain, size.0, size.0 - 1 - x, y));
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 1), "{what} ({x},{y}): {a:?} != {b:?}");
}
}
}
on_each_backend!(mirrored_video_is_exact_cropped_centred_and_toggles_without_a_new_frame, mirrored_video_on_metal, mirrored_video_is_exact_cropped_centred_and_toggles_without_a_new_frame_on);
fn mirrored_video_is_exact_cropped_centred_and_toggles_without_a_new_frame_on(gpu: Gpu) {
let mut renderer = SurfaceRenderer::new(&gpu.device, OFFSCREEN_FORMAT);
let mut id = 0;
for native in [false, cfg!(target_os = "macos")] {
let surface = NativeSurface::new();
surface.set_mirrored(true);
let mut publish_next = |b: ByteFrame| {
id += 1;
publish(&surface, b, id, native);
};
// 1:1 BGRA: each one-pixel column lands exactly on its mirror, also when the node's
// odd spare pixel snaps the image origin to x = 1.
let (b, src) = bgra_ramp(8, 4);
publish_next(b);
for (node_w, origin) in [(8u32, 0u32), (9, 1)] {
let p = render(&gpu, &mut renderer, &[draw(&surface, [0.0, 0.0, node_w as f32, 4.0])], (node_w, 4));
for y in 0..4 {
for x in origin..origin + 8 {
let expected = src[(y * 8 + (7 - (x - origin))) as usize];
assert_eq!(pixel(&p, node_w, x, y), expected, "native={native} 1:1 mirror at ({x},{y}) in {node_w}");
}
}
}
// 1:1 Fill crop of a 16x8 source into 8x8: columns 4..12 show, mirrored about the centre.
let (b, src) = bgra_ramp(16, 8);
publish_next(b);
let mut d = draw(&surface, [0.0, 0.0, 8.0, 8.0]);
d.fit = SurfaceFit::Fill;
let p = render(&gpu, &mut renderer, &[d], (8, 8));
for y in 0..8 {
for x in 0..8 {
assert_eq!(pixel(&p, 8, x, y), src[(y * 16 + 11 - x) as usize], "native={native} Fill crop ({x},{y})");
}
}
// NV12 at 1:1: luma per pixel and each 2x2 chroma block move together.
let (w, h) = (8u32, 4u32);
let luma: Vec<u8> = (0..w * h).map(|i| (16 + i * 6) as u8).collect();
let chroma: Vec<u8> = (0..w * h / 4).flat_map(|i| [(40 + i * 20) as u8, (200 - i * 18) as u8]).collect();
let color = ColorInfo { matrix: Matrix::Bt709, transfer: Transfer::Srgb };
publish_next(ByteFrame {
width: w,
height: h,
format: Format::Nv12Full,
color,
planes: [luma.clone(), chroma.clone()],
});
let p = render(&gpu, &mut renderer, &[draw(&surface, [0.0, 0.0, w as f32, h as f32])], (w, h));
for y in 0..h {
for x in 0..w {
let sx = w - 1 - x;
let c = ((y / 2) * (w / 2) + sx / 2) as usize * 2;
let reference =
nv12_reference(luma[(y * w + sx) as usize], chroma[c], chroma[c + 1], Format::Nv12Full, color)
.map(srgb);
let got = pixel(&p, w, x, y);
for i in 0..3 {
assert!(got[i].abs_diff(reference[i]) <= 1, "native={native} NV12 ({x},{y}): {got:?} != {reference:?}");
}
}
}
// Filtered paths: bilinear Fill (2x, cropped) and the area-grid shrink, BGRA and NV12.
let (bgra, _) = bgra_ramp(16, 8);
for (frame, rect, fit, size, what) in [
(bgra, [0.0, 0.0, 16.0, 16.0], SurfaceFit::Fill, (16, 16), "BGRA bilinear Fill"),
(synthetic(32, 16, 3), [0.0, 0.0, 24.0, 20.0], SurfaceFit::Fill, (24, 20), "NV12 bilinear Fill"),
(synthetic(128, 32, 5), [0.0, 0.0, 8.0, 8.0], SurfaceFit::Fit, (8, 8), "NV12 area shrink"),
] {
publish_next(frame);
let mut d = draw(&surface, rect);
d.fit = fit;
surface.set_mirrored(false);
let plain = render(&gpu, &mut renderer, &[d.clone()], size);
surface.set_mirrored(true);
let mirrored = render(&gpu, &mut renderer, &[d], size);
assert_ne!(plain, mirrored, "{what}: the source must not be symmetric");
assert_row_reversed(&mirrored, &plain, size, &format!("native={native} {what}"));
}
// Rounded corners, clips and opacity stay put in screen space.
let (b, _) = bgra_ramp(16, 16);
publish_next(b);
let mut d = draw(&surface, [0.0, 0.0, 16.0, 16.0]);
d.radii = [8.0, 0.0, 0.0, 0.0];
d.clip[2] = 12.0;
d.opacity = 0.5;
let p = render(&gpu, &mut renderer, &[d], (16, 16));
assert_eq!(pixel(&p, 16, 0, 0)[3], 0, "top-left radius");
assert_eq!(pixel(&p, 16, 15, 0)[3], 0, "right clip");
assert!(pixel(&p, 16, 11, 0)[3].abs_diff(128) <= 1, "opacity");
}
// Toggling wakes once per change and redraws the same cached frame, with no new push.
let surface = NativeSurface::new();
let wakes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let w = wakes.clone();
surface.set_waker(Arc::new(move || {
w.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}));
let (b, src) = bgra_ramp(8, 2);
surface.push_bytes(b, 1).unwrap();
let woken = wakes.load(std::sync::atomic::Ordering::SeqCst);
let d = [draw(&surface, [0.0, 0.0, 8.0, 2.0])];
let plain = render(&gpu, &mut renderer, &d, (8, 2));
assert_eq!(pixel(&plain, 8, 0, 0), src[0]);
let clone = surface.clone();
clone.set_mirrored(true);
clone.set_mirrored(true);
assert!(surface.is_mirrored(), "clones share the flag");
assert_eq!(wakes.load(std::sync::atomic::Ordering::SeqCst), woken + 1, "one wake per change");
let mirrored = render(&gpu, &mut renderer, &d, (8, 2));
assert_eq!(pixel(&mirrored, 8, 0, 0), src[7]);
assert_row_reversed(&mirrored, &plain, (8, 2), "runtime toggle");
surface.set_mirrored(false);
assert_eq!(wakes.load(std::sync::atomic::Ordering::SeqCst), woken + 2);
assert_eq!(render(&gpu, &mut renderer, &d, (8, 2)), plain, "unmirroring restores the frame");
assert_eq!(surface.latest().unwrap().id, 1, "no new frame was pushed");
}
const ORIENTS: [[i8; 4]; 8] =
[[1, 0, 0, 1], [-1, 0, 0, 1], [1, 0, 0, -1], [-1, 0, 0, -1], [0, 1, 1, 0], [0, -1, 1, 0], [0, 1, -1, 0], [0, -1, -1, 0]];
/// The buffer pixel an upright pixel shows, by rotating about the centre.
fn buffer_pixel(o: Orient, [w, h]: [u32; 2], x: u32, y: u32) -> (u32, u32) {
let [uw, uh] = o.upright([w, h]);
let (cx, cy) = (x as f64 + 0.5 - uw as f64 / 2.0, y as f64 + 0.5 - uh as f64 / 2.0);
let m = o.0.map(f64::from);
((m[0] * cx + m[1] * cy + w as f64 / 2.0).floor() as u32, (m[2] * cx + m[3] * cy + h as f64 / 2.0).floor() as u32)
}
/// The frame turned upright on the CPU.
fn turned(b: &ByteFrame, o: Orient) -> ByteFrame {
let plane = |p: &[u8], w: u32, h: u32, bpp: usize| {
let [uw, uh] = o.upright([w, h]);
let mut out = Vec::with_capacity(p.len());
for y in 0..uh {
for x in 0..uw {
let (bx, by) = buffer_pixel(o, [w, h], x, y);
let i = (by * w + bx) as usize * bpp;
out.extend_from_slice(&p[i..i + bpp]);
}
}
out
};
let [w, h] = [b.width, b.height];
let planes = match b.format {
Format::Bgra => [plane(&b.planes[0], w, h, 4), vec![]],
_ => [plane(&b.planes[0], w, h, 1), plane(&b.planes[1], w / 2, h / 2, 2)],
};
let [width, height] = o.upright([w, h]);
ByteFrame { width, height, format: b.format, color: b.color, planes }
}
fn publish_oriented(s: &NativeSurface, b: ByteFrame, id: u64, native: bool, o: Orient) {
#[cfg(target_os = "macos")]
if native {
s.push_oriented(macos::PixelBuffer::from_bytes(&b).unwrap(), id, o).unwrap();
return;
}
let _ = native;
s.push_bytes_oriented(b, id, o).unwrap();
}
#[test]
fn orientations_come_from_quarter_turn_transforms_only() {
// An iPhone portrait clip: buffer (x, y) shows at (h - y, x).
assert_eq!(Orient::from_transform(0.0, 1.0, -1.0, 0.0), Orient([0, 1, -1, 0]));
assert_eq!(Orient::from_transform(1.0, 0.0, 0.0, 1.0), Orient::UP);
assert_eq!(Orient::from_transform(-1.0, 0.0, 0.0, -1.0), Orient([-1, 0, 0, -1]));
let s = std::f64::consts::FRAC_1_SQRT_2;
assert_eq!(Orient::from_transform(s, s, -s, s), Orient::UP, "45 degrees isn't a quarter turn");
assert_eq!(Orient::from_transform(2.0, 0.0, 0.0, 2.0), Orient::UP, "scales are ignored");
assert!(Orient([0, 1, -1, 0]).swaps());
assert_eq!(Orient([0, 1, -1, 0]).upright([64, 32]), [32, 64]);
// The buffer's top-left pixel ends up top-right, as it does on the phone.
assert_eq!(buffer_pixel(Orient([0, 1, -1, 0]), [6, 4], 3, 0), (0, 0));
}
// A buffer drawn with an orientation equals the same picture turned upright on the CPU, for
// every quarter turn and flip, at 1:1, magnified and shrunk, BGRA and NV12.
on_each_backend!(oriented_frames_draw_like_frames_turned_upright, oriented_frames_on_metal, oriented_frames_draw_like_frames_turned_upright_on);
fn oriented_frames_draw_like_frames_turned_upright_on(gpu: Gpu) {
let mut renderer = SurfaceRenderer::new(&gpu.device, OFFSCREEN_FORMAT);
let mut id = 0;
for native in [false, cfg!(target_os = "macos")] {
for m in ORIENTS {
let o = Orient(m);
for frame in [bgra_ramp(16, 8).0, synthetic(32, 16, 3)] {
let upright = turned(&frame, o);
let [uw, uh] = [upright.width, upright.height];
let (oriented, reference) = (NativeSurface::new(), NativeSurface::new());
id += 1;
publish_oriented(&oriented, frame, id, native, o);
publish(&reference, upright, id, native);
for (w, h, what) in [(uw, uh, "1:1"), (uw * 2, uh * 2, "2x"), (uw / 2, uh / 2, "half")] {
let rect = [0.0, 0.0, w as f32, h as f32];
let got = render(&gpu, &mut renderer, &[draw(&oriented, rect)], (w, h));
let want = render(&gpu, &mut renderer, &[draw(&reference, rect)], (w, h));
for (i, (g, r)) in got.iter().zip(&want).enumerate() {
assert!(g.abs_diff(*r) <= 1, "native={native} {m:?} {what} byte {i}: {g} != {r}");
}
}
}
}
}
}
// A portrait clip stored sideways (display matrix rotate=90): its player buffers, drawn with
// the track's orientation, match the upright poster AVFoundation decodes, quadrant by quadrant.
#[cfg(target_os = "macos")]
on_each_backend!(rotated_clip_buffers_draw_upright_like_its_poster, rotated_clip_on_metal, rotated_clip_buffers_draw_upright_like_its_poster_on);
#[cfg(target_os = "macos")]
fn rotated_clip_buffers_draw_upright_like_its_poster_on(gpu: Gpu) {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../rune/tests/fixtures/quadrants-rot90.mp4");
let (upright, raw, o) = crate::video::test_frames(&crate::MediaSource::File(path), 0.125).unwrap();
assert_eq!((raw.width, raw.height), (64, 32), "stored landscape");
assert_eq!((upright.width, upright.height), (32, 64), "shown portrait");
assert!(o.swaps(), "{o:?}");
let mut renderer = SurfaceRenderer::new(&gpu.device, OFFSCREEN_FORMAT);
for native in [false, true] {
let (oriented, poster) = (NativeSurface::new(), NativeSurface::new());
publish_oriented(&oriented, ByteFrame { planes: raw.planes.clone(), ..raw }, 1, native, o);
publish(&poster, ByteFrame { planes: upright.planes.clone(), ..upright }, 1, native);
for scale in [1, 2] {
let (w, h) = (32 / scale, 64 / scale);
let rect = [0.0, 0.0, w as f32, h as f32];
let got = render(&gpu, &mut renderer, &[draw(&oriented, rect)], (w, h));
let want = render(&gpu, &mut renderer, &[draw(&poster, rect)], (w, h));
// Inside each quadrant, clear of chroma bleed at its edges.
let mut colours = Vec::new();
for (qx, qy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let (x, y) = ((qx * 16 + 8) / scale, (qy * 32 + 16) / scale);
let (g, r) = (pixel(&got, w, x, y), pixel(&want, w, x, y));
assert!(g.iter().zip(r).all(|(g, r)| g.abs_diff(r) <= 8), "native={native} 1/{scale} quadrant ({qx},{qy}): {g:?} != {r:?}");
colours.push(r);
}
colours.dedup();
assert_eq!(colours.len(), 4, "four distinct quadrants: {colours:?}");
}
}
}
@@ -0,0 +1,142 @@
struct Uniforms {
viewport: vec4<f32>, node: vec4<f32>, image: vec4<f32>, radii: vec4<f32>,
clip: vec4<f32>, fade: vec4<u32>, color: vec4<f32>, sampling: vec4<f32>, orient: vec4<f32>,
};
@group(0) @binding(0) var<uniform> u: Uniforms;
@group(0) @binding(1) var plane0: texture_2d<f32>;
@group(0) @binding(2) var plane1: texture_2d<f32>;
@group(0) @binding(3) var filtering: sampler;
struct Out { @builtin(position) pos: vec4<f32> };
@vertex fn vs(@builtin(vertex_index) vi: u32) -> Out {
let corner = vec2<f32>(f32(vi & 1u), f32(vi >> 1u));
let p = u.node.xy + corner * u.node.zw;
let local = p - u.viewport.zw;
return Out(vec4<f32>(local.x / u.viewport.x * 2.0 - 1.0, 1.0 - local.y / u.viewport.y * 2.0, 0.0, 1.0));
}
fn linear(v: vec3<f32>) -> vec3<f32> {
let x = clamp(v, vec3<f32>(0.0), vec3<f32>(1.0));
if u.color.z > 1.5 { return x; }
if u.color.z < 0.5 { return select(pow((x + 0.055) / 1.055, vec3<f32>(2.4)), x / 12.92, x <= vec3<f32>(0.04045)); }
return select(pow((x + 0.099) / 1.099, vec3<f32>(1.0 / 0.45)), x / 4.5, x < vec3<f32>(0.081));
}
fn convert(a: vec4<f32>, uv: vec2<f32>) -> vec4<f32> {
if u.color.x < 0.5 { return vec4<f32>(linear(a.rgb) * a.a, a.a); }
var y = a.r;
var c = uv - vec2<f32>(128.0 / 255.0);
if u.color.x < 1.5 { y = (y - 16.0 / 255.0) * (255.0 / 219.0); c *= 255.0 / 224.0; }
var kr = 0.299; var kb = 0.114;
if u.color.y > 0.5 { kr = 0.2126; kb = 0.0722; }
let r = y + 2.0 * (1.0 - kr) * c.y;
let b = y + 2.0 * (1.0 - kb) * c.x;
let g = (y - kr * r - kb * b) / (1.0 - kr - kb);
return vec4<f32>(linear(vec3<f32>(r,g,b)), 1.0);
}
fn sample_linear(uv: vec2<f32>) -> vec4<f32> {
return convert(textureSampleLevel(plane0, filtering, uv, 0.0), textureSampleLevel(plane1, filtering, uv, 0.0).rg);
}
// Apple's continuous corner (crates/rune/src/shaders/clip.wgsl `sd_continuous` / `sd_rounded`).
const CONTINUOUS_K: f32 = 1.52866483;
fn sd_continuous(p: vec2<f32>, half: vec2<f32>, r: f32) -> f32 {
let e = CONTINUOUS_K * r;
let q = half - abs(p);
let v = vec2<f32>(e) - q;
if (v.x <= 0.0 || v.y <= 0.0) { return max(-q.x, -q.y); }
let u = atan2(v.y, v.x) * (4.0 / 3.14159265) - 1.0;
let u2 = u * u;
return length(v) - e * (1.14602295 + u2 * (-0.37573161 + u2 * (0.30796609 - 0.07724354 * u2)));
}
fn sd_rounded(p: vec2<f32>, half: vec2<f32>, radii: vec4<f32>) -> f32 {
var r = radii.x;
if (p.x > 0.0) {
r = select(radii.y, radii.z, p.y > 0.0);
} else {
r = select(radii.x, radii.w, p.y > 0.0);
}
if (r < 0.0) { return sd_continuous(p, half, min(-r, min(half.x, half.y))); }
r = min(r, min(half.x, half.y));
let q = abs(p) - half + vec2<f32>(r);
return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - r;
}
fn unpack_clip_radii(w: u32) -> vec4<f32> {
if (w == 0u) { return vec4<f32>(0.0); }
if ((w & 0x60000000u) != 0x60000000u) {
return vec4<f32>(bitcast<f32>(w));
}
let step = select(0.5, 2.0, (w & 0x10000000u) != 0u);
let sgn = select(1.0, -1.0, (w & 0x80000000u) != 0u);
return vec4<f32>(
f32(w & 0x7fu),
f32((w >> 7u) & 0x7fu),
f32((w >> 14u) & 0x7fu),
f32((w >> 21u) & 0x7fu),
) * (step * sgn);
}
fn ramp(d: f32, width: f32) -> f32 {
if width == 0.0 { return clamp(d + 0.5, 0.0, 1.0); }
let x = clamp(d / abs(width), 0.0, 1.0);
if width < 0.0 { return x; }
return x*x*(3.0-2.0*x);
}
@fragment fn fs(i: Out) -> @location(0) vec4<f32> {
let p = i.pos.xy + u.viewport.zw;
var local = p - u.image.xy;
let unflipped = local / u.image.zw;
if any(unflipped < vec2<f32>(0.0)) || any(unflipped >= vec2<f32>(1.0)) { discard; }
// Mirror about the image centre: Fill crops stay centred and 1:1 texels stay exact.
if u.sampling.w > 0.5 { local.x = u.image.z - local.x; }
// Quarter turns and flips about the centre, into the buffer's (unrotated) image space.
let m = mat2x2<f32>(u.orient.xz, u.orient.yw);
let size = abs(u.orient.xz) * u.image.z + abs(u.orient.yw) * u.image.w;
let buffer = m * (local - u.image.zw * 0.5) + size * 0.5;
let uv = buffer / size;
var col: vec4<f32>;
if u.sampling.x > 0.5 {
// Integer device-pixel origin + pixel-centre positions: no interpolation, even at Retina 2x.
let texel = vec2<i32>(floor(buffer));
col = convert(textureLoad(plane0, texel, 0), textureLoad(plane1, texel / 2, 0).rg);
} else {
let ratio = u.sampling.yz / size;
// Bounded area supersampling for large shrink ratios (up to 8x8 bilinear taps).
// Convert each sample before accumulating so filtering is in linear light.
let taps = vec2<i32>(clamp(ceil(ratio), vec2<f32>(1.0), vec2<f32>(8.0)));
col = vec4<f32>(0.0);
for (var y = 0; y < taps.y; y++) { for (var x = 0; x < taps.x; x++) {
let offset = (vec2<f32>(f32(x)+0.5, f32(y)+0.5) / vec2<f32>(taps) - 0.5) / size;
col += sample_linear(uv + offset);
}}
col /= f32(taps.x * taps.y);
}
let half = u.node.zw*0.5;
let distance = sd_rounded(p-u.node.xy-half, half, u.radii);
let hard = vec4<f32>(p - u.clip.xy, u.clip.zw - p);
let fade = vec4<f32>(unpack2x16float(u.fade.x), unpack2x16float(u.fade.y));
var clip = 1.0;
if u.fade.z == 0u {
clip = ramp(hard.x, fade.x) * ramp(hard.y, fade.y) * ramp(hard.z, fade.z) * ramp(hard.w, fade.w);
} else {
for (var edge = 0u; edge < 4u; edge++) {
let raw_off = (u.fade.z >> (edge * 8u)) & 0xFFu;
let is_stops = (raw_off & 0x80u) != 0u;
let off_u = raw_off & 0x7Fu;
// Native surfaces carry no frame-globals stop table; degrade stop-tagged edges to a
// linear ramp while preserving exact 7-bit offset and hard-edge (`off_u >= 127`) semantics.
let fw = select(fade[edge], -abs(fade[edge]), is_stops);
var a: f32;
if off_u >= 127u {
a = ramp(hard[edge], 0.0);
} else if off_u > 0u {
let offset = f32(off_u) * (1.0 / 127.0);
a = min(ramp(hard[edge], 0.0), ramp(hard[edge] + offset * abs(fw), fw));
} else {
a = ramp(hard[edge], fw);
}
clip *= a;
}
}
var mask = 1.0;
if u.fade.w != 0u {
let h = (u.clip.zw-u.clip.xy)*0.5;
mask = clamp(0.5 - sd_rounded(p-u.clip.xy-h, h, unpack_clip_radii(u.fade.w)), 0.0, 1.0);
}
return col * (clamp(0.5-distance,0.0,1.0)*clip*mask*u.color.w);
}
@@ -0,0 +1,304 @@
//! D3D shared textures from another process or API, read on Rune's D3D12 device.
//!
//! The producer renders BGRA8 frames into textures it shares by name (a D3D11 texture made with
//! `D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_NTHANDLE`, then
//! `IDXGIResource1::CreateSharedHandle`, or a D3D12 one with `CreateSharedHandle`), on the adapter
//! from [`adapter_luid`]. Rune copies a pushed frame into a texture of its own the first time it
//! draws it, so the shared texture is read once, in one short submission. When the frame names a
//! release fence, Rune signals it to the frame's value on its GPU queue after that copy; the
//! producer may write the texture again once the fence reaches the value. A frame replaced before
//! it was drawn is never read and signals nothing: the next frame's higher value covers it.
#![allow(unsafe_code)]
use super::*;
use ::windows::Win32::Foundation::{CloseHandle, GENERIC_ALL, HANDLE};
use ::windows::Win32::Graphics::Direct3D12::{D3D12_RESOURCE_DIMENSION_TEXTURE2D, ID3D12Device, ID3D12Fence, ID3D12Resource};
use ::windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
use ::windows::core::{HSTRING, Interface};
use std::sync::atomic::{AtomicU64, Ordering};
use wgpu::hal::api::Dx12;
/// How many opened textures and fences an importer keeps: a producer usually cycles a few
/// textures per stream, and one fence.
const OPENED: usize = 16;
/// A frame in a named D3D shared texture, BGRA8 (`DXGI_FORMAT_B8G8R8A8_UNORM`), complete before
/// it is pushed. Build one with [`named`](Self::named).
#[derive(Clone, Debug)]
pub struct SharedTexture {
name: String,
size: [u32; 2],
release: Option<(String, u64)>,
}
impl SharedTexture {
/// The texture shared under `name`, `width` × `height` pixels.
///
/// ```
/// use rune_media::native_surface::windows::SharedTexture;
/// let frame = SharedTexture::named("my-app-frame-0", 1280, 720).release_fence("my-app-read", 42);
/// # let _ = frame;
/// // surface.push_shared(frame, 42)?;
/// ```
pub fn named(name: impl Into<String>, width: u32, height: u32) -> Self {
Self { name: name.into(), size: [width, height], release: None }
}
/// Signal the fence shared under `name` (`ID3D11Fence` or `ID3D12Fence`, made with a shared
/// flag and shared by name) to `value` once Rune has read the texture. Values must grow from
/// frame to frame.
pub fn release_fence(mut self, name: impl Into<String>, value: u64) -> Self {
self.release = Some((name.into(), value));
self
}
pub(crate) fn size(&self) -> [u32; 2] {
self.size
}
}
/// One NV12 picture Rune's video decoder (`video::windows`) wrote into a shared texture it opened
/// on Rune's D3D12 device. Rune samples its two planes in place (`with_plane_slice`): no copy.
pub(crate) struct DecodedPlanes {
pub(crate) resource: ID3D12Resource,
pub(crate) size: [u32; 2],
pub(crate) fences: Arc<VideoFences>,
/// The raw `ID3D12Device` the resource and fences were opened on.
pub(crate) device: usize,
}
/// A decoder's two fences on Rune's D3D12 device: it signals `ready` once a picture is written;
/// Rune waits on it before drawing the picture and signals `release` with the same value after
/// the submission that drew it, when the decoder may write that texture again.
pub(crate) struct VideoFences {
pub(crate) ready: ID3D12Fence,
pub(crate) release: ID3D12Fence,
}
/// The D3D12 device of the last window Rune made with D3D12, which video decoders open their
/// textures on.
static DEVICE: Mutex<Option<ID3D12Device>> = Mutex::new(None);
pub(crate) fn presenting_device() -> Option<ID3D12Device> {
DEVICE.lock().unwrap().clone()
}
/// Forgets the last window's device once it is removed. Decoders opening a clip then wait for
/// the next one (`presenting_device` is None until a window notes it).
pub(crate) fn release_removed_device() {
let mut device = DEVICE.lock().unwrap();
// SAFETY: a plain query on a device this slot holds.
if device.as_ref().is_some_and(|d| unsafe { d.GetDeviceRemovedReason() }.is_err()) {
*device = None;
}
}
/// Counts the windows' D3D12 devices Rune made: it moves when one replaces a lost one, so what
/// was opened on the old device (a decoder's textures and fences) is opened again.
static GENERATION: AtomicU64 = AtomicU64::new(0);
pub(crate) fn device_generation() -> u64 {
GENERATION.load(Ordering::Acquire)
}
static ADAPTER_LUID: AtomicU64 = AtomicU64::new(0);
/// The LUID (`HighPart`, `LowPart`) of the adapter Rune last made a window's device on, once it
/// has made one with D3D12: a producer of shared textures renders on it so Rune can open them.
/// Chromium takes it as `--use-adapter-luid=HIGH,LOW`.
pub fn adapter_luid() -> Option<(i32, u32)> {
let luid = ADAPTER_LUID.load(Ordering::Relaxed);
(luid != 0).then_some(((luid >> 32) as i32, luid as u32))
}
/// Remembers `device`'s adapter for [`adapter_luid`]; nothing off D3D12.
pub(crate) fn note_adapter(device: &wgpu::Device) {
// SAFETY: the raw device is only asked for its LUID.
let Some(hal) = (unsafe { device.as_hal::<Dx12>() }) else { return };
// SAFETY: a plain query on the live device.
let luid = unsafe { hal.raw_device().GetAdapterLuid() };
ADAPTER_LUID.store((u64::from(luid.HighPart as u32) << 32) | u64::from(luid.LowPart), Ordering::Relaxed);
*DEVICE.lock().unwrap() = Some(hal.raw_device().clone());
GENERATION.fetch_add(1, Ordering::AcqRel);
}
pub(crate) struct Importer {
device: wgpu::Device,
textures: Vec<(String, ID3D12Resource)>,
fences: Vec<(String, ID3D12Fence)>,
/// Decoded pictures' plane wrappers, by resource: a decoder cycles a few textures. Each goes
/// once its decoder and every picture in it are gone.
planes: Vec<(usize, std::sync::Weak<DecodedPlanes>, [wgpu::Texture; 2])>,
}
impl Importer {
pub fn new(device: &wgpu::Device) -> Result<Self, String> {
// SAFETY: only checks the backend.
if unsafe { device.as_hal::<Dx12>() }.is_none() {
return Err("shared textures need wgpu's D3D12 backend".into());
}
Ok(Self { device: device.clone(), textures: Vec::new(), fences: Vec::new(), planes: Vec::new() })
}
/// The two planes of a decoded picture as R8 and RG8 textures over its own resource, once the
/// decoder's write of `value` is done on the GPU. The wrappers start and stay in the shader
/// resource state as far as wgpu knows: a shared resource leaves every submission in COMMON
/// and is promoted to a read state implicitly, so wgpu never transitions it.
pub fn import_decoded(&mut self, queue: &wgpu::Queue, planes: &Arc<DecodedPlanes>, value: u64) -> Result<[wgpu::Texture; 2], String> {
// SAFETY: only the raw device is compared.
let hal = unsafe { self.device.as_hal::<Dx12>() }.ok_or("decoded video needs wgpu's D3D12 backend")?;
if hal.raw_device().as_raw() as usize != planes.device {
return Err("the video was decoded for another GPU device".into());
}
drop(hal);
let key = planes.resource.as_raw() as usize;
let textures = match self.planes.iter().find(|(k, live, _)| *k == key && live.strong_count() > 0) {
Some((_, _, textures)) => textures.clone(),
None => {
let [w, h] = planes.size;
let wrap = |format, width, height, plane| {
let desc = pipeline::descriptor(width, height, format);
// SAFETY: the resource is a 2D, single-mip NV12 texture of `planes.size` on this
// device; plane 0 is `w`x`h` R8, plane 1 is half that in RG8.
let hal = unsafe {
wgpu::hal::dx12::Device::texture_from_raw(planes.resource.clone(), format, desc.dimension, desc.size, 1, 1)
}
.with_plane_slice(plane);
// SAFETY: as above; it is only ever sampled.
unsafe { self.device.create_texture_from_hal::<Dx12>(hal, &desc, wgpu::TextureUses::RESOURCE) }
};
let textures = [wrap(wgpu::TextureFormat::R8Unorm, w, h, 0), wrap(wgpu::TextureFormat::Rg8Unorm, w / 2, h / 2, 1)];
self.forget_gone();
self.planes.push((key, Arc::downgrade(planes), textures.clone()));
textures
}
};
// SAFETY: the raw queue only gets a wait, ordered before the work that samples the planes.
let raw = unsafe { queue.as_hal::<Dx12>() }.ok_or("decoded video needs wgpu's D3D12 backend")?;
// SAFETY: as above; the fence is live and opened on this device.
unsafe { raw.as_raw().Wait(&planes.fences.ready, value) }.map_err(|e| format!("wait for the decoder: {e}"))?;
Ok(textures)
}
/// Copies `frame` into a texture of Rune's own, then signals its release fence.
pub fn import(&mut self, queue: &wgpu::Queue, frame: &SharedTexture) -> Result<[wgpu::Texture; 2], String> {
let fence = match &frame.release {
Some((name, value)) => Some((self.fence(name)?, *value)),
None => None,
};
let copied = self.copy(queue, frame);
if let Some((fence, value)) = fence {
// After the copy's submission (or at once if it failed), so the producer never waits
// on a frame Rune gave up on.
// SAFETY: the raw queue only gets a signal, ordered after work wgpu already submitted.
let hal = unsafe { queue.as_hal::<Dx12>() }.ok_or("shared textures need wgpu's D3D12 backend")?;
// SAFETY: as above; `fence` is a live shared fence opened on this device.
unsafe { hal.as_raw().Signal(&fence, value) }.map_err(|e| format!("signal release fence: {e}"))?;
}
copied
}
/// Lets go of plane wrappers whose decoder and pictures are all gone, so their textures go too.
pub fn forget_gone(&mut self) {
self.planes.retain(|(_, live, _)| live.strong_count() > 0);
}
fn copy(&mut self, queue: &wgpu::Queue, frame: &SharedTexture) -> Result<[wgpu::Texture; 2], String> {
let [width, height] = frame.size;
let resource = self.texture(&frame.name, width, height)?;
let mut desc = pipeline::descriptor(width, height, wgpu::TextureFormat::Bgra8Unorm);
desc.usage = wgpu::TextureUsages::COPY_SRC;
// SAFETY: `resource` was opened on this device and checked to be a 2D, single-mip,
// single-sample BGRA8 texture of `desc`'s size.
let hal = unsafe {
wgpu::hal::dx12::Device::texture_from_raw(
resource,
desc.format,
desc.dimension,
desc.size,
desc.mip_level_count,
desc.sample_count,
)
};
// A shared resource enters and leaves each submission in COMMON, which wgpu's D3D12
// backend calls PRESENT.
// SAFETY: the resource was checked against `desc` above and belongs to this device.
let source = unsafe { self.device.create_texture_from_hal::<Dx12>(hal, &desc, wgpu::TextureUses::PRESENT) };
let mut desc = pipeline::descriptor(width, height, wgpu::TextureFormat::Bgra8Unorm);
desc.usage |= wgpu::TextureUsages::COPY_DST;
let owned = self.device.create_texture(&desc);
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("shared texture copy") });
encoder.copy_texture_to_texture(source.as_image_copy(), owned.as_image_copy(), desc.size);
encoder.transition_resources(
std::iter::empty(),
std::iter::once(wgpu::TextureTransition { texture: &source, selector: None, state: wgpu::TextureUses::PRESENT }),
);
queue.submit([encoder.finish()]);
Ok([owned.clone(), owned])
}
fn texture(&mut self, name: &str, width: u32, height: u32) -> Result<ID3D12Resource, String> {
if let Some((_, resource)) = self.textures.iter().find(|(n, _)| n == name) {
return Ok(resource.clone());
}
let resource: ID3D12Resource = self.open(name)?;
// SAFETY: a plain query on a live resource.
let desc = unsafe { resource.GetDesc() };
if desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D
|| desc.Width != u64::from(width)
|| desc.Height != height
|| desc.DepthOrArraySize != 1
|| desc.MipLevels != 1
|| desc.SampleDesc.Count != 1
|| desc.Format != DXGI_FORMAT_B8G8R8A8_UNORM
{
return Err(format!("shared texture {name:?} isn't a {width}x{height} BGRA8 texture"));
}
remember(&mut self.textures, name, resource.clone());
Ok(resource)
}
fn fence(&mut self, name: &str) -> Result<ID3D12Fence, String> {
if let Some((_, fence)) = self.fences.iter().find(|(n, _)| n == name) {
return Ok(fence.clone());
}
let fence: ID3D12Fence = self.open(name)?;
remember(&mut self.fences, name, fence.clone());
Ok(fence)
}
fn open<T: Interface>(&self, name: &str) -> Result<T, String> {
// SAFETY: only the raw device is borrowed, for the calls below.
let hal = unsafe { self.device.as_hal::<Dx12>() }.ok_or("shared textures need wgpu's D3D12 backend")?;
let device: &ID3D12Device = hal.raw_device();
// SAFETY: opens a named shared object; the handle is closed once the object holds its
// own reference.
let handle: HANDLE = unsafe { device.OpenSharedHandleByName(&HSTRING::from(name), GENERIC_ALL.0) }
.map_err(|e| format!("open shared {name:?}: {e}"))?;
let mut object: Option<T> = None;
// SAFETY: `handle` is the live handle opened above; `object` receives a new reference.
let opened = unsafe { device.OpenSharedHandle(handle, &mut object) };
// SAFETY: `handle` is ours and closed once; the opened object keeps the resource alive.
unsafe { CloseHandle(handle) }.ok();
opened.map_err(|e| format!("open shared {name:?}: {e}"))?;
object.ok_or_else(|| format!("open shared {name:?}: no object"))
}
}
/// After the submission that drew a decoded picture: the decoder may write its texture again.
pub(crate) fn release_decoded(queue: &wgpu::Queue, planes: &DecodedPlanes, value: u64) {
// SAFETY: the raw queue only gets a signal, ordered after work wgpu already submitted.
if let Some(raw) = unsafe { queue.as_hal::<Dx12>() } {
// SAFETY: as above; the fence is live and belongs to this device.
unsafe { raw.as_raw().Signal(&planes.fences.release, value) }.ok();
}
}
/// Keeps `value` under `name`, dropping the oldest past [`OPENED`].
fn remember<T>(list: &mut Vec<(String, T)>, name: &str, value: T) {
if list.len() >= OPENED {
list.remove(0);
}
list.push((name.to_owned(), value));
}
@@ -0,0 +1,372 @@
//! The recorder's state machine. Each phase holds exactly what is valid in it (the device
//! session, the fake input and its clock anchor, what an interruption saved), and `step` turns
//! an event into the next phase and the effects for [`Shared`](super::Shared) to carry out.
//! An answer from the device or a permission prompt carries the [`Attempt`] that asked for it,
//! so one for an attempt the phase no longer holds changes nothing.
use super::fake::{self, Input};
use super::meter::{Level, Meter};
use super::{RecorderState, Recording, backend};
use rune_core::machine::{Attempt, Effects, Seq};
use std::path::PathBuf;
/// A recording from a [`FakeMicrophone`](super::FakeMicrophone).
pub(super) struct FakeSession {
input: Input,
path: PathBuf,
meter: Meter,
/// Samples folded into the meter.
metered: u64,
unplug: Option<f64>,
}
pub(super) enum Source {
Device(backend::Session),
Fake(FakeSession),
}
pub(super) enum Phase {
Idle,
/// Checking or asking for microphone access: nothing is open yet.
Asking { attempt: Attempt },
/// The device is opening its input.
Opening { attempt: Attempt, session: backend::Session },
Recording {
attempt: Attempt,
source: Source,
/// (clock, elapsed) when recording last (re)started; set by the first clock reading.
anchor: Option<(f64, f64)>,
},
Paused { attempt: Attempt, source: Source },
/// `stop` is waiting for the device to finish its file. Reads as the phase it left.
Stopping { attempt: Attempt, paused: bool },
/// The input went away; `saved` is what it captured.
Interrupted { attempt: Attempt, reason: String, saved: Recording },
Stopped,
Failed(String),
}
pub(super) struct Control {
pub phase: Phase,
pub seq: Seq,
/// Bumped whenever the public state changes, for the app's waker.
pub generation: u64,
/// Seconds recorded, pauses excluded: held while paused and after stopping.
pub elapsed: f64,
/// Elapsed follows the headless clock of the starting thread, not the wall clock.
pub virtual_clock: bool,
/// The file the current attempt writes.
pub path: PathBuf,
}
pub(super) enum Event {
Start { path: PathBuf, virtual_clock: bool },
/// Microphone access for `attempt`: granted, or why not.
Permission { attempt: Attempt, granted: Result<(), String> },
FakeOpened { attempt: Attempt, opened: Result<FakeSession, String> },
DeviceOpened { attempt: Attempt, opened: Result<backend::Session, String> },
/// The device started capturing.
Began { attempt: Attempt },
/// The device couldn't open.
Failed { attempt: Attempt, error: String },
/// The device went away after `duration` seconds of audio.
Interrupted { attempt: Attempt, reason: String, duration: f64 },
Metered { attempt: Attempt, level: Level },
/// Catch up to the clock: elapsed time, and a fake input's levels and unplugging.
Tick,
Pause,
Resume,
Stop,
/// The device finished its file after `Effect::StopDevice`.
Stopped { attempt: Attempt, result: Result<f64, String> },
Cancel,
}
pub(super) enum Effect {
/// Publish a silent level.
Silence,
Publish(Level),
/// Check (or ask for) microphone access, then answer with `Event::Permission`.
Ask { attempt: Attempt },
/// Open the input: a fake one, answering with `Event::FakeOpened`, or the device,
/// answering with `Event::DeviceOpened` before anything else steps.
Open { attempt: Attempt },
/// Catch this recorder up on every headless frame of the current thread.
FollowHeadless,
PauseDevice,
ResumeDevice,
/// Finish the device's file (blocking), answering with `Event::Stopped`.
StopDevice { attempt: Attempt, session: backend::Session },
/// Stop the device and delete its file.
CancelDevice(backend::Session),
RemoveFile(PathBuf),
/// What `stop` returns.
Reply(Result<Recording, String>),
}
/// Clock sums drift by a few ulps (60 steps of 1/60 s fall just short of 1 s): treat elapsed
/// time this close to a boundary as on it, so frame rate never moves a sample or an unplug.
const CLOCK_SLACK: f64 = 1e-9;
/// Whole samples recorded after `seconds` at `rate`.
pub(super) fn frames_at(seconds: f64, rate: u32) -> u64 {
((seconds + CLOCK_SLACK) * rate as f64).floor().max(0.0) as u64
}
impl FakeSession {
pub(super) fn new(input: Input, path: PathBuf, unplug: Option<f64>) -> Self {
Self { input, path, meter: Meter::default(), metered: 0, unplug }
}
/// When the input goes away, if `elapsed` has reached it.
fn unplugged(&self, elapsed: f64) -> Option<f64> {
self.unplug.filter(|t| elapsed + CLOCK_SLACK >= *t)
}
/// Writes the first `seconds` of the input, stopping where it was unplugged.
pub(super) fn write(self, seconds: f64) -> Result<Recording, String> {
let seconds = self.unplug.map_or(seconds, |t| seconds.min(t));
let frames = frames_at(seconds, self.input.rate);
fake::write_wav(&self.path, &self.input, frames)?;
Ok(Recording { path: self.path, duration: frames as f64 / self.input.rate as f64 })
}
/// Folds the samples up to `elapsed` into the meter, in 10 ms blocks.
fn meter_to(&mut self, elapsed: f64) -> Level {
let rate = self.input.rate;
let target = frames_at(elapsed, rate);
let block = (rate / 100).max(1) as u64;
// Only the last few seconds still show in the meter.
self.metered = self.metered.max(target.saturating_sub(10 * rate as u64) / block * block);
while self.metered + block <= target {
let input = &self.input;
self.meter.push_samples((self.metered..self.metered + block).map(|i| input.sample(i)), rate);
self.metered += block;
}
self.meter.level()
}
}
/// Elapsed follows the clock from `anchor`. A clock behind the anchor (a new runtime on this
/// thread) restarts from here.
pub(super) fn advance(elapsed: &mut f64, anchor: &mut Option<(f64, f64)>, now: Option<f64>) {
let Some(now) = now else { return };
match *anchor {
Some((clock, at)) if clock <= now => *elapsed = at + (now - clock),
_ => *anchor = Some((now, *elapsed)),
}
}
pub(super) const NOT_RECORDING: &str = "not recording";
impl Control {
pub(super) fn new(path: PathBuf) -> Self {
Self { phase: Phase::Idle, seq: Seq::default(), generation: 0, elapsed: 0.0, virtual_clock: false, path }
}
pub(super) fn status(&self) -> RecorderState {
match &self.phase {
Phase::Idle => RecorderState::Idle,
Phase::Asking { .. } | Phase::Opening { .. } => RecorderState::Starting,
Phase::Recording { .. } | Phase::Stopping { paused: false, .. } => RecorderState::Recording,
Phase::Paused { .. } | Phase::Stopping { paused: true, .. } => RecorderState::Paused,
Phase::Interrupted { reason, .. } => RecorderState::Interrupted(reason.clone()),
Phase::Stopped => RecorderState::Stopped,
Phase::Failed(e) => RecorderState::Failed(e.clone()),
}
}
/// Recording or paused from a fake microphone.
pub(super) fn is_fake(&self) -> bool {
matches!(&self.phase, Phase::Recording { source: Source::Fake(_), .. } | Phase::Paused { source: Source::Fake(_), .. })
}
/// The device recording or paused now.
pub(super) fn device(&self) -> Option<&backend::Session> {
match &self.phase {
Phase::Recording { source: Source::Device(s), .. } | Phase::Paused { source: Source::Device(s), .. } => Some(s),
_ => None,
}
}
/// A new runtime on this thread starts its clock at 0: a recording goes on from there.
pub(super) fn restart_clock(&mut self) {
if let Phase::Recording { anchor: anchor @ Some(_), .. } = &mut self.phase {
*anchor = Some((0.0, self.elapsed));
}
}
/// One transition, at clock reading `now` (`None` when this thread's headless clock isn't
/// running).
pub(super) fn step(&mut self, event: Event, now: Option<f64>) -> Effects<Effect> {
let before = self.status();
let effects = self.transition(event, now);
if self.status() != before {
self.generation += 1;
}
effects
}
fn transition(&mut self, event: Event, now: Option<f64>) -> Effects<Effect> {
use Effect::*;
let phase = std::mem::replace(&mut self.phase, Phase::Idle);
let (phase, effects) = match (phase, event) {
(
phase @ (Phase::Asking { .. } | Phase::Opening { .. } | Phase::Recording { .. } | Phase::Paused { .. } | Phase::Stopping { .. }),
Event::Start { .. },
) => (phase, Effects::none()),
(_, Event::Start { path, virtual_clock }) => {
let attempt = self.seq.next();
(self.elapsed, self.path, self.virtual_clock) = (0.0, path, virtual_clock);
(Phase::Asking { attempt }, Effects::two(Silence, Ask { attempt }))
}
(Phase::Asking { attempt }, Event::Permission { attempt: a, granted }) if a == attempt => match granted {
Ok(()) => (Phase::Asking { attempt }, Effects::one(Open { attempt })),
Err(e) => (Phase::Failed(e), Effects::none()),
},
(Phase::Asking { attempt }, Event::FakeOpened { attempt: a, opened }) if a == attempt => match opened {
Ok(fake) => {
let anchor = now.map(|now| (now, 0.0));
let effects = if self.virtual_clock { Effects::one(FollowHeadless) } else { Effects::none() };
(Phase::Recording { attempt, source: Source::Fake(fake), anchor }, effects)
}
Err(e) => (Phase::Failed(e), Effects::none()),
},
(Phase::Asking { attempt }, Event::DeviceOpened { attempt: a, opened }) if a == attempt => match opened {
Ok(session) => (Phase::Opening { attempt, session }, Effects::none()),
Err(e) => (Phase::Failed(e), Effects::none()),
},
// An input opened for an attempt that's gone records for nobody.
(phase, Event::DeviceOpened { opened: Ok(session), .. }) => (phase, Effects::one(CancelDevice(session))),
(Phase::Opening { attempt, session }, Event::Began { attempt: a }) if a == attempt => {
(Phase::Recording { attempt, source: Source::Device(session), anchor: now.map(|now| (now, 0.0)) }, Effects::none())
}
(Phase::Asking { attempt } | Phase::Opening { attempt, .. }, Event::Failed { attempt: a, error }) if a == attempt => {
(Phase::Failed(error), Effects::none())
}
(Phase::Recording { attempt, source, mut anchor }, Event::Interrupted { attempt: a, reason, duration }) if a == attempt => {
advance(&mut self.elapsed, &mut anchor, now);
drop(source);
let saved = Recording { path: self.path.clone(), duration };
(Phase::Interrupted { attempt, reason, saved }, Effects::one(Silence))
}
(Phase::Paused { attempt, .. } | Phase::Stopping { attempt, .. }, Event::Interrupted { attempt: a, reason, duration }) if a == attempt => {
let saved = Recording { path: self.path.clone(), duration };
(Phase::Interrupted { attempt, reason, saved }, Effects::one(Silence))
}
(phase @ Phase::Recording { attempt, source: Source::Device(_), .. }, Event::Metered { attempt: a, level }) if a == attempt => {
(phase, Effects::one(Publish(level)))
}
(Phase::Recording { attempt, source, mut anchor }, Event::Tick) => {
advance(&mut self.elapsed, &mut anchor, now);
self.catch_up(attempt, source, anchor)
}
(Phase::Recording { attempt, source, mut anchor }, Event::Pause) => {
advance(&mut self.elapsed, &mut anchor, now);
match self.catch_up(attempt, source, anchor) {
(Phase::Recording { attempt, source, .. }, mut effects) => {
effects.push(Silence);
if matches!(source, Source::Device(_)) {
effects.push(PauseDevice);
}
(Phase::Paused { attempt, source }, effects)
}
other => other,
}
}
(Phase::Paused { attempt, source }, Event::Resume) => {
let effects = if matches!(source, Source::Device(_)) { Effects::one(ResumeDevice) } else { Effects::none() };
(Phase::Recording { attempt, source, anchor: now.map(|now| (now, self.elapsed)) }, effects)
}
(Phase::Recording { attempt, source, mut anchor }, Event::Stop) => {
advance(&mut self.elapsed, &mut anchor, now);
let (phase, mut effects) = self.catch_up(attempt, source, anchor);
let (phase, more) = self.stop(phase);
effects.extend(more);
(phase, effects)
}
(phase, Event::Stop) => self.stop(phase),
(Phase::Stopping { attempt, .. }, Event::Stopped { attempt: a, result }) if a == attempt => {
let result = result.map(|duration| Recording { path: self.path.clone(), duration });
let phase = match &result {
Ok(_) => Phase::Stopped,
Err(e) => Phase::Failed(e.clone()),
};
(phase, Effects::two(Silence, Reply(result)))
}
// The device went away while it finished: what it saved is the recording.
(Phase::Interrupted { attempt, saved, .. }, Event::Stopped { attempt: a, .. }) if a == attempt => {
(Phase::Stopped, Effects::two(Silence, Reply(Ok(saved))))
}
(Phase::Asking { .. }, Event::Cancel) => (Phase::Idle, Effects::one(Silence)),
(Phase::Opening { session, .. }, Event::Cancel)
| (Phase::Recording { source: Source::Device(session), .. } | Phase::Paused { source: Source::Device(session), .. }, Event::Cancel) => {
(Phase::Idle, Effects::two(Silence, CancelDevice(session)))
}
(Phase::Recording { source: Source::Fake(fake), .. } | Phase::Paused { source: Source::Fake(fake), .. }, Event::Cancel) => {
(Phase::Idle, Effects::two(Silence, RemoveFile(fake.path)))
}
(Phase::Interrupted { saved, .. }, Event::Cancel) => (Phase::Idle, Effects::two(Silence, RemoveFile(saved.path))),
(phase, _) => (phase, Effects::none()),
};
self.phase = phase;
effects
}
/// `stop` from `phase`, already caught up to the clock.
fn stop(&mut self, phase: Phase) -> (Phase, Effects<Effect>) {
use Effect::*;
let (attempt, source, paused) = match phase {
Phase::Recording { attempt, source, .. } => (attempt, source, false),
Phase::Paused { attempt, source } => (attempt, source, true),
Phase::Interrupted { saved, .. } => return (Phase::Stopped, Effects::one(Reply(Ok(saved)))),
Phase::Asking { .. } => return (Phase::Idle, Effects::one(Reply(Err(STOPPED_EARLY.into())))),
Phase::Opening { session, .. } => return (Phase::Idle, Effects::two(CancelDevice(session), Reply(Err(STOPPED_EARLY.into())))),
Phase::Failed(e) => return (Phase::Failed(e.clone()), Effects::one(Reply(Err(e)))),
phase @ (Phase::Idle | Phase::Stopped | Phase::Stopping { .. }) => return (phase, Effects::one(Reply(Err(NOT_RECORDING.into())))),
};
match source {
Source::Fake(fake) => {
let result = fake.write(self.elapsed);
let phase = match &result {
Ok(_) => Phase::Stopped,
Err(e) => Phase::Failed(e.clone()),
};
(phase, Effects::two(Silence, Reply(result)))
}
Source::Device(session) => (Phase::Stopping { attempt, paused }, Effects::one(StopDevice { attempt, session })),
}
}
/// A recording caught up to `self.elapsed`: a fake input meters its samples, or goes away
/// once it reaches its unplug time.
fn catch_up(&mut self, attempt: Attempt, source: Source, anchor: Option<(f64, f64)>) -> (Phase, Effects<Effect>) {
let mut fake = match source {
Source::Fake(fake) => fake,
Source::Device(session) => return (Phase::Recording { attempt, source: Source::Device(session), anchor }, Effects::none()),
};
if let Some(unplug) = fake.unplugged(self.elapsed) {
self.elapsed = unplug;
let phase = match fake.write(unplug) {
Ok(saved) => Phase::Interrupted { attempt, reason: "the microphone went away".into(), saved },
Err(e) => Phase::Failed(e),
};
return (phase, Effects::one(Effect::Silence));
}
let level = fake.meter_to(self.elapsed);
(Phase::Recording { attempt, source: Source::Fake(fake), anchor }, Effects::one(Effect::Publish(level)))
}
}
const STOPPED_EARLY: &str = "stopped before recording started";
#[cfg(test)]
#[path = "control_tests.rs"]
mod tests;
@@ -0,0 +1,126 @@
use super::*;
fn control() -> Control {
Control::new(PathBuf::from("note.m4a"))
}
fn start(c: &mut Control) -> Attempt {
let effects: Vec<_> = c.step(Event::Start { path: PathBuf::from("note.m4a"), virtual_clock: false }, Some(0.0)).into_iter().collect();
match effects.as_slice() {
[Effect::Silence, Effect::Ask { attempt }] => *attempt,
_ => panic!("a start asks for permission"),
}
}
fn is_empty(effects: Effects<Effect>) -> bool {
effects.into_iter().next().is_none()
}
#[test]
fn a_permission_answer_after_cancel_opens_nothing() {
let mut c = control();
let attempt = start(&mut c);
assert_eq!(c.status(), RecorderState::Starting);
c.step(Event::Cancel, None);
assert!(is_empty(c.step(Event::Permission { attempt, granted: Ok(()) }, None)));
assert_eq!(c.status(), RecorderState::Idle);
// A later start's answer is the only one that opens.
let again = start(&mut c);
assert!(is_empty(c.step(Event::Permission { attempt, granted: Ok(()) }, None)));
let opened: Vec<_> = c.step(Event::Permission { attempt: again, granted: Ok(()) }, None).into_iter().collect();
assert!(matches!(opened.as_slice(), [Effect::Open { attempt }] if *attempt == again));
}
#[test]
fn stale_reports_change_nothing() {
let mut c = control();
let stale = start(&mut c);
c.step(Event::Stop, None);
let attempt = start(&mut c);
let generation = c.generation;
for event in [
Event::Failed { attempt: stale, error: "late".into() },
Event::Permission { attempt: stale, granted: Err("late".into()) },
Event::Interrupted { attempt: stale, reason: "late".into(), duration: 1.0 },
Event::Stopped { attempt: stale, result: Ok(1.0) },
// Nothing has opened for this attempt yet, so it can't have begun.
Event::Began { attempt },
] {
assert!(is_empty(c.step(event, Some(1.0))));
}
assert!(matches!(c.phase, Phase::Asking { attempt: a } if a == attempt));
assert_eq!(c.generation, generation, "the app's waker hears nothing");
}
#[test]
fn a_start_while_starting_changes_nothing() {
let mut c = control();
let attempt = start(&mut c);
assert!(is_empty(c.step(Event::Start { path: PathBuf::from("other.m4a"), virtual_clock: true }, None)));
assert!(matches!(c.phase, Phase::Asking { attempt: a } if a == attempt));
assert_eq!((c.path.as_path(), c.virtual_clock), (std::path::Path::new("note.m4a"), false));
}
#[test]
fn an_interruption_while_the_device_finishes_returns_what_it_saved() {
let mut c = control();
let attempt = c.seq.next();
c.phase = Phase::Stopping { attempt, paused: false };
assert_eq!(c.status(), RecorderState::Recording);
c.step(Event::Interrupted { attempt, reason: "the input device changed".into(), duration: 2.0 }, None);
assert_eq!(c.status(), RecorderState::Interrupted("the input device changed".into()));
let reply: Vec<_> = c.step(Event::Stopped { attempt, result: Err("the recording already ended".into()) }, None).into_iter().collect();
assert!(matches!(reply.as_slice(), [Effect::Silence, Effect::Reply(Ok(r))] if r.duration == 2.0));
assert_eq!(c.status(), RecorderState::Stopped);
}
#[test]
fn stopping_reads_as_the_phase_it_left() {
let mut c = control();
let attempt = c.seq.next();
c.phase = Phase::Stopping { attempt, paused: true };
assert_eq!(c.status(), RecorderState::Paused);
assert!(matches!(c.step(Event::Stop, None).into_iter().next(), Some(Effect::Reply(Err(_)))));
assert!(is_empty(c.step(Event::Cancel, None)));
assert!(is_empty(c.step(Event::Start { path: PathBuf::from("note.m4a"), virtual_clock: false }, None)));
assert_eq!(c.status(), RecorderState::Paused);
}
/// An input that opens for an attempt that's gone is cancelled rather than left recording.
#[cfg(target_os = "macos")]
#[test]
fn an_input_opened_for_a_gone_attempt_is_cancelled() {
let mut c = control();
let attempt = start(&mut c);
c.step(Event::Cancel, None);
let (session, _commands) = backend::idle_session();
let effects: Vec<_> = c.step(Event::DeviceOpened { attempt, opened: Ok(session) }, None).into_iter().collect();
assert!(matches!(effects.as_slice(), [Effect::CancelDevice(_)]));
assert_eq!(c.status(), RecorderState::Idle);
}
#[cfg(target_os = "macos")]
#[test]
fn a_device_recording_pauses_resumes_and_hands_its_session_to_stop() {
let mut c = control();
let attempt = start(&mut c);
c.step(Event::Permission { attempt, granted: Ok(()) }, Some(0.0));
let (session, _commands) = backend::idle_session();
c.step(Event::DeviceOpened { attempt, opened: Ok(session) }, Some(0.0));
assert_eq!(c.status(), RecorderState::Starting);
c.step(Event::Began { attempt }, Some(1.0));
c.step(Event::Tick, Some(3.0));
assert_eq!((c.status(), c.elapsed), (RecorderState::Recording, 2.0));
let paused: Vec<_> = c.step(Event::Pause, Some(4.0)).into_iter().collect();
assert!(matches!(paused.as_slice(), [Effect::Silence, Effect::PauseDevice]));
c.step(Event::Tick, Some(10.0));
assert_eq!(c.elapsed, 3.0, "held while paused");
let resumed: Vec<_> = c.step(Event::Resume, Some(10.0)).into_iter().collect();
assert!(matches!(resumed.as_slice(), [Effect::ResumeDevice]));
let stop: Vec<_> = c.step(Event::Stop, Some(11.0)).into_iter().collect();
assert!(matches!(stop.as_slice(), [Effect::StopDevice { attempt: a, .. }] if *a == attempt));
assert_eq!((c.status(), c.elapsed), (RecorderState::Recording, 4.0));
c.step(Event::Stopped { attempt, result: Ok(4.0) }, Some(11.5));
assert_eq!(c.status(), RecorderState::Stopped);
}
+240
View File
@@ -0,0 +1,240 @@
//! The fake microphone headless runs record from, and the WAV files it reads and writes.
use super::MicPermission;
use std::io::{BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The default fake input's sample rate.
const RATE: u32 = 48_000;
/// A microphone for headless runs and tests: recorders started where no window has run (and
/// any recorder given one with [`Recorder::fake`](super::Recorder::fake)) record from it
/// instead of a device. It never opens a device, never asks for permission and never makes a
/// sound. Elapsed time follows the virtual clock, levels come from its samples, and `stop`
/// writes them to a 16-bit mono WAV that [`Player::audio`](crate::Player::audio) can open.
///
/// Its input loops when the recording outlasts it. With none installed, headless recorders
/// hear [`FakeMicrophone::default`]: a 220 Hz tone that swells and fades every 1.6 s, so a
/// meter in `--frames` output moves.
///
/// ```
/// use rune_media::{FakeMicrophone, MicPermission};
/// // Recorders started on this thread now hear a -6 dBFS 1 kHz sine.
/// FakeMicrophone::sine(1000.0, 0.5).install();
/// // Or test the denied path.
/// FakeMicrophone::silence().permission(MicPermission::Denied).install();
/// ```
#[derive(Clone, Debug)]
pub struct FakeMicrophone {
signal: Signal,
pub(super) permission: MicPermission,
pub(super) answer: MicPermission,
pub(super) unplug: Option<f64>,
}
#[derive(Clone, Debug)]
enum Signal {
Swell,
Silence,
Sine { hz: f32, amplitude: f32 },
Samples { rate: u32, samples: Arc<[f32]> },
Wav(PathBuf),
}
impl Default for FakeMicrophone {
/// A 220 Hz tone whose amplitude swells from silence to 0.3 and back every 1.6 s.
fn default() -> Self {
Self::with(Signal::Swell)
}
}
thread_local! {
static INSTALLED: std::cell::RefCell<Option<FakeMicrophone>> = const { std::cell::RefCell::new(None) };
}
impl FakeMicrophone {
fn with(signal: Signal) -> Self {
Self { signal, permission: MicPermission::Granted, answer: MicPermission::Granted, unplug: None }
}
/// Digital silence.
pub fn silence() -> Self {
Self::with(Signal::Silence)
}
/// A steady sine at `hz` with peak `amplitude` (1 is full scale), sampled at 48 kHz.
pub fn sine(hz: f32, amplitude: f32) -> Self {
Self::with(Signal::Sine { hz, amplitude })
}
/// Mono samples at `rate` Hz (-1 to 1).
pub fn samples(rate: u32, samples: impl Into<Vec<f32>>) -> Self {
Self::with(Signal::Samples { rate: rate.max(1), samples: samples.into().into() })
}
/// A WAV file (8, 16, 24 or 32-bit PCM, or 32-bit float), mixed to mono, read when a
/// recording starts. A file that can't be read fails the recording with the reason.
pub fn wav(path: impl Into<PathBuf>) -> Self {
Self::with(Signal::Wav(path.into()))
}
/// What [`Recorder::permission`](super::Recorder::permission) reports (default
/// `Granted`). Starting with `Denied` or `Restricted` fails as a real microphone would.
pub fn permission(mut self, permission: MicPermission) -> Self {
self.permission = permission;
self
}
/// How a permission request resolves while the permission is `Undetermined` (default
/// `Granted`). Like the system's answer, it sticks.
pub fn answers(mut self, answer: MicPermission) -> Self {
self.answer = answer;
self
}
/// The microphone goes away after `seconds` of recording, as when a headset is unplugged:
/// the recorder keeps what it captured and reports
/// [`RecorderState::Interrupted`](super::RecorderState::Interrupted).
pub fn unplug_after(mut self, seconds: f64) -> Self {
self.unplug = Some(seconds.max(0.0));
self
}
/// Recorders started on this thread while no window has run hear this microphone.
pub fn install(self) {
INSTALLED.with_borrow_mut(|m| *m = Some(self));
}
/// Back to [`FakeMicrophone::default`] on this thread.
pub fn uninstall() {
INSTALLED.with_borrow_mut(|m| *m = None);
}
pub(super) fn installed() -> Self {
INSTALLED.with_borrow(|m| m.clone()).unwrap_or_default()
}
/// Answers a permission request on the installed microphone, which remembers the answer.
pub(super) fn request_installed() -> MicPermission {
INSTALLED.with_borrow_mut(|m| m.get_or_insert_with(Self::default).resolve())
}
pub(super) fn resolve(&mut self) -> MicPermission {
if self.permission == MicPermission::Undetermined {
self.permission = self.answer;
}
self.permission
}
/// The samples to record from, read once per recording.
pub(super) fn open(&self) -> Result<Input, String> {
Ok(match &self.signal {
Signal::Swell => Input { rate: RATE, kind: Kind::Swell },
Signal::Silence => Input { rate: RATE, kind: Kind::Silence },
Signal::Sine { hz, amplitude } => Input { rate: RATE, kind: Kind::Sine { hz: *hz as f64, amplitude: *amplitude as f64 } },
Signal::Samples { rate, samples } => Input { rate: *rate, kind: Kind::Samples(samples.clone()) },
Signal::Wav(path) => {
let (rate, samples) = read_wav(path)?;
Input { rate, kind: Kind::Samples(samples.into()) }
}
})
}
}
pub(super) struct Input {
pub rate: u32,
kind: Kind,
}
enum Kind {
Swell,
Silence,
Sine { hz: f64, amplitude: f64 },
Samples(Arc<[f32]>),
}
impl Input {
/// Sample `i`, looping a finite input.
pub fn sample(&self, i: u64) -> f32 {
let t = i as f64 / self.rate as f64;
let tau = std::f64::consts::TAU;
match &self.kind {
Kind::Silence => 0.0,
Kind::Sine { hz, amplitude } => (amplitude * (tau * hz * t).sin()) as f32,
Kind::Swell => (0.3 * (0.5 - 0.5 * (tau * t / 1.6).cos()) * (tau * 220.0 * t).sin()) as f32,
Kind::Samples(s) if s.is_empty() => 0.0,
Kind::Samples(s) => s[(i % s.len() as u64) as usize],
}
}
}
/// Writes the first `frames` samples of `input` to a 16-bit mono WAV.
pub(super) fn write_wav(path: &Path, input: &Input, frames: u64) -> Result<(), String> {
let fail = |e: std::io::Error| format!("couldn't write {}: {e}", path.display());
let bytes = frames.checked_mul(2).filter(|b| *b <= u32::MAX as u64 - 36).ok_or_else(|| "the recording is too long for a WAV file".to_string())?;
let mut out = BufWriter::new(std::fs::File::create(path).map_err(fail)?);
out.write_all(&wav_header(input.rate, bytes as u32)).map_err(fail)?;
for i in 0..frames {
let s = (input.sample(i).clamp(-1.0, 1.0) * 32767.0).round() as i16;
out.write_all(&s.to_le_bytes()).map_err(fail)?;
}
out.flush().map_err(fail)
}
fn wav_header(rate: u32, data: u32) -> [u8; 44] {
let mut h = [0u8; 44];
let put = |h: &mut [u8; 44], at: usize, b: &[u8]| h[at..at + b.len()].copy_from_slice(b);
put(&mut h, 0, b"RIFF");
put(&mut h, 4, &(36 + data).to_le_bytes());
put(&mut h, 8, b"WAVEfmt ");
put(&mut h, 16, &16u32.to_le_bytes());
put(&mut h, 20, &1u16.to_le_bytes()); // PCM
put(&mut h, 22, &1u16.to_le_bytes()); // mono
put(&mut h, 24, &rate.to_le_bytes());
put(&mut h, 28, &(rate * 2).to_le_bytes());
put(&mut h, 32, &2u16.to_le_bytes());
put(&mut h, 34, &16u16.to_le_bytes());
put(&mut h, 36, b"data");
put(&mut h, 40, &data.to_le_bytes());
h
}
/// Reads a PCM or float WAV, mixed to mono: (sample rate, samples).
pub(crate) fn read_wav(path: &Path) -> Result<(u32, Vec<f32>), String> {
let mut bytes = Vec::new();
std::fs::File::open(path).and_then(|mut f| f.read_to_end(&mut bytes)).map_err(|e| format!("couldn't read {}: {e}", path.display()))?;
parse_wav(&bytes).map_err(|e| format!("{}: {e}", path.display()))
}
pub(super) fn parse_wav(b: &[u8]) -> Result<(u32, Vec<f32>), &'static str> {
if b.len() < 12 || &b[0..4] != b"RIFF" || &b[8..12] != b"WAVE" {
return Err("not a WAV file");
}
let u16_at = |i: usize| u16::from_le_bytes([b[i], b[i + 1]]);
let u32_at = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
let (mut fmt, mut data) = (None, None);
let mut at = 12;
while at + 8 <= b.len() {
let len = u32_at(at + 4) as usize;
let (start, end) = (at + 8, (at + 8).saturating_add(len).min(b.len()));
match &b[at..at + 4] {
b"fmt " if end - start >= 16 => fmt = Some(start),
b"data" => data = Some(start..end),
_ => {}
}
at = end.saturating_add(len & 1);
}
let (Some(f), Some(data)) = (fmt, data) else { return Err("no fmt or data chunk") };
let mut format = u16_at(f);
if format == 0xFFFE && f + 26 <= b.len() {
format = u16_at(f + 24); // WAVE_FORMAT_EXTENSIBLE: the sub-format's first two bytes.
}
let (channels, rate, bits) = (u16_at(f + 2) as usize, u32_at(f + 4), u16_at(f + 14));
let width = bits as usize / 8;
if channels == 0 || rate == 0 || width == 0 {
return Err("invalid fmt chunk");
}
let sample: fn(&[u8]) -> f32 = match (format, bits) {
(1, 8) => |s| (s[0] as f32 - 128.0) / 128.0,
(1, 16) => |s| i16::from_le_bytes([s[0], s[1]]) as f32 / 32768.0,
(1, 24) => |s| (i32::from_le_bytes([0, s[0], s[1], s[2]]) >> 8) as f32 / 8_388_608.0,
(1, 32) => |s| i32::from_le_bytes([s[0], s[1], s[2], s[3]]) as f32 / 2_147_483_648.0,
(3, 32) => |s| f32::from_le_bytes([s[0], s[1], s[2], s[3]]),
_ => return Err("unsupported WAV sample format (use PCM or 32-bit float)"),
};
let frame = width * channels;
let samples = b[data]
.chunks_exact(frame)
.map(|f| f.chunks_exact(width).map(sample).sum::<f32>() / channels as f32)
.collect();
Ok((rate, samples))
}
+372
View File
@@ -0,0 +1,372 @@
//! AVAudioRecorder on a thread of its own: it encodes AAC (or writes WAV) and meters the
//! input, so Rune never touches samples. The thread creates, drives and releases the recorder;
//! nothing about it needs the main thread. AVCaptureDevice reports and asks for microphone
//! access. CoreAudio's default input device is watched for changes.
#![allow(unsafe_code)]
use super::meter::Meter;
use super::{MicPermission, Options, RecordFormat, Recorder, Shared};
use objc2::rc::{Allocated, Retained, autoreleasepool};
use objc2::runtime::{AnyClass, AnyObject, Bool};
use objc2::{class, msg_send};
use objc2_av_foundation::AVMediaTypeAudio;
use objc2_foundation::{NSDictionary, NSError, NSString, NSURL};
use rune_core::machine::Attempt;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
/// The default input device is checked this many meter ticks apart (about twice a second).
const DEVICE_CHECK_TICKS: u32 = 15;
/// `stop` and `cancel` give up waiting on the recorder thread after this long.
const REPLY_PATIENCE: Duration = Duration::from_secs(5);
// AVAudioSettings keys (AVFAudio, re-exported by AVFoundation).
#[link(name = "AVFoundation", kind = "framework")]
unsafe extern "C" {
static AVFormatIDKey: &'static NSString;
static AVSampleRateKey: &'static NSString;
static AVNumberOfChannelsKey: &'static NSString;
static AVEncoderAudioQualityKey: &'static NSString;
static AVLinearPCMBitDepthKey: &'static NSString;
static AVLinearPCMIsFloatKey: &'static NSString;
static AVLinearPCMIsBigEndianKey: &'static NSString;
static AVLinearPCMIsNonInterleaved: &'static NSString;
}
#[repr(C)]
struct PropertyAddress {
selector: u32,
scope: u32,
element: u32,
}
#[link(name = "CoreAudio", kind = "framework")]
unsafe extern "C" {
fn AudioObjectGetPropertyData(
object: u32,
address: *const PropertyAddress,
qualifier_size: u32,
qualifier: *const std::ffi::c_void,
size: *mut u32,
data: *mut std::ffi::c_void,
) -> i32;
}
/// The system's default input device, if there is one.
fn default_input() -> Option<u32> {
let address = PropertyAddress {
selector: u32::from_be_bytes(*b"dIn "), // kAudioHardwarePropertyDefaultInputDevice
scope: u32::from_be_bytes(*b"glob"),
element: 0,
};
let (mut device, mut size) = (0u32, 4u32);
// kAudioObjectSystemObject is 1.
// SAFETY: `address` is valid, qualifier is null with 0 length, and `size` matches the 4-byte `device` out-buffer.
let status = unsafe { AudioObjectGetPropertyData(1, &address, 0, std::ptr::null(), &mut size, (&raw mut device).cast()) };
(status == 0 && device != 0).then_some(device)
}
pub(super) fn permission() -> MicPermission {
// SAFETY: `AVMediaTypeAudio` is an immutable static AVFoundation string constant.
let (Some(audio), Some(device)) = (unsafe { AVMediaTypeAudio }, AnyClass::get(c"AVCaptureDevice")) else {
return MicPermission::Restricted;
};
// SAFETY: `device` is `AVCaptureDevice` and `+authorizationStatusForMediaType:` takes `AVMediaType` and returns `isize`.
let status: isize = unsafe { msg_send![device, authorizationStatusForMediaType: audio] };
match status {
3 => MicPermission::Granted,
2 => MicPermission::Denied,
1 => MicPermission::Restricted,
_ => MicPermission::Undetermined,
}
}
pub(super) fn request_permission(callback: Box<dyn FnOnce(MicPermission) + Send>) {
if let Err(e) = preflight() {
if cfg!(debug_assertions) {
eprintln!("rune: {e}");
}
return callback(MicPermission::Denied);
}
let current = permission();
// SAFETY: `AVMediaTypeAudio` is an immutable static AVFoundation string constant.
let (Some(audio), Some(device)) = (unsafe { AVMediaTypeAudio }, AnyClass::get(c"AVCaptureDevice")) else {
return callback(current);
};
if current != MicPermission::Undetermined {
return callback(current);
}
let callback = Mutex::new(Some(callback));
let block = block2::RcBlock::new(move |granted: Bool| {
if let Some(callback) = callback.lock().unwrap().take() {
callback(if granted.as_bool() { MicPermission::Granted } else { MicPermission::Denied });
}
});
// SAFETY: `device` is `AVCaptureDevice`, `audio` is `AVMediaTypeAudio`, and `block` matches `void (^)(BOOL)`.
unsafe {
let _: () = msg_send![device, requestAccessForMediaType: audio, completionHandler: &*block];
}
}
/// macOS ends a bundled app that touches the microphone without a usage description; refuse
/// instead. An unbundled binary is attributed to the terminal that ran it.
pub(super) fn preflight() -> Result<(), String> {
// SAFETY: `NSBundle` class and instance selectors match their Foundation Objective-C signatures.
unsafe {
let bundle: Option<Retained<AnyObject>> = msg_send![class!(NSBundle), mainBundle];
let Some(bundle) = bundle else { return Ok(()) };
let path: Option<Retained<NSString>> = msg_send![&*bundle, bundlePath];
if !path.is_some_and(|p| p.to_string().ends_with(".app")) {
return Ok(());
}
let key = NSString::from_str("NSMicrophoneUsageDescription");
let value: Option<Retained<AnyObject>> = msg_send![&*bundle, objectForInfoDictionaryKey: &*key];
match value {
Some(_) => Ok(()),
None => Err("the app's Info.plist has no NSMicrophoneUsageDescription, so macOS won't let it record".into()),
}
}
}
fn number_u32(value: u32) -> Retained<AnyObject> {
// SAFETY: `NSNumber`'s `+numberWithUnsignedInt:` takes a `u32` and returns a retained `NSNumber`.
unsafe { msg_send![class!(NSNumber), numberWithUnsignedInt: value] }
}
fn number_f64(value: f64) -> Retained<AnyObject> {
// SAFETY: `NSNumber`'s `+numberWithDouble:` takes an `f64` and returns a retained `NSNumber`.
unsafe { msg_send![class!(NSNumber), numberWithDouble: value] }
}
fn number_bool(value: bool) -> Retained<AnyObject> {
// SAFETY: `NSNumber`'s `+numberWithBool:` takes an ObjC `BOOL` and returns a retained `NSNumber`.
unsafe { msg_send![class!(NSNumber), numberWithBool: Bool::new(value)] }
}
/// An AVAudioRecorder for `path`, not yet prepared or recording: no file and no capture.
pub(super) fn make_recorder(path: &Path, opts: &Options) -> Result<Retained<AnyObject>, String> {
let class = AnyClass::get(c"AVAudioRecorder").ok_or("the system recorder (AVAudioRecorder) is unavailable")?;
let path = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
let url = NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()));
// SAFETY: `AVSampleRateKey` and `AVNumberOfChannelsKey` are immutable static `NSString` constants exported by AVFoundation.
let mut entries: Vec<(&NSString, Retained<AnyObject>)> = unsafe {
vec![(AVSampleRateKey, number_f64(opts.sample_rate as f64)), (AVNumberOfChannelsKey, number_u32(opts.channels as u32))]
};
// SAFETY: `AVFormatIDKey`, `AVEncoderAudioQualityKey`, and `AVLinearPCM*` are immutable static `NSString` constants exported by AVFoundation.
unsafe {
match opts.format {
RecordFormat::Aac => {
entries.push((AVFormatIDKey, number_u32(u32::from_be_bytes(*b"aac "))));
entries.push((AVEncoderAudioQualityKey, number_u32(0x60))); // AVAudioQualityHigh
}
RecordFormat::Wav => {
entries.push((AVFormatIDKey, number_u32(u32::from_be_bytes(*b"lpcm"))));
entries.push((AVLinearPCMBitDepthKey, number_u32(16)));
entries.push((AVLinearPCMIsFloatKey, number_bool(false)));
entries.push((AVLinearPCMIsBigEndianKey, number_bool(false)));
entries.push((AVLinearPCMIsNonInterleaved, number_bool(false)));
}
}
}
let keys: Vec<&NSString> = entries.iter().map(|(k, _)| *k).collect();
let values: Vec<&AnyObject> = entries.iter().map(|(_, v)| &**v).collect();
let settings = NSDictionary::<NSString, AnyObject>::from_slices(&keys, &values);
// SAFETY: `class` is `AVAudioRecorder`, `url` and `settings` are live Foundation objects, and the initializer matches AVFoundation's signature.
unsafe {
let recorder: Allocated<AnyObject> = msg_send![class, alloc];
let recorder: Result<Retained<AnyObject>, Retained<NSError>> = msg_send![recorder, initWithURL: &*url, settings: &*settings, error: _];
recorder.map_err(|e| format!("couldn't record to {}: {}", path.display(), e.localizedDescription()))
}
}
thread_local! {
static ON_RECORDER_THREAD: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) struct Session {
commands: Sender<Command>,
}
pub(super) enum Command {
Pause,
Resume,
Stop(Sender<Result<f64, String>>),
Cancel(Sender<()>),
}
pub(super) fn start(shared: &Arc<Shared>, attempt: Attempt, path: &Path, opts: &Options) -> Result<Session, String> {
let (commands, rx) = mpsc::channel();
let (weak, path, opts) = (Arc::downgrade(shared), path.to_path_buf(), opts.clone());
std::thread::Builder::new()
.name("rune-recorder".into())
.spawn(move || run(weak, attempt, path, opts, rx))
.map_err(|e| format!("couldn't start the recorder thread: {e}"))?;
Ok(Session { commands })
}
pub(super) fn pause(session: &Session) {
session.commands.send(Command::Pause).ok();
}
pub(super) fn resume(session: &Session) {
session.commands.send(Command::Resume).ok();
}
pub(super) fn stop(session: Session) -> Result<f64, String> {
let (reply, done) = mpsc::channel();
session.commands.send(Command::Stop(reply)).map_err(|_| "the recording already ended".to_string())?;
done.recv_timeout(REPLY_PATIENCE).unwrap_or_else(|_| Err("the recorder didn't stop".into()))
}
/// The last handle dropped: stop and finalize the file (an m4a is unplayable until the
/// recorder writes its index), waiting a bounded time. On the recorder thread itself (the last
/// handle dropped while it reported) waiting would deadlock; dropping the session disconnects
/// it instead, and the thread stops the recorder as soon as its report returns.
pub(super) fn finish(session: Session) {
if !ON_RECORDER_THREAD.try_with(|on| on.get()).unwrap_or(true) {
stop(session).ok();
}
}
#[cfg(test)]
pub(super) fn mark_recorder_thread() {
ON_RECORDER_THREAD.set(true);
}
#[cfg(test)]
pub(super) fn idle_session() -> (Session, Receiver<Command>) {
let (commands, rx) = mpsc::channel();
(Session { commands }, rx)
}
pub(super) fn cancel(session: Session) {
let (reply, done) = mpsc::channel();
if session.commands.send(Command::Cancel(reply)).is_ok() {
done.recv_timeout(REPLY_PATIENCE).ok();
}
}
/// Prepares and starts the recorder: (recorder, the input device it started on).
fn open(path: &Path, opts: &Options) -> Result<(Retained<AnyObject>, Option<u32>), String> {
let device = default_input().ok_or("no microphone is connected")?;
let recorder = make_recorder(path, opts)?;
// SAFETY: `recorder` is a live `AVAudioRecorder`; these selectors match their AVFoundation Objective-C signatures.
unsafe {
let _: () = msg_send![&*recorder, setMeteringEnabled: Bool::YES];
let prepared: Bool = msg_send![&*recorder, prepareToRecord];
if !prepared.as_bool() {
return Err(format!("couldn't create {}", path.display()));
}
let started: Bool = msg_send![&*recorder, record];
if !started.as_bool() {
let _: Bool = msg_send![&*recorder, deleteRecording];
return Err("couldn't start recording from the microphone".into());
}
}
Ok((recorder, Some(device)))
}
fn run(weak: Weak<Shared>, attempt: Attempt, path: PathBuf, opts: Options, commands: Receiver<Command>) {
ON_RECORDER_THREAD.set(true);
let opened = autoreleasepool(|_| open(&path, &opts));
let (recorder, device) = match opened {
Ok(opened) => opened,
Err(e) => {
if let Some(shared) = weak.upgrade() {
shared.failed(attempt, e);
}
return;
}
};
if let Some(shared) = weak.upgrade() {
shared.began(attempt);
}
let recorder = &*recorder;
let current_time = || -> f64 {
// SAFETY: `recorder` is a live `AVAudioRecorder` on this thread and `-currentTime` returns `NSTimeInterval` (`f64`).
unsafe { msg_send![recorder, currentTime] }
};
let stop = || {
// SAFETY: `recorder` is a live `AVAudioRecorder` on this thread and `-stop` takes no arguments and returns void.
unsafe {
let _: () = msg_send![recorder, stop];
}
};
let (mut meter, mut last, mut ticks, mut paused, mut recorded) = (Meter::default(), rune_core::time::now(), 0u32, false, 0f64);
loop {
let command = commands.recv_timeout(Recorder::METER_INTERVAL);
let done = autoreleasepool(|_| match command {
Ok(Command::Pause) => {
recorded = recorded.max(current_time());
// SAFETY: `recorder` is a live `AVAudioRecorder` on this thread and `-pause` takes no arguments and returns void.
unsafe {
let _: () = msg_send![recorder, pause];
}
paused = true;
false
}
Ok(Command::Resume) => {
// SAFETY: `recorder` is a live `AVAudioRecorder` on this thread and `-record` returns `BOOL`.
let _: Bool = unsafe { msg_send![recorder, record] };
(paused, last) = (false, rune_core::time::now());
false
}
Ok(Command::Stop(reply)) => {
// currentTime reads 0 once stopped.
recorded = recorded.max(current_time());
stop();
reply.send(Ok(recorded)).ok();
true
}
Ok(Command::Cancel(reply)) => {
stop();
// SAFETY: `recorder` is a stopped `AVAudioRecorder` on this thread and `-deleteRecording` returns `BOOL`.
let _: Bool = unsafe { msg_send![recorder, deleteRecording] };
reply.send(()).ok();
true
}
Err(RecvTimeoutError::Timeout) if paused => false,
Err(RecvTimeoutError::Timeout) => {
let Some(shared) = weak.upgrade() else {
stop();
return true;
};
// SAFETY: `recorder` is a live `AVAudioRecorder` with metering enabled; channel 0 exists and selectors match AVFoundation.
let (peak, average, recording): (f32, f32, Bool) = unsafe {
let _: () = msg_send![recorder, updateMeters];
(msg_send![recorder, peakPowerForChannel: 0usize], msg_send![recorder, averagePowerForChannel: 0usize], msg_send![recorder, isRecording])
};
recorded = recorded.max(current_time());
let now = rune_core::time::now();
meter.push_db(peak, average, (now - last).as_secs_f64());
last = now;
shared.metered(attempt, meter.level());
ticks += 1;
let lost = if !recording.as_bool() {
Some("recording stopped: the input device went away")
} else if ticks % DEVICE_CHECK_TICKS == 0 && default_input() != device {
Some("the input device changed")
} else {
None
};
match lost {
Some(reason) => {
stop();
shared.interrupted(attempt, reason.into(), recorded);
true
}
None => false,
}
}
// Every handle is gone: keep the file.
Err(RecvTimeoutError::Disconnected) => {
stop();
true
}
});
if done {
break;
}
}
}
+104
View File
@@ -0,0 +1,104 @@
//! Meter ballistics shared by the fake microphone and the macOS backend.
/// The quietest level a meter reports, in dBFS, as AVAudioRecorder does.
pub(crate) const FLOOR_DB: f32 = -160.0;
/// The level `Level::meter` maps to 0.
const METER_FLOOR_DB: f32 = -60.0;
/// RMS rises with this time constant (seconds)...
const ATTACK: f64 = 0.03;
/// ...and falls with this one, so speech reads as a steady bar rather than flicker.
const RELEASE: f64 = 0.3;
/// The peak jumps up at once and falls this many dB a second.
const PEAK_FALL: f64 = 20.0;
/// An input level, smoothed like a meter: the peak jumps up at once and falls at 20 dB/s, and
/// the RMS rises over about 30 ms and falls over about 300 ms. Silence is -160 dBFS.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Level {
peak_db: f32,
rms_db: f32,
}
impl Level {
/// No input.
pub const SILENT: Level = Level { peak_db: FLOOR_DB, rms_db: FLOOR_DB };
pub(crate) fn new(peak_db: f32, rms_db: f32) -> Self {
Self { peak_db: peak_db.clamp(FLOOR_DB, 0.0), rms_db: rms_db.clamp(FLOOR_DB, 0.0) }
}
/// The smoothed peak sample in dBFS (-160 to 0).
pub fn peak_db(&self) -> f32 {
self.peak_db
}
/// The smoothed RMS in dBFS (-160 to 0). A full-scale sine reads about -3.
pub fn rms_db(&self) -> f32 {
self.rms_db
}
/// The RMS for a level bar: -60 dBFS and below is 0, full scale is 1.
pub fn meter(&self) -> f32 {
to_meter(self.rms_db)
}
}
fn to_meter(db: f32) -> f32 {
((db - METER_FLOOR_DB) / -METER_FLOOR_DB).clamp(0.0, 1.0)
}
fn db(amplitude: f64) -> f64 {
if amplitude > 0.0 { (20.0 * amplitude.log10()).max(FLOOR_DB as f64) } else { FLOOR_DB as f64 }
}
/// Smooths raw block measurements into a [`Level`].
#[derive(Clone, Copy, Debug)]
pub(crate) struct Meter {
peak_db: f64,
/// Smoothed mean square.
ms: f64,
}
impl Default for Meter {
fn default() -> Self {
Self { peak_db: FLOOR_DB as f64, ms: 0.0 }
}
}
impl Meter {
/// Folds in one block lasting `dt` seconds: its peak amplitude and mean square.
pub fn push(&mut self, peak: f64, mean_square: f64, dt: f64) {
if !(dt > 0.0) {
return;
}
let mean_square = if mean_square.is_finite() { mean_square.max(0.0) } else { 0.0 };
let tau = if mean_square > self.ms { ATTACK } else { RELEASE };
self.ms += (mean_square - self.ms) * (1.0 - (-dt / tau).exp());
let peak = if peak.is_finite() { db(peak.abs()) } else { FLOOR_DB as f64 };
self.peak_db = peak.max(self.peak_db - PEAK_FALL * dt).max(FLOOR_DB as f64);
}
/// Folds in a block measured in dBFS, as AVAudioRecorder reports it.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub fn push_db(&mut self, peak_db: f32, rms_db: f32, dt: f64) {
let amplitude = |db: f32| if db.is_finite() && db > FLOOR_DB { 10f64.powf(db as f64 / 20.0) } else { 0.0 };
let rms = amplitude(rms_db);
self.push(amplitude(peak_db), rms * rms, dt);
}
/// Folds in a block of samples lasting `samples.len() / rate` seconds.
pub fn push_samples(&mut self, samples: impl Iterator<Item = f32>, rate: u32) {
let (mut peak, mut sum, mut n) = (0f64, 0f64, 0usize);
for s in samples {
let s = if s.is_finite() { s as f64 } else { 0.0 };
peak = peak.max(s.abs());
sum += s * s;
n += 1;
}
if n > 0 {
self.push(peak, sum / n as f64, n as f64 / rate as f64);
}
}
pub fn level(&self) -> Level {
let rms_db = if self.ms > 0.0 { (10.0 * self.ms.log10()).max(FLOOR_DB as f64) } else { FLOOR_DB as f64 };
Level::new(self.peak_db as f32, rms_db as f32)
}
}
+592
View File
@@ -0,0 +1,592 @@
//! Audio recording: a cheap, cloneable [`Recorder`] handle that records the microphone to a
//! file, with elapsed time and a smoothed input level to draw.
//!
//! In a window on macOS, AVAudioRecorder records on its own thread (AAC or WAV, metering built
//! in) and publishes the level 30 times a second while recording. Elsewhere starting fails with
//! a clear state.
//!
//! Headless runs (no window event loop yet, as with `Player`) never open a device: recorders
//! hear a [`FakeMicrophone`], elapsed time follows the virtual clock of the runtime stepping
//! on the thread that started them, levels come from the fake samples in 10 ms blocks (so they
//! don't depend on the frame rate), and `stop` writes a real WAV.
mod control;
mod fake;
mod meter;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "macos")]
use macos as backend;
#[cfg(not(target_os = "macos"))]
mod unsupported;
#[cfg(not(target_os = "macos"))]
use unsupported as backend;
pub use fake::FakeMicrophone;
pub use meter::Level;
use crate::video::{WakerSlot, headless_clock};
use control::{Control, Effect, Event, FakeSession, Phase, Source};
#[cfg(test)]
use meter::Meter;
use rune_core::live::Live;
use rune_core::machine::Attempt;
use rune_core::time::Instant;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError, Weak};
use std::time::Duration;
/// The file format a recorder writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecordFormat {
/// AAC in an MPEG-4 container (`.m4a`), high quality: about 1 MB a minute, mono.
Aac,
/// 16-bit PCM WAV: about 5 MB a minute at 44.1 kHz mono.
Wav,
}
/// Where a recorder is.
///
/// The `Interrupted` and `Failed` messages start lower case and have no final period, so they
/// read after a colon ("Couldn't record: {message}"). Capitalize the first letter to show one
/// on its own. Later versions keep this form.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecorderState {
/// Not started, or cancelled.
Idle,
/// Asking for permission or opening the input.
Starting,
Recording,
Paused,
/// Stopped with the file written.
Stopped,
/// The input went away mid-recording (unplugged, or the default input changed). What was
/// captured is saved; `stop` returns it and `cancel` deletes it.
Interrupted(String),
/// Couldn't record: no permission, no input, an unwritable path, or an unsupported
/// platform. `start` tries again.
Failed(String),
}
/// Microphone access, as the system reports it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MicPermission {
Granted,
/// The user said no; only System Settings can change it.
Denied,
/// Not asked yet: [`Recorder::request_permission`] (or `start`) asks.
Undetermined,
/// The system won't allow recording (device management, parental controls), or this
/// platform can't record.
Restricted,
}
/// A finished recording.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Recording {
/// The file, ready for [`Player::audio`](crate::Player::audio). Its extension follows
/// the format, and a [fake microphone](Recorder::fake) always writes `.wav`, so read the
/// type from this path rather than from the one given to [`Recorder::to_file`].
pub path: PathBuf,
/// Seconds of audio, pauses excluded.
pub duration: f64,
}
/// Records the microphone to a file. Clones share one recorder; dropping the last clone while
/// recording stops it and keeps the file.
///
/// ```ignore
/// let rec = rune::Recorder::to_file("note.m4a"); // AAC; "note.wav" records WAV
/// rec.start();
/// // In a view, a level bar that redraws without re-running the view:
/// let bar = rune::el().w(4.0).h(40.0).live_scale(&rec.live_level());
/// // or read `rec.level().meter()` and `rec.elapsed()` from `poll`.
/// let note = rec.stop()?;
/// let clip = rune::Player::audio(note.path);
/// # Ok::<(), String>(())
/// ```
///
/// macOS asks for microphone access the first time an app records, and ends an app whose
/// Info.plist has no `NSMicrophoneUsageDescription`. Rune checks first: a bundled app without
/// the key fails to start with a clear message instead. An unbundled binary run from a
/// terminal is attributed to the terminal, which asks on its behalf. Hardened-runtime apps
/// also need the `com.apple.security.device.audio-input` entitlement (sandboxed apps
/// `com.apple.security.device.microphone`); an ad-hoc signed dev build may be denied without
/// a prompt.
#[derive(Clone)]
pub struct Recorder {
shared: Arc<Shared>,
}
impl std::fmt::Debug for Recorder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let c = self.shared.ctl.lock().unwrap();
f.debug_struct("Recorder").field("path", &self.shared.path).field("state", &c.status()).field("elapsed", &c.elapsed).finish_non_exhaustive()
}
}
#[derive(Clone, Debug)]
pub(crate) struct Options {
pub format: RecordFormat,
pub sample_rate: u32,
pub channels: u16,
fake: Option<FakeMicrophone>,
}
pub(crate) struct Shared {
path: PathBuf,
opts: Mutex<Options>,
ctl: Mutex<Control>,
/// The published level: peak and RMS f32 bits in one word, so reads take no lock and
/// always see a matching pair.
level: AtomicU64,
/// Whether a fake recording is in progress, so `level` knows to catch it up without
/// locking for a device recording.
faked: AtomicBool,
live: Live<f32>,
waker: WakerSlot,
}
/// Whether recorders use the device backend: in a window, and always in a browser (which has
/// no headless mode and no file system for a fake microphone's WAV).
fn devices() -> bool {
cfg!(target_arch = "wasm32") || crate::video::playback_enabled()
}
/// Seconds since the first recorder looked, for elapsed time in a window.
fn wall_now() -> f64 {
static ORIGIN: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
ORIGIN.get_or_init(rune_core::time::now).elapsed().as_secs_f64()
}
thread_local! {
/// Fake recorders following this thread's headless clock.
static HEADLESS: std::cell::RefCell<Vec<Weak<Shared>>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// `follow_headless` and `reset_headless`, set by `Recorder::to_file`: every runtime's frame calls
/// them through this, so an app that never makes a `Recorder` doesn't link a recorder's state
/// machine.
static HEADLESS_HOOKS: std::sync::OnceLock<(fn(), fn())> = std::sync::OnceLock::new();
/// A headless runtime starts a frame: fake recorders started on this thread catch up to it,
/// so bound level meters move and an unplugged fake microphone interrupts on time.
#[doc(hidden)]
pub fn headless_frame(_clock: f64) {
if let Some((follow, _)) = HEADLESS_HOOKS.get() { follow(); }
}
/// A new runtime on this thread starts its clock at 0: fake recordings keep their elapsed
/// time and go on from there.
#[doc(hidden)]
pub fn headless_reset() {
if let Some((_, reset)) = HEADLESS_HOOKS.get() { reset(); }
}
fn follow_headless() {
let recorders: Vec<Arc<Shared>> = HEADLESS.with_borrow_mut(|h| {
h.retain(|w| w.strong_count() > 0);
h.iter().filter_map(Weak::upgrade).collect()
});
for r in recorders {
r.follow();
}
}
fn reset_headless() {
let recorders: Vec<Arc<Shared>> = HEADLESS.with_borrow(|h| h.iter().filter_map(Weak::upgrade).collect());
for r in recorders {
r.apply(Event::Tick);
r.ctl.lock().unwrap().restart_clock();
}
}
impl Recorder {
/// How often a recording publishes its level in a window. A `poll` that draws elapsed
/// time can ask for frames at this rate while recording with `tx.wake_after`.
pub const METER_INTERVAL: Duration = Duration::from_millis(33);
/// A recorder writing `path`: WAV when it ends in `.wav`, otherwise AAC, at 44.1 kHz
/// mono. The format decides the file's extension: AAC writes `.m4a` (or keeps `.mp4`) and
/// WAV writes `.wav`, so `to_file("note")` writes `note.m4a`, and
/// [`Recording::path`] is always the file written. Nothing happens until
/// [`start`](Self::start); each start overwrites the file.
pub fn to_file(path: impl Into<PathBuf>) -> Self {
HEADLESS_HOOKS.get_or_init(|| (follow_headless, reset_headless));
let path = path.into();
let wav = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("wav"));
let format = if wav { RecordFormat::Wav } else { RecordFormat::Aac };
let opts = Options { format, sample_rate: 44_100, channels: 1, fake: None };
Self {
shared: Arc::new(Shared {
opts: Mutex::new(opts),
ctl: Mutex::new(Control::new(path.clone())),
path,
level: AtomicU64::new(pack(Level::SILENT)),
faked: AtomicBool::new(false),
live: Live::new(0.0),
waker: WakerSlot::default(),
}),
}
}
/// The format for the next start, overriding the extension's. The file's extension
/// follows it: `to_file("note.m4a").format(RecordFormat::Wav)` writes `note.wav`.
pub fn format(self, format: RecordFormat) -> Self {
self.shared.opts.lock().unwrap().format = format;
self
}
/// Device sample rate for the next start (default 44 100 Hz).
pub fn sample_rate(self, hz: u32) -> Self {
self.shared.opts.lock().unwrap().sample_rate = hz.clamp(8_000, 192_000);
self
}
/// Device channels for the next start: 1 (default) or 2.
pub fn channels(self, channels: u16) -> Self {
self.shared.opts.lock().unwrap().channels = channels.clamp(1, 2);
self
}
/// Record from `mic` instead of a device, even in a window (where its level and elapsed
/// time update when read). A fake microphone always writes 16-bit mono WAV at its input's
/// rate: for an AAC recorder at `note.m4a` it writes `note.wav`, and [`Recording::path`]
/// says so.
pub fn fake(self, mic: FakeMicrophone) -> Self {
self.shared.opts.lock().unwrap().fake = Some(mic);
self
}
/// The file a device recording writes: the path given to [`to_file`](Self::to_file),
/// with the format's extension. A fake microphone writes the `.wav` beside it.
pub fn path(&self) -> PathBuf {
with_format_extension(&self.shared.path, self.shared.opts.lock().unwrap().format)
}
/// Microphone access now. Headless: the installed [`FakeMicrophone`]'s (default
/// `Granted`). Never asks.
pub fn permission() -> MicPermission {
if devices() { backend::permission() } else { FakeMicrophone::installed().permission }
}
/// Asks for microphone access if it's `Undetermined`, then calls `callback` with the
/// answer, from any thread (at once when already decided, and always at once headless).
/// macOS shows its prompt with the app's `NSMicrophoneUsageDescription`; a bundled app
/// without one gets `Denied` rather than the crash macOS would cause.
pub fn request_permission(callback: impl FnOnce(MicPermission) + Send + 'static) {
if devices() { backend::request_permission(Box::new(callback)) } else { callback(FakeMicrophone::request_installed()) }
}
/// Starts recording, from `Idle`, `Stopped`, `Interrupted` or `Failed` (an interrupted
/// recording's file is overwritten). Asks for permission first when it's `Undetermined`
/// (the state is `Starting` meanwhile); without it the state becomes `Failed`.
pub fn start(&self) {
let shared = &self.shared;
let fake = shared.fake_mic().is_some();
let format = if fake { RecordFormat::Wav } else { shared.opts.lock().unwrap().format };
let path = with_format_extension(&shared.path, format);
shared.apply(Event::Start { path, virtual_clock: fake && !devices() });
shared.settle();
}
/// Pauses a recording; elapsed time and the file stop growing.
pub fn pause(&self) {
self.shared.apply(Event::Pause);
self.shared.settle();
}
/// Resumes a paused recording into the same file.
pub fn resume(&self) {
self.shared.apply(Event::Resume);
self.shared.settle();
}
/// Stops and finalizes the file (blocking for the few milliseconds that takes), returning
/// it. After an interruption, returns what was saved. Stopping while `Starting` abandons
/// the start; stopping when not recording returns an error and changes nothing.
pub fn stop(&self) -> Result<Recording, String> {
let result = self.shared.apply(Event::Stop).unwrap_or_else(|| Err(control::NOT_RECORDING.into()));
self.shared.settle();
result
}
/// Stops and deletes the file of a recording in progress (or interrupted), back to
/// `Idle`. Only a file this recording created is deleted: a stopped recording's file is
/// the app's and stays, and cancelling a start that hasn't opened the input yet leaves an
/// earlier file at the same path alone.
pub fn cancel(&self) {
self.shared.apply(Event::Cancel);
self.shared.settle();
}
pub fn state(&self) -> RecorderState {
self.shared.lock_following().status()
}
/// Whether audio is being captured now (`Recording`, not paused).
pub fn is_recording(&self) -> bool {
self.shared.lock_following().status() == RecorderState::Recording
}
/// Seconds recorded, pauses excluded: 0 until recording starts, held while paused and
/// after stopping. Live from the clock in a window; the virtual clock headless.
pub fn elapsed(&self) -> f64 {
self.shared.lock_following().elapsed
}
/// The smoothed input level, silent unless recording. Takes no lock in a window and never
/// allocates, so it's fine to read every frame.
pub fn level(&self) -> Level {
if self.shared.faked.load(Ordering::Relaxed) {
self.shared.follow();
}
unpack(self.shared.level.load(Ordering::Acquire))
}
/// [`level().meter()`](Level::meter) as a [`Live`] value, for `live_scale`, `live_rect`
/// or `live_opacity`: a bound meter redraws at the meter rate while recording without
/// re-running the view, and draws nothing while idle or paused.
pub fn live_level(&self) -> Live<f32> {
self.shared.live.clone()
}
/// Called, from any thread, when the state changes: started, paused, resumed, stopped,
/// interrupted or failed. Hand it the app's `setup` waker so `poll` hears a permission
/// answer or an unplugged microphone. Nothing calls it for elapsed time or levels.
pub fn set_waker(&self, waker: rune_core::Waker) {
self.shared.waker.set(waker);
self.shared.settle();
}
}
const DENIED: &str = "microphone access is denied: allow it in System Settings > Privacy & Security > Microphone";
const RESTRICTED: &str = "microphone access is restricted on this device";
fn granted(answer: MicPermission) -> Result<(), String> {
match answer {
MicPermission::Granted => Ok(()),
MicPermission::Restricted => Err(RESTRICTED.into()),
MicPermission::Denied | MicPermission::Undetermined => Err(DENIED.into()),
}
}
impl Control {
/// The clock elapsed time follows.
fn now(&self) -> Option<f64> {
if self.virtual_clock { headless_clock() } else { Some(wall_now()) }
}
}
/// An effect that runs with the control unlocked, as it blocks, re-enters or does I/O.
enum Unlocked {
Ask(Attempt),
OpenFake { attempt: Attempt, mic: FakeMicrophone, path: PathBuf },
StopDevice { attempt: Attempt, session: backend::Session },
CancelDevice(backend::Session),
RemoveFile(PathBuf),
}
impl Shared {
/// The fake microphone a start would use: the recorder's own, or, headless, the thread's.
fn fake_mic(&self) -> Option<FakeMicrophone> {
let own = self.opts.lock().unwrap().fake.clone();
own.or_else(|| (!devices()).then(FakeMicrophone::installed))
}
fn resolve_fake_permission(&self) -> MicPermission {
let mut opts = self.opts.lock().unwrap();
match &mut opts.fake {
Some(mic) => mic.resolve(),
None => FakeMicrophone::request_installed(),
}
}
/// Steps the machine with `event` and carries out what it asks, feeding the answers back
/// in, until nothing is left. Returns what `stop` replies, if it was asked. Opening a
/// device and its answer happen under one lock, so no other event lands between them.
/// Call with no locks held; the caller settles.
fn apply(self: &Arc<Self>, event: Event) -> Option<Result<Recording, String>> {
let mut events = vec![event];
let mut reply = None;
while !events.is_empty() {
let mut unlocked = Vec::new();
{
let mut c = self.ctl.lock().unwrap();
while !events.is_empty() {
let event = events.remove(0);
let now = c.now();
for effect in c.step(event, now) {
match effect {
Effect::Silence => self.publish(Level::SILENT),
Effect::Publish(level) => self.publish(level),
Effect::Ask { attempt } => unlocked.push(Unlocked::Ask(attempt)),
Effect::Open { attempt } => match self.fake_mic() {
Some(mic) => unlocked.push(Unlocked::OpenFake { attempt, mic, path: c.path.clone() }),
None => {
let opts = self.opts.lock().unwrap().clone();
events.push(Event::DeviceOpened { attempt, opened: backend::start(self, attempt, &c.path, &opts) });
}
},
Effect::FollowHeadless => self.follow_headless(),
Effect::PauseDevice => c.device().into_iter().for_each(backend::pause),
Effect::ResumeDevice => c.device().into_iter().for_each(backend::resume),
Effect::StopDevice { attempt, session } => unlocked.push(Unlocked::StopDevice { attempt, session }),
Effect::CancelDevice(session) => unlocked.push(Unlocked::CancelDevice(session)),
Effect::RemoveFile(path) => unlocked.push(Unlocked::RemoveFile(path)),
Effect::Reply(result) => reply = Some(result),
}
}
}
self.faked.store(c.is_fake(), Ordering::Relaxed);
}
events.extend(unlocked.into_iter().filter_map(|job| self.run(job)));
}
reply
}
fn run(self: &Arc<Self>, job: Unlocked) -> Option<Event> {
match job {
Unlocked::Ask(attempt) => self.ask(attempt),
Unlocked::OpenFake { attempt, mic, path } => {
let opened = mic.open().and_then(|input| {
// The file exists from the start, as a device recording's does.
fake::write_wav(&path, &input, 0)?;
Ok(FakeSession::new(input, path, mic.unplug))
});
Some(Event::FakeOpened { attempt, opened })
}
Unlocked::StopDevice { attempt, session } => Some(Event::Stopped { attempt, result: backend::stop(session) }),
Unlocked::CancelDevice(session) => {
backend::cancel(session);
None
}
Unlocked::RemoveFile(path) => {
std::fs::remove_file(path).ok();
None
}
}
}
/// Microphone access for `attempt`: the answer now, or later from the system's prompt.
fn ask(self: &Arc<Self>, attempt: Attempt) -> Option<Event> {
let fake = self.fake_mic();
if fake.is_none()
&& let Err(e) = backend::preflight()
{
return Some(Event::Permission { attempt, granted: Err(e) });
}
let answer = match (fake.as_ref().map_or_else(backend::permission, |mic| mic.permission), fake) {
(MicPermission::Undetermined, Some(_)) => self.resolve_fake_permission(),
(MicPermission::Undetermined, None) => {
let weak = Arc::downgrade(self);
backend::request_permission(Box::new(move |answer| {
let Some(shared) = weak.upgrade() else { return };
shared.apply(Event::Permission { attempt, granted: granted(answer) });
shared.settle();
}));
return None;
}
(answer, _) => answer,
};
Some(Event::Permission { attempt, granted: granted(answer) })
}
/// Follow this recorder on every headless frame of this thread, once.
fn follow_headless(self: &Arc<Self>) {
HEADLESS.with_borrow_mut(|h| {
h.retain(|w| w.strong_count() > 0);
if !h.iter().any(|w| std::ptr::eq(w.as_ptr(), Arc::as_ptr(self))) {
h.push(Arc::downgrade(self));
}
});
}
/// The control, caught up to the clock.
fn lock_following(self: &Arc<Self>) -> std::sync::MutexGuard<'_, Control> {
self.follow();
self.ctl.lock().unwrap()
}
/// A recording catches up to the clock: elapsed, a fake's levels, and an unplugged input.
fn follow(self: &Arc<Self>) {
self.apply(Event::Tick);
self.settle();
}
fn publish(&self, level: Level) {
self.level.store(pack(level), Ordering::Release);
self.live.set(level.meter());
}
/// Tells the app's waker that the state changed. Call with no locks held.
fn settle(&self) {
let generation = self.ctl.lock().unwrap().generation;
self.waker.tell(generation);
}
// Reports from a device backend's thread.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn began(self: &Arc<Self>, attempt: Attempt) {
self.apply(Event::Began { attempt });
self.settle();
}
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn failed(self: &Arc<Self>, attempt: Attempt, error: String) {
self.apply(Event::Failed { attempt, error });
self.settle();
}
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn interrupted(self: &Arc<Self>, attempt: Attempt, reason: String, duration: f64) {
self.apply(Event::Interrupted { attempt, reason, duration });
self.settle();
}
/// A level from the device, published unless the recording moved on.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn metered(self: &Arc<Self>, attempt: Attempt, level: Level) {
self.apply(Event::Metered { attempt, level });
}
}
/// The last handle is gone: a recording in progress stops and keeps its file. This never
/// locks (it has the only reference), so it can't deadlock wherever the last handle drops.
impl Drop for Shared {
fn drop(&mut self) {
let c = self.ctl.get_mut().unwrap_or_else(PoisonError::into_inner);
let now = c.now();
let source = match std::mem::replace(&mut c.phase, Phase::Idle) {
Phase::Recording { source, mut anchor, .. } => {
control::advance(&mut c.elapsed, &mut anchor, now);
source
}
Phase::Paused { source, .. } => source,
Phase::Opening { session, .. } => Source::Device(session),
_ => return,
};
match source {
Source::Fake(fake) => {
fake.write(c.elapsed).ok();
}
Source::Device(session) => backend::finish(session),
}
}
}
/// `path` with an extension that holds `format`, which AVAudioRecorder picks the container by.
fn with_format_extension(path: &Path, format: RecordFormat) -> PathBuf {
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let (keep, want): (&[&str], &str) = match format {
RecordFormat::Aac => (&["m4a", "mp4"], "m4a"),
RecordFormat::Wav => (&["wav"], "wav"),
};
if ext.as_deref().is_some_and(|e| keep.contains(&e)) { path.to_path_buf() } else { path.with_extension(want) }
}
fn pack(level: Level) -> u64 {
(u64::from(level.peak_db().to_bits()) << 32) | u64::from(level.rms_db().to_bits())
}
fn unpack(bits: u64) -> Level {
Level::new(f32::from_bits((bits >> 32) as u32), f32::from_bits(bits as u32))
}
#[cfg(test)]
mod tests;
+586
View File
@@ -0,0 +1,586 @@
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
/// A temporary directory, removed on drop.
struct Scratch(PathBuf);
impl Scratch {
fn new(name: &str) -> Self {
let dir = std::env::temp_dir().join(format!("rune-recorder-{}-{name}", std::process::id()));
std::fs::remove_dir_all(&dir).ok();
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn join(&self, name: &str) -> PathBuf {
self.0.join(name)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).ok();
}
}
/// Drives this thread's virtual clock like a headless `Runtime`.
struct HeadlessClock(f64);
impl HeadlessClock {
fn new() -> Self {
crate::recorder::headless_reset();
crate::video::headless_reset();
Self(0.0)
}
fn frame(&mut self, dt: f64) {
self.0 += dt;
crate::video::headless_frame(self.0);
crate::recorder::headless_frame(self.0);
}
}
fn runtime() -> HeadlessClock {
HeadlessClock::new()
}
#[track_caller]
fn near(got: f64, want: f64, tolerance: f64) {
assert!((got - want).abs() <= tolerance, "got {got}, want {want}");
}
#[test]
fn a_recording_starts_pauses_resumes_and_stops() {
FakeMicrophone::silence().install();
let dir = Scratch::new("states");
let rec = Recorder::to_file(dir.join("note.wav"));
let mut rt = runtime();
assert_eq!(rec.state(), RecorderState::Idle);
assert_eq!(rec.stop(), Err("not recording".into()));
rec.start();
assert_eq!(rec.state(), RecorderState::Recording);
assert!(rec.is_recording());
rt.frame(0.25);
near(rec.elapsed(), 0.25, 1e-9);
rec.pause();
assert_eq!(rec.state(), RecorderState::Paused);
rt.frame(0.5);
near(rec.elapsed(), 0.25, 1e-9);
rec.resume();
rec.start(); // Already recording: nothing happens.
rt.frame(0.1);
near(rec.elapsed(), 0.35, 1e-9);
let note = rec.stop().unwrap();
assert_eq!(note.path, dir.join("note.wav"));
near(note.duration, 0.35, 1e-9);
assert_eq!(rec.state(), RecorderState::Stopped);
rt.frame(0.2);
near(rec.elapsed(), 0.35, 1e-9);
assert_eq!(rec.stop(), Err("not recording".into()));
rec.start();
assert_eq!(rec.elapsed(), 0.0, "a new recording starts from zero");
rt.frame(0.1);
near(rec.elapsed(), 0.1, 1e-9);
}
#[test]
fn a_new_runtime_restarts_elapsed_from_its_own_clock() {
FakeMicrophone::silence().install();
let dir = Scratch::new("clock");
let mut old = runtime();
old.frame(5.0);
let rec = Recorder::to_file(dir.join("note.wav"));
rec.start();
let mut rt = runtime();
rt.frame(0.1);
rt.frame(0.1);
near(rec.elapsed(), 0.2, 1e-9);
}
#[test]
fn a_known_sine_reads_its_known_peak_and_rms() {
let dir = Scratch::new("sine");
FakeMicrophone::sine(1000.0, 0.5).install();
let rec = Recorder::to_file(dir.join("a.wav"));
let mut rt = runtime();
assert_eq!(rec.level(), Level::SILENT);
rec.start();
rt.frame(1.0);
let level = rec.level();
// Peak 0.5 is -6.02 dBFS; a sine's RMS is 3.01 dB below its peak.
near(level.peak_db() as f64, 20.0 * 0.5f64.log10(), 0.01);
near(level.rms_db() as f64, 20.0 * (0.5 / 2f64.sqrt()).log10(), 0.01);
near(level.meter() as f64, (60.0 - 9.0309) / 60.0, 0.001);
assert_eq!(rec.live_level().get(), level.meter());
rec.pause();
assert_eq!(rec.level(), Level::SILENT, "a paused recorder hears nothing");
assert_eq!(rec.live_level().get(), 0.0);
rec.stop().unwrap();
// The same second in 64 frames reads exactly the same: levels don't depend on frame rate.
let rec = Recorder::to_file(dir.join("b.wav"));
let mut rt = runtime();
rec.start();
for _ in 0..64 {
rt.frame(1.0 / 64.0);
}
assert_eq!(rec.level(), level);
FakeMicrophone::silence().install();
let quiet = Recorder::to_file(dir.join("c.wav"));
quiet.start();
rt.frame(0.5);
assert_eq!(quiet.level(), Level::SILENT);
assert_eq!(quiet.level().meter(), 0.0);
}
#[test]
fn the_meter_rises_fast_and_falls_slowly() {
let mut m = Meter::default();
for _ in 0..3 {
m.push(0.5, 0.125, 0.01);
}
let rising = m.level();
assert!(rising.rms_db() > -12.0, "30 ms in, the RMS is close: {rising:?}");
for _ in 0..10 {
m.push(0.0, 0.0, 0.01);
}
let falling = m.level();
assert!(falling.rms_db() > -13.0 && falling.rms_db() < rising.rms_db(), "100 ms of silence: {falling:?}");
near(falling.peak_db() as f64, -6.0206 - 2.0, 0.01);
m.push(f64::NAN, f64::INFINITY, 0.01);
assert!(m.level().rms_db().is_finite(), "bad samples never poison the meter");
}
#[test]
fn stopping_writes_a_wav_of_the_recorded_length() {
let dir = Scratch::new("length");
FakeMicrophone::sine(1000.0, 0.5).install();
let rec = Recorder::to_file(dir.join("note.wav"));
let mut rt = runtime();
rec.start();
rt.frame(1.5);
let note = rec.stop().unwrap();
near(note.duration, 1.5, 1e-9);
let (rate, samples) = fake::read_wav(&note.path).unwrap();
assert_eq!((rate, samples.len()), (48_000, 72_000));
near(samples[12] as f64, 0.5, 1.0 / 32_000.0);
near(samples[36] as f64, -0.5, 1.0 / 32_000.0);
// Players open it.
#[cfg(target_os = "macos")]
{
let clip = crate::Player::audio(note.path.clone());
near(clip.duration().expect("the recording opens"), 1.5, 0.01);
}
}
#[test]
fn an_aac_recorder_on_a_fake_microphone_writes_wav_beside_its_path() {
let dir = Scratch::new("aac");
FakeMicrophone::silence().install();
let rec = Recorder::to_file(dir.join("note.m4a"));
let mut rt = runtime();
rec.start();
rt.frame(0.2);
let note = rec.stop().unwrap();
assert_eq!(note.path, dir.join("note.wav"));
assert!(note.path.exists());
assert!(!dir.join("note.m4a").exists());
assert_eq!(rec.path(), dir.join("note.m4a"), "a device would write the m4a");
}
/// The format picks the extension, so AVAudioRecorder (which picks its container by the
/// extension) never gets a mismatch, and a fake never writes RIFF into an `.m4a`.
#[test]
fn the_format_decides_the_file_extension() {
let dir = Scratch::new("extension");
FakeMicrophone::silence().install();
let path = |rec: Recorder| rec.path().strip_prefix(&dir.0).unwrap().to_path_buf();
assert_eq!(path(Recorder::to_file(dir.join("x.wav")).format(RecordFormat::Aac)), PathBuf::from("x.m4a"));
assert_eq!(path(Recorder::to_file(dir.join("x.m4a")).format(RecordFormat::Wav)), PathBuf::from("x.wav"));
assert_eq!(path(Recorder::to_file(dir.join("x"))), PathBuf::from("x.m4a"));
assert_eq!(path(Recorder::to_file(dir.join("x.mp3"))), PathBuf::from("x.m4a"));
assert_eq!(path(Recorder::to_file(dir.join("x.MP4"))), PathBuf::from("x.MP4"));
assert_eq!(path(Recorder::to_file(dir.join("x.WAV"))), PathBuf::from("x.WAV"));
let wav = Recorder::to_file(dir.join("note.m4a")).format(RecordFormat::Wav);
wav.start();
let note = wav.stop().unwrap();
assert_eq!(note.path, dir.join("note.wav"));
assert_eq!(&std::fs::read(&note.path).unwrap()[..4], b"RIFF");
assert!(!dir.join("note.m4a").exists(), "no RIFF bytes behind an .m4a name");
}
/// Dropping the last handle mid-recording keeps what was captured, whether recording or
/// paused; a clone keeps the recording going.
#[test]
fn dropping_the_last_handle_keeps_the_recording() {
let dir = Scratch::new("drop");
FakeMicrophone::sine(1000.0, 0.5).install();
let mut rt = runtime();
let rec = Recorder::to_file(dir.join("a.wav"));
rec.start();
rt.frame(0.25);
let clone = rec.clone();
drop(rec);
rt.frame(0.25);
assert!(clone.is_recording());
drop(clone);
let (_, samples) = fake::read_wav(&dir.join("a.wav")).unwrap();
assert_eq!(samples.len(), 24_000);
let rec = Recorder::to_file(dir.join("b.wav"));
rec.start();
rt.frame(0.1);
rec.pause();
rt.frame(0.5);
drop(rec);
assert_eq!(fake::read_wav(&dir.join("b.wav")).unwrap().1.len(), 4_800);
// A cancelled or stopped recorder leaves nothing more to do.
let rec = Recorder::to_file(dir.join("c.wav"));
rec.start();
rt.frame(0.1);
rec.cancel();
drop(rec);
assert!(!dir.join("c.wav").exists());
}
/// Cancelling a start that hasn't opened anything (still waiting on permission, say) leaves
/// an earlier recording at the same path alone.
#[test]
fn cancelling_a_pending_start_keeps_an_earlier_file() {
let dir = Scratch::new("pending");
FakeMicrophone::silence().install();
let path = dir.join("note.wav");
let rec = Recorder::to_file(&path);
let mut rt = runtime();
rec.start();
rt.frame(0.2);
rec.stop().unwrap();
// A device start waiting on a permission answer: Starting, with no input open.
{
let mut c = rec.shared.ctl.lock().unwrap();
let attempt = c.seq.next();
c.phase = Phase::Asking { attempt };
}
rec.cancel();
assert_eq!(rec.state(), RecorderState::Idle);
assert!(path.exists(), "the earlier recording stays");
}
/// 60 frames of 1/60 s sum to just under 1 s; that mustn't drop the last block's level, a
/// sample, or move an unplug to a later frame.
#[test]
fn frame_rate_never_moves_a_sample_level_or_unplug() {
let dir = Scratch::new("rate");
FakeMicrophone::default().install();
let mut rt = runtime();
let one = Recorder::to_file(dir.join("one.wav"));
one.start();
rt.frame(1.0);
let (level, note) = (one.level(), one.stop().unwrap());
let mut rt = runtime();
let sixty = Recorder::to_file(dir.join("sixty.wav"));
sixty.start();
for _ in 0..60 {
rt.frame(1.0 / 60.0);
}
assert_eq!(sixty.level(), level);
let other = sixty.stop().unwrap();
assert_eq!(other.duration, note.duration);
assert_eq!(fake::read_wav(&other.path).unwrap().1.len(), 48_000);
FakeMicrophone::silence().unplug_after(0.3).install();
let mut rt = runtime();
let rec = Recorder::to_file(dir.join("unplug.wav"));
rec.start();
for _ in 0..18 {
rt.frame(1.0 / 60.0);
}
assert!(matches!(rec.state(), RecorderState::Interrupted(_)), "unplugs on the 18th frame: {:?}", rec.state());
assert_eq!(rec.stop().unwrap().duration, 0.3);
}
/// Restarting a recorder doesn't follow it more than once a frame.
#[test]
fn a_restarted_recorder_is_followed_once() {
let dir = Scratch::new("restart");
FakeMicrophone::silence().install();
let mut rt = runtime();
let rec = Recorder::to_file(dir.join("note.wav"));
for _ in 0..3 {
rec.start();
rt.frame(0.1);
rec.stop().unwrap();
}
let followed = HEADLESS.with_borrow(|h| h.iter().filter(|w| std::ptr::eq(w.as_ptr(), Arc::as_ptr(&rec.shared))).count());
assert_eq!(followed, 1);
}
#[test]
fn levels_pack_into_one_word() {
for level in [Level::SILENT, Level::new(-6.0, -9.0), Level::new(0.0, -160.0)] {
assert_eq!(unpack(pack(level)), level);
}
}
/// A late failure from an earlier attempt leaves the current attempt's session alone.
#[cfg(target_os = "macos")]
#[test]
fn a_stale_failure_leaves_the_current_session() {
let rec = Recorder::to_file(std::env::temp_dir().join("rune-recorder-stale.m4a"));
let (session, _commands) = macos::idle_session();
let (stale, attempt) = {
let mut c = rec.shared.ctl.lock().unwrap();
let (stale, attempt) = (c.seq.next(), c.seq.next());
c.phase = Phase::Opening { attempt, session };
(stale, attempt)
};
rec.shared.failed(stale, "late".into());
assert!(matches!(rec.shared.ctl.lock().unwrap().phase, Phase::Opening { .. }));
rec.shared.failed(attempt, "now".into());
assert!(matches!(rec.shared.ctl.lock().unwrap().phase, Phase::Failed(_)));
}
/// A second `stop` (or a `cancel`) while the device finishes its file changes nothing: the
/// first `stop` gets the file. It used to mark the recorder `Failed("not recording")`.
#[cfg(target_os = "macos")]
#[test]
fn a_second_stop_while_the_device_finishes_changes_nothing() {
let rec = Recorder::to_file(std::env::temp_dir().join("rune-recorder-second-stop.m4a"));
let (session, commands) = macos::idle_session();
{
let mut c = rec.shared.ctl.lock().unwrap();
let attempt = c.seq.next();
c.phase = Phase::Recording { attempt, source: Source::Device(session), anchor: None };
}
let first = std::thread::spawn({
let rec = rec.clone();
move || rec.stop()
});
let Ok(macos::Command::Stop(reply)) = commands.recv() else { panic!("the device was asked to stop") };
assert_eq!(rec.stop(), Err("not recording".into()));
rec.cancel();
assert_eq!(rec.state(), RecorderState::Recording, "still finishing the first stop's file");
reply.send(Ok(1.5)).unwrap();
assert_eq!(first.join().unwrap().map(|r| r.duration), Ok(1.5));
assert_eq!(rec.state(), RecorderState::Stopped);
}
/// Dropping the last handle on the recorder thread itself (the last handle went while it
/// reported) returns at once instead of waiting on itself.
#[cfg(target_os = "macos")]
#[test]
fn finishing_on_the_recorder_thread_doesnt_wait_on_itself() {
let (session, commands) = macos::idle_session();
let begun = rune_core::time::now();
std::thread::spawn(move || {
macos::mark_recorder_thread();
macos::finish(session);
})
.join()
.unwrap();
assert!(begun.elapsed() < std::time::Duration::from_secs(1));
assert!(commands.try_recv().is_err(), "nothing was asked of the thread");
}
#[test]
fn cancel_deletes_the_file_of_a_recording_in_progress() {
let dir = Scratch::new("cancel");
FakeMicrophone::silence().install();
let path = dir.join("note.wav");
let rec = Recorder::to_file(&path);
let mut rt = runtime();
rec.start();
assert!(path.exists(), "the file exists from the start");
rt.frame(0.3);
rec.cancel();
assert!(!path.exists());
assert_eq!(rec.state(), RecorderState::Idle);
assert!(rec.stop().is_err());
rec.start();
rt.frame(0.3);
rec.pause();
rec.cancel();
assert!(!path.exists(), "paused counts as in progress");
rec.start();
rt.frame(0.3);
rec.stop().unwrap();
rec.cancel();
assert!(path.exists(), "a stopped recording is the app's");
assert_eq!(rec.state(), RecorderState::Stopped);
}
#[test]
fn starting_without_permission_fails_clearly() {
let dir = Scratch::new("permission");
let path = dir.join("note.wav");
FakeMicrophone::silence().permission(MicPermission::Denied).install();
assert_eq!(Recorder::permission(), MicPermission::Denied);
let rec = Recorder::to_file(&path);
rec.start();
let RecorderState::Failed(message) = rec.state() else { panic!("{:?}", rec.state()) };
assert!(message.contains("denied"), "{message}");
assert!(!rec.is_recording());
assert!(!path.exists(), "nothing is written without permission");
assert_eq!(rec.stop(), Err(message));
FakeMicrophone::silence().permission(MicPermission::Restricted).install();
rec.start();
assert!(matches!(rec.state(), RecorderState::Failed(m) if m.contains("restricted")));
// Undetermined: starting asks, and the answer sticks.
FakeMicrophone::silence().permission(MicPermission::Undetermined).answers(MicPermission::Denied).install();
rec.start();
assert!(matches!(rec.state(), RecorderState::Failed(m) if m.contains("denied")));
assert_eq!(Recorder::permission(), MicPermission::Denied);
FakeMicrophone::silence().permission(MicPermission::Undetermined).install();
let answer = Arc::new(Mutex::new(None));
let heard = answer.clone();
Recorder::request_permission(move |p| *heard.lock().unwrap() = Some(p));
assert_eq!(*answer.lock().unwrap(), Some(MicPermission::Granted));
assert_eq!(Recorder::permission(), MicPermission::Granted);
rec.start();
assert_eq!(rec.state(), RecorderState::Recording);
// A recorder's own fake microphone decides for it.
let own = Recorder::to_file(dir.join("own.wav")).fake(FakeMicrophone::silence().permission(MicPermission::Undetermined).answers(MicPermission::Granted));
own.start();
assert_eq!(own.state(), RecorderState::Recording);
}
#[test]
fn an_unplugged_microphone_keeps_what_was_captured() {
let dir = Scratch::new("unplug");
FakeMicrophone::sine(440.0, 0.25).unplug_after(0.5).install();
let rec = Recorder::to_file(dir.join("note.wav"));
let changes = Arc::new(AtomicUsize::new(0));
let count = changes.clone();
rec.set_waker(Arc::new(move || {
count.fetch_add(1, SeqCst);
}));
let mut rt = runtime();
rec.start();
rt.frame(0.3);
assert_eq!(rec.state(), RecorderState::Recording);
let before = changes.load(SeqCst);
rt.frame(0.4);
assert_eq!(changes.load(SeqCst), before + 1, "the frame that unplugs wakes the app");
assert_eq!(rec.state(), RecorderState::Interrupted("the microphone went away".into()));
near(rec.elapsed(), 0.5, 1e-9);
assert_eq!(rec.level(), Level::SILENT);
let note = rec.stop().unwrap();
near(note.duration, 0.5, 1e-9);
assert_eq!(fake::read_wav(&note.path).unwrap().1.len(), 24_000);
assert_eq!(rec.state(), RecorderState::Stopped);
rec.start();
rt.frame(0.6);
assert!(matches!(rec.state(), RecorderState::Interrupted(_)));
rec.cancel();
assert!(!note.path.exists(), "cancel deletes an interrupted recording");
}
#[test]
fn the_waker_hears_state_changes_not_progress() {
let dir = Scratch::new("waker");
FakeMicrophone::silence().install();
let rec = Recorder::to_file(dir.join("note.wav"));
let calls = Arc::new(AtomicUsize::new(0));
let count = calls.clone();
rec.set_waker(Arc::new(move || {
count.fetch_add(1, SeqCst);
}));
assert_eq!(calls.load(SeqCst), 0, "nothing happened yet");
let mut rt = runtime();
rec.start();
assert_eq!(calls.load(SeqCst), 1);
rt.frame(0.1);
rt.frame(0.1);
let _ = (rec.elapsed(), rec.level());
assert_eq!(calls.load(SeqCst), 1, "elapsed time and levels don't wake");
rec.pause();
rec.resume();
rec.stop().unwrap();
assert_eq!(calls.load(SeqCst), 4);
}
#[test]
fn wav_and_sample_inputs_record_their_samples() {
let dir = Scratch::new("wav");
let ramp: Vec<f32> = (0..800).map(|i| i as f32 / 800.0 - 0.5).collect();
let rec = Recorder::to_file(dir.join("ramp.wav")).fake(FakeMicrophone::samples(8_000, ramp.clone()));
let mut rt = runtime();
rec.start();
rt.frame(0.25); // 2000 samples: the 800-sample ramp loops.
let ramp_file = rec.stop().unwrap().path;
let (rate, got) = fake::read_wav(&ramp_file).unwrap();
assert_eq!((rate, got.len()), (8_000, 2_000));
for (i, s) in got.iter().enumerate() {
near(*s as f64, ramp[i % 800] as f64, 1.0 / 32_000.0);
}
let again = Recorder::to_file(dir.join("again.wav")).fake(FakeMicrophone::wav(&ramp_file));
again.start();
rt.frame(0.125);
let (_, copy) = fake::read_wav(&again.stop().unwrap().path).unwrap();
assert_eq!(copy.len(), 1_000);
for (a, b) in copy.iter().zip(&got) {
near(*a as f64, *b as f64, 1.0 / 32_000.0);
}
let missing = Recorder::to_file(dir.join("x.wav")).fake(FakeMicrophone::wav(dir.join("missing.wav")));
missing.start();
assert!(matches!(missing.state(), RecorderState::Failed(m) if m.contains("couldn't read")));
}
#[test]
fn an_unwritable_path_fails_to_start() {
FakeMicrophone::silence().install();
let rec = Recorder::to_file(std::env::temp_dir().join("rune-recorder-missing-dir").join("deeper").join("note.wav"));
rec.start();
assert!(matches!(rec.state(), RecorderState::Failed(m) if m.contains("couldn't write")), "{:?}", rec.state());
}
#[test]
fn wav_files_parse_formats_and_reject_others() {
assert!(fake::parse_wav(b"RIFF\0\0\0\0WAVE").is_err());
assert!(fake::parse_wav(b"not a wav").is_err());
// Stereo 32-bit float, mixed to mono.
let mut b = Vec::new();
b.extend_from_slice(b"RIFF\0\0\0\0WAVEfmt ");
b.extend_from_slice(&16u32.to_le_bytes());
b.extend_from_slice(&3u16.to_le_bytes());
b.extend_from_slice(&2u16.to_le_bytes());
b.extend_from_slice(&22_050u32.to_le_bytes());
b.extend_from_slice(&(22_050u32 * 8).to_le_bytes());
b.extend_from_slice(&8u16.to_le_bytes());
b.extend_from_slice(&32u16.to_le_bytes());
b.extend_from_slice(b"data");
b.extend_from_slice(&16u32.to_le_bytes());
for s in [0.5f32, -0.5, 1.0, 0.0] {
b.extend_from_slice(&s.to_le_bytes());
}
assert_eq!(fake::parse_wav(&b).unwrap(), (22_050, vec![0.0, 0.5]));
}
/// The real backend's recorder object builds for both formats without preparing or starting
/// it, so nothing is captured and no permission prompt appears.
#[cfg(target_os = "macos")]
#[test]
#[allow(unsafe_code)]
fn the_macos_recorder_builds_without_capturing() {
use objc2::msg_send;
use objc2::runtime::Bool;
let dir = Scratch::new("macos");
for (name, format) in [("a.m4a", RecordFormat::Aac), ("b.wav", RecordFormat::Wav)] {
let opts = Options { format, sample_rate: 44_100, channels: 1, fake: None };
let recorder = macos::make_recorder(&dir.join(name), &opts).unwrap_or_else(|e| panic!("{name}: {e}"));
// SAFETY: `recorder` is a live `AVAudioRecorder` returned by `make_recorder`; `isRecording` returns `BOOL`.
let recording: Bool = unsafe { msg_send![&*recorder, isRecording] };
assert!(!recording.as_bool());
}
assert!(macos::preflight().is_ok(), "an unbundled test binary is attributed to its terminal");
// Reading the status never prompts.
let _ = macos::permission();
}
@@ -0,0 +1,43 @@
//! Platforms without a recorder yet: starting fails with a clear message. Fake microphones
//! still work everywhere.
use super::{MicPermission, Options, Shared};
use std::path::Path;
use std::sync::Arc;
pub(crate) enum Session {}
pub(super) fn permission() -> MicPermission {
MicPermission::Restricted
}
pub(super) fn request_permission(callback: Box<dyn FnOnce(MicPermission) + Send>) {
callback(MicPermission::Restricted)
}
pub(super) fn preflight() -> Result<(), String> {
Err("recording isn't supported on this platform".into())
}
pub(super) fn start(_: &Arc<Shared>, _: rune_core::machine::Attempt, _: &Path, _: &Options) -> Result<Session, String> {
Err("recording isn't supported on this platform".into())
}
pub(super) fn pause(session: &Session) {
match *session {}
}
pub(super) fn resume(session: &Session) {
match *session {}
}
pub(super) fn stop(session: Session) -> Result<f64, String> {
match session {}
}
pub(super) fn finish(session: Session) {
match session {}
}
pub(super) fn cancel(session: Session) {
match session {}
}
+293
View File
@@ -0,0 +1,293 @@
//! Ogg (Vorbis, Opus) and WebM/Matroska audio, which AVFoundation can't read: decoded in Rust
//! to 16-bit PCM, streamed to a temporary WAV file that AVPlayer then plays. Only the
//! compressed clip is held in memory while it decodes.
use std::io::{BufWriter, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use symphonia::core::audio::SampleBuffer;
use symphonia::core::codecs::{CODEC_TYPE_OPUS, CODEC_TYPE_VORBIS, DecoderOptions};
use symphonia::core::errors::Error;
use symphonia::core::formats::FormatOptions;
use symphonia::core::io::MediaSourceStream;
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
/// A WAV's sizes are 32-bit: at most this many 16-bit samples (about 6 hours of 48 kHz stereo).
const MAX_SAMPLES: u64 = (u32::MAX as u64 - 36) / 2;
const TOO_LONG: &str = "too long to decode (a WAV holds about 6 hours of 48 kHz stereo)";
/// What a decode produced.
struct Format {
rate: u32,
channels: u16,
/// Interleaved samples to keep, when the container says where the clip ends.
keep: Option<u64>,
}
/// An Ogg or EBML (WebM, Matroska) stream, by its first bytes.
pub(super) fn sniff(bytes: &[u8]) -> bool {
bytes.starts_with(b"OggS") || bytes.starts_with(&[0x1a, 0x45, 0xdf, 0xa3])
}
/// Decodes the first Vorbis or Opus track, handing `push` interleaved samples as they come.
fn decode(bytes: Vec<u8>, push: &mut dyn FnMut(&[i16]) -> Result<(), String>) -> Result<Format, String> {
let fail = |e: Error| format!("can't decode this audio: {e}");
let ogg = bytes.starts_with(b"OggS");
let stream = MediaSourceStream::new(Box::new(std::io::Cursor::new(bytes)), Default::default());
let options = FormatOptions { enable_gapless: true, ..Default::default() };
let mut format = symphonia::default::get_probe()
.format(&Hint::new(), stream, &options, &MetadataOptions::default())
.map_err(fail)?
.format;
let track = format
.tracks()
.iter()
.find(|t| matches!(t.codec_params.codec, CODEC_TYPE_VORBIS | CODEC_TYPE_OPUS))
.ok_or("no Vorbis or Opus audio track")?;
let (id, params) = (track.id, track.codec_params.clone());
let mut decoder = if params.codec == CODEC_TYPE_OPUS {
Decoder::Opus(Opus::new(params.extra_data.as_deref().unwrap_or_default())?)
} else {
Decoder::Vorbis(symphonia::default::get_codecs().make(&params, &DecoderOptions::default()).map_err(fail)?, None)
};
let mut out = Format { rate: params.sample_rate.unwrap_or(48_000), channels: 0, keep: None };
loop {
let packet = match format.next_packet() {
Ok(packet) => packet,
Err(Error::IoError(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
Err(e) => return Err(fail(e)),
};
if packet.track_id() != id {
continue;
}
match &mut decoder {
Decoder::Vorbis(d, buffer) => match d.decode(&packet) {
Ok(audio) => {
let spec = *audio.spec();
out.rate = spec.rate;
out.channels = spec.channels.count() as u16;
let buffer = buffer.get_or_insert_with(|| SampleBuffer::new(audio.capacity() as u64, spec));
if buffer.capacity() < audio.capacity() * spec.channels.count() {
*buffer = SampleBuffer::new(audio.capacity() as u64, spec);
}
buffer.copy_interleaved_ref(audio);
push(buffer.samples())?;
}
// A damaged packet is skipped, as a player would.
Err(Error::DecodeError(_)) => {}
Err(e) => return Err(fail(e)),
},
Decoder::Opus(o) => {
out.rate = 48_000;
out.channels = o.channels as u16;
push(o.decode(&packet.data)?)?;
}
}
}
// Ogg Opus ends at its last granule position, which counts the pre-skip (RFC 7845 §4).
if let (Decoder::Opus(o), Some(end), true) = (&decoder, params.n_frames, ogg) {
out.keep = Some(end.saturating_sub(o.pre_skip as u64) * o.channels as u64).filter(|&keep| keep > 0);
}
Ok(out)
}
enum Decoder {
Vorbis(Box<dyn symphonia::core::codecs::Decoder>, Option<SampleBuffer<i16>>),
Opus(Opus),
}
struct Opus {
decoder: opuscule::Decoder,
channels: usize,
pre_skip: usize,
/// Decoded frames still to drop for the pre-skip.
skip: usize,
gain: f32,
buffer: Vec<f32>,
out: Vec<i16>,
}
impl Opus {
/// From the `OpusHead` identification header (RFC 7845 §5.1).
fn new(head: &[u8]) -> Result<Self, String> {
if head.len() < 19 || &head[..8] != b"OpusHead" {
return Err("Opus track without an OpusHead header".into());
}
let channels = head[9] as usize;
if head[18] != 0 || !(1..=2).contains(&channels) {
return Err(format!("Opus with {channels} channels isn't supported (mono and stereo are)"));
}
let pre_skip = u16::from_le_bytes([head[10], head[11]]) as usize;
let gain_db = i16::from_le_bytes([head[16], head[17]]) as f32 / 256.0;
let layout = if channels == 1 { opuscule::Channels::Mono } else { opuscule::Channels::Stereo };
let decoder = opuscule::Decoder::new(opuscule::SampleRate::Hz48000, layout);
// 120 ms, the longest packet.
let buffer = vec![0.0; 5760 * channels];
Ok(Self { decoder, channels, pre_skip, skip: pre_skip, gain: 10f32.powf(gain_db / 20.0), buffer, out: Vec::new() })
}
fn decode(&mut self, packet: &[u8]) -> Result<&[i16], String> {
self.out.clear();
let frames = match self.decoder.decode(Some(packet), &mut self.buffer, false) {
Ok(frames) => frames,
// A damaged packet is skipped, as a player would.
Err(opuscule::Error::InvalidPacket) => return Ok(&self.out),
Err(e) => return Err(format!("Opus: {e}")),
};
let start = self.skip.min(frames);
self.skip -= start;
let gain = self.gain;
let samples = &self.buffer[start * self.channels..frames * self.channels];
self.out.extend(samples.iter().map(|s| ((s * gain).clamp(-1.0, 1.0) * 32767.0) as i16));
Ok(&self.out)
}
}
/// The 44-byte header of a 16-bit PCM WAV holding `samples` interleaved samples.
fn header(rate: u32, channels: u16, samples: u64) -> Result<[u8; 44], String> {
let too_long = || TOO_LONG.to_string();
let data = u32::try_from(samples.checked_mul(2).ok_or_else(too_long)?).map_err(|_| too_long())?;
let riff = data.checked_add(36).ok_or_else(too_long)?;
let block = channels.checked_mul(2).ok_or("too many channels")?;
let byte_rate = rate.checked_mul(block as u32).ok_or("sample rate too high")?;
let mut h = [0u8; 44];
let fields: [&[u8]; 12] = [
b"RIFF",
&riff.to_le_bytes(),
b"WAVEfmt ",
&16u32.to_le_bytes(),
&1u16.to_le_bytes(),
&channels.to_le_bytes(),
&rate.to_le_bytes(),
&byte_rate.to_le_bytes(),
&block.to_le_bytes(),
&16u16.to_le_bytes(),
b"data",
&data.to_le_bytes(),
];
let mut at = 0;
for field in fields {
h[at..at + field.len()].copy_from_slice(field);
at += field.len();
}
Ok(h)
}
/// A decoded clip on disk for AVPlayer, removed when dropped.
pub(super) struct Wav(PathBuf);
impl Wav {
/// Decodes an Ogg or WebM clip into a new WAV file, streaming its samples to disk.
pub fn decode(bytes: Vec<u8>) -> Result<Self, String> {
let io = |e: std::io::Error| format!("can't write decoded audio: {e}");
static NEXT: AtomicU64 = AtomicU64::new(0);
let dir = std::env::temp_dir().join("rune-audio");
if NEXT.load(Ordering::Relaxed) == 0 {
sweep(&dir);
}
std::fs::create_dir_all(&dir).map_err(io)?;
// Removes the file again on any failure below.
let wav = Self(dir.join(format!("{}-{}.wav", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))));
let mut out = BufWriter::new(std::fs::File::create(&wav.0).map_err(io)?);
out.write_all(&[0; 44]).map_err(io)?;
let (mut samples, mut bytes_out) = (0u64, Vec::new());
let format = decode(bytes, &mut |chunk| {
samples += chunk.len() as u64;
if samples > MAX_SAMPLES {
return Err(TOO_LONG.into());
}
bytes_out.clear();
bytes_out.extend(chunk.iter().flat_map(|s| s.to_le_bytes()));
out.write_all(&bytes_out).map_err(io)
})?;
let samples = format.keep.map_or(samples, |keep| keep.min(samples));
if samples == 0 || format.channels == 0 {
return Err("no audio decoded".into());
}
let header = header(format.rate, format.channels, samples)?;
let mut file = out.into_inner().map_err(|e| io(e.into_error()))?;
file.set_len(44 + samples * 2).map_err(io)?;
file.seek(SeekFrom::Start(0)).and_then(|_| file.write_all(&header)).map_err(io)?;
Ok(wav)
}
pub fn path(&self) -> &Path {
&self.0
}
}
impl Drop for Wav {
fn drop(&mut self) {
std::fs::remove_file(&self.0).ok();
}
}
/// Removes files a process that didn't exit cleanly left a day or more ago.
fn sweep(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let day = std::time::Duration::from_secs(24 * 60 * 60);
for entry in entries.flatten() {
let old = entry.metadata().and_then(|m| m.modified()).is_ok_and(|t| t.elapsed().is_ok_and(|age| age > day));
if old {
std::fs::remove_file(entry.path()).ok();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture(name: &str) -> Vec<u8> {
std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("../rune/tests/fixtures").join(name)).unwrap()
}
/// A WAV's rate, channels and samples, checking its sizes agree with the file.
fn read(path: &Path) -> (u32, u16, Vec<i16>) {
let b = std::fs::read(path).unwrap();
let u32_at = |i: usize| u32::from_le_bytes(b[i..i + 4].try_into().unwrap());
assert_eq!((&b[..4], &b[8..16], &b[36..40]), (&b"RIFF"[..], &b"WAVEfmt "[..], &b"data"[..]));
assert_eq!((u32_at(4) as usize, u32_at(40) as usize), (b.len() - 8, b.len() - 44));
let samples = b[44..].chunks(2).map(|s| i16::from_le_bytes([s[0], s[1]])).collect();
(u32_at(24), u16::from_le_bytes([b[22], b[23]]), samples)
}
/// Each fixture is 0.5 s of a 440 Hz sine.
#[test]
fn decodes_ogg_vorbis_ogg_opus_and_webm_opus() {
for (name, rate, channels) in [("sine-vorbis.ogg", 22_050, 2), ("sine-opus.ogg", 48_000, 1), ("sine-opus.webm", 48_000, 1)] {
let bytes = fixture(name);
assert!(sniff(&bytes), "{name}");
let wav = Wav::decode(bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
let (got_rate, got_channels, samples) = read(wav.path());
assert_eq!((got_rate, got_channels), (rate, channels), "{name}");
let duration = samples.len() as f64 / channels as f64 / rate as f64;
assert!((duration - 0.5).abs() < 0.03, "{name}: {duration}");
if name == "sine-opus.ogg" {
assert_eq!(samples.len(), 24_000, "Ogg's pre-skip and end trim, each applied once");
}
// A sine, not silence: 1/8 amplitude (lavfi's default), RMS ~0.09.
let mid = &samples[samples.len() / 4..samples.len() * 3 / 4];
let rms = (mid.iter().map(|&s| (s as f64 / 32768.0).powi(2)).sum::<f64>() / mid.len() as f64).sqrt();
assert!((0.05..0.6).contains(&rms), "{name}: rms {rms}");
let path = wav.path().to_owned();
drop(wav);
assert!(!path.exists(), "{name}: removed on drop");
}
}
#[test]
fn a_clip_too_long_for_a_wav_fails_clearly() {
assert!(header(48_000, 2, MAX_SAMPLES).is_ok());
let e = header(48_000, 2, MAX_SAMPLES + 1).unwrap_err();
assert!(e.contains("too long"), "{e}");
assert!(header(48_000, 2, u64::MAX).is_err());
}
#[test]
fn rejects_what_isnt_ogg_or_webm() {
assert!(!sniff(b"RIFF\0\0\0\0WAVE"));
assert!(Wav::decode(b"OggS but not really".to_vec()).is_err());
}
}
@@ -0,0 +1,350 @@
//! AVFoundation asset opening, metadata, foreign audio decoding (`ogg-audio`), `CMTime` helpers
//! and still-frame decoding through `AVAssetImageGenerator`.
#![allow(unsafe_code)]
use super::{Decoded, Native};
use crate::native_surface::{ByteFrame, ColorInfo, Format, Orient};
#[cfg(feature = "ogg-audio")]
use crate::video::foreign;
use crate::video::{Kind, MediaSource, Meta};
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2_av_foundation::{
AVAsset, AVAssetImageGenerator, AVAssetReferenceRestrictions, AVMediaTypeAudio, AVMediaTypeVideo, AVURLAsset,
AVURLAssetReferenceRestrictionsKey, AVURLAssetShouldSupportAliasDataReferencesKey,
};
use objc2_core_foundation::{CGPoint, CGRect, CGSize};
use objc2_core_graphics::{CGBitmapContextCreate, CGColorSpace, CGContext, CGImage, CGImageAlphaInfo, CGImageByteOrderInfo, kCGColorSpaceSRGB};
use objc2_core_media::{CMTime, CMTimeFlags};
use objc2_foundation::{NSDictionary, NSNumber, NSString, NSURL};
/// The source's lowercase extension, if any.
pub(in crate::video) fn extension(source: &MediaSource) -> Option<String> {
let name = match source {
MediaSource::File(path) => path.file_name()?.to_string_lossy().into_owned(),
MediaSource::Url(url) => {
let path = url.split(['?', '#']).next().unwrap_or_default();
// The last segment of the path, never the host.
let path = path.split_once("://").map_or(path, |(_, rest)| rest.split_once('/').map_or("", |(_, path)| path));
path.rsplit('/').next().unwrap_or_default().to_string()
}
};
Some(name.rsplit_once('.')?.1.to_ascii_lowercase()).filter(|ext| !ext.is_empty())
}
/// Audio in a container AVFoundation can't read, which `ogg-audio` decodes instead.
fn foreign_audio(source: &MediaSource, kind: Kind) -> bool {
cfg!(feature = "ogg-audio")
&& kind == Kind::Audio
&& extension(source).is_some_and(|ext| matches!(ext.as_str(), "ogg" | "oga" | "opus" | "webm" | "mka" | "mkv"))
}
/// AVFoundation has no Ogg, WebM or Matroska demuxer; fail at once rather than wait on a load
/// that can only fail.
pub(super) fn unsupported_format(source: &MediaSource, kind: Kind) -> Option<String> {
let ext = extension(source)?;
(!foreign_audio(source, kind) && matches!(ext.as_str(), "ogg" | "oga" | "ogv" | "opus" | "spx" | "webm" | "mkv" | "mka"))
.then(|| format!(".{ext} isn't supported on macOS (AVFoundation can't read it); use mp3, m4a, wav, mp4 or mov"))
}
fn url(source: &MediaSource) -> Result<Retained<NSURL>, String> {
match source {
MediaSource::File(path) => {
let meta = std::fs::metadata(path).map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound => format!("no such file: {}", path.display()),
_ => format!("can't open {}: {e}", path.display()),
})?;
if !meta.is_file() {
return Err(format!("not a file: {}", path.display()));
}
let path = std::path::absolute(path).unwrap_or_else(|_| path.clone());
Ok(NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy())))
}
MediaSource::Url(url) => {
let parsed = NSURL::URLWithString(&NSString::from_str(url)).ok_or_else(|| format!("invalid URL: {url}"))?;
if parsed.isFileURL()
&& let Some(host) = parsed.host()
{
let host = host.to_string();
if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") {
return Err(format!("unsupported file URL host: {url}"));
}
}
Ok(parsed)
}
}
}
/// Opens a local `file:` URL with `ForbidAll` reference restrictions so only media data stored
/// inside the container file itself is allowed. Apple's default (`ForbidLocalReferenceToRemote`)
/// leaves `ForbidLocalReferenceToLocal` off, allowing external QuickTime `dref` references to
/// read other local files.
fn local_asset(url: &NSURL) -> Retained<AVURLAsset> {
let restrictions = NSNumber::new_usize(AVAssetReferenceRestrictions::ForbidAll.0);
let aliases = NSNumber::new_bool(false);
let restrictions: &AnyObject = &restrictions;
let aliases: &AnyObject = &aliases;
// SAFETY: `AVURLAssetReferenceRestrictionsKey` (macOS 10.7+) and
// `AVURLAssetShouldSupportAliasDataReferencesKey` (macOS 10.10+) are immutable static
// AVFoundation string constants, and the values are live `NSNumber` objects.
let options = unsafe {
NSDictionary::<NSString, AnyObject>::from_slices(
&[AVURLAssetReferenceRestrictionsKey, AVURLAssetShouldSupportAliasDataReferencesKey],
&[restrictions, aliases],
)
};
// SAFETY: `url` is a live `NSURL` and `options` is a live `NSDictionary` of AVURLAsset options.
unsafe { AVURLAsset::URLAssetWithURL_options(url, Some(&options)) }
}
fn asset(source: &MediaSource, headers: &[(String, String)]) -> Result<Retained<AVURLAsset>, String> {
let url = url(source)?;
if matches!(source, MediaSource::File(_)) || url.isFileURL() {
return Ok(local_asset(&url));
}
if headers.is_empty() {
// SAFETY: `url` is a live `NSURL` and `URLAssetWithURL_options` accepts `None` for options.
return Ok(unsafe { AVURLAsset::URLAssetWithURL_options(&url, None) });
}
let names: Vec<_> = headers.iter().map(|(name, _)| NSString::from_str(name)).collect();
let values: Vec<_> = headers.iter().map(|(_, value)| NSString::from_str(value)).collect();
let fields = NSDictionary::from_slices(&names.iter().map(|n| &**n).collect::<Vec<_>>(), &values.iter().map(|v| &**v).collect::<Vec<_>>());
// Long-standing and widely used, though missing from AVFoundation's headers.
let key = NSString::from_str("AVURLAssetHTTPHeaderFieldsKey");
let fields: &AnyObject = &fields;
let options = NSDictionary::<NSString, AnyObject>::from_slices(&[&*key], &[fields]);
// SAFETY: `url` is a live `NSURL` and `options` is a live `NSDictionary` of HTTP header fields.
Ok(unsafe { AVURLAsset::URLAssetWithURL_options(&url, Some(&options)) })
}
/// Opens a clip and reads its facts, blocking. Audio AVFoundation can't read plays from a WAV
/// decoded from it: up front for a foreign extension, or when its own asset has no audio track
/// and its bytes are Ogg or WebM.
pub(super) fn open(source: &MediaSource, headers: &[(String, String)], kind: Kind, decoded: &Decoded) -> Result<(Retained<AVURLAsset>, Meta), String> {
let opened = |asset: Retained<AVURLAsset>| meta(&asset, kind).map(|meta| (asset, meta));
#[cfg(feature = "ogg-audio")]
{
let wav = |wav: &foreign::Wav| opened(asset(&MediaSource::File(wav.path().into()), &[])?);
if foreign_audio(source, kind) {
return match decoded.get_or_init(|| decode_foreign(source, headers, false)) {
Ok(Some(decoded)) => wav(decoded),
Ok(None) => Err("no Ogg or WebM audio".into()),
Err(e) => Err(e.clone()),
};
}
let own = opened(asset(source, headers)?);
if own.is_err() && kind == Kind::Audio {
match decoded.get_or_init(|| decode_foreign(source, headers, true)) {
Ok(Some(decoded)) => return wav(decoded),
// Ogg or WebM that didn't decode: say why, not that AVFoundation found nothing.
Err(e) => return Err(e.clone()),
Ok(None) => {}
}
}
own
}
#[cfg(not(feature = "ogg-audio"))]
{
let () = decoded;
opened(asset(source, headers)?)
}
}
/// The asset a player opens: the decoded WAV once there is one.
pub(super) fn player_asset(source: &MediaSource, headers: &[(String, String)], decoded: &Decoded) -> Result<Retained<AVURLAsset>, String> {
#[cfg(feature = "ogg-audio")]
if let Some(Ok(Some(wav))) = decoded.get() {
return asset(&MediaSource::File(wav.path().into()), &[]);
}
#[cfg(not(feature = "ogg-audio"))]
let () = decoded;
asset(source, headers)
}
/// Fetches a clip and decodes it to a WAV. When sniffing, bytes that aren't Ogg or WebM give
/// `None`, and a fetch that fails gives `None` too, leaving AVFoundation's error to report.
#[cfg(feature = "ogg-audio")]
fn decode_foreign(source: &MediaSource, headers: &[(String, String)], sniff: bool) -> Result<Option<foreign::Wav>, String> {
let bytes = match fetch(source, headers) {
Ok(bytes) => bytes,
Err(_) if sniff => return Ok(None),
Err(e) => return Err(e),
};
if sniff && !foreign::sniff(&bytes) {
return Ok(None);
}
foreign::Wav::decode(bytes).map(Some)
}
/// A clip's bytes: a file read, or a blocking fetch with its request headers.
#[cfg(feature = "ogg-audio")]
#[allow(deprecated)] // NSURLConnection's synchronous load is what a worker or headless run wants.
fn fetch(source: &MediaSource, headers: &[(String, String)]) -> Result<Vec<u8>, String> {
use objc2_foundation::{NSHTTPURLResponse, NSMutableURLRequest, NSURLConnection};
if let MediaSource::File(path) = source {
return std::fs::read(path).map_err(|e| format!("can't read {}: {e}", path.display()));
}
let request = NSMutableURLRequest::requestWithURL(&*url(source)?);
for (name, value) in headers {
request.setValue_forHTTPHeaderField(Some(&NSString::from_str(value)), &NSString::from_str(name));
}
let mut response = None;
let data = NSURLConnection::sendSynchronousRequest_returningResponse_error(&request, Some(&mut response))
.map_err(|e| e.localizedDescription().to_string())?;
let status = response.and_then(|r| r.downcast::<NSHTTPURLResponse>().ok()).map(|r| r.statusCode());
if let Some(status) = status.filter(|s| !(200..300).contains(s)) {
return Err(format!("HTTP {status}"));
}
Ok(data.to_vec())
}
pub(super) fn seconds(t: CMTime) -> f64 {
// SAFETY: `CMTimeGetSeconds` accepts any `CMTime` value and returns non-finite for invalid times.
let s = unsafe { t.seconds() };
if s.is_finite() { s } else { 0.0 }
}
pub(super) fn cm(seconds: f64) -> CMTime {
// SAFETY: `CMTimeMakeWithSeconds` accepts any `f64` and a positive timescale (`600_000`).
unsafe { CMTime::with_seconds(seconds, 600_000) }
}
pub(super) fn zero() -> CMTime {
CMTime { value: 0, timescale: 1, flags: CMTimeFlags::Valid, epoch: 0 }
}
/// Blocks until the asset's tracks load (a network fetch for URLs).
#[allow(deprecated)] // The synchronous loaders are what a worker or headless run wants.
fn meta(asset: &AVURLAsset, kind: Kind) -> Result<Meta, String> {
let duration = || {
// SAFETY: `asset` is a live `AVURLAsset` queried synchronously on a worker or headless thread.
seconds(unsafe { asset.duration() })
};
if kind == Kind::Audio {
// SAFETY: `AVMediaTypeAudio` is an immutable static AVFoundation string constant.
let audio = unsafe { AVMediaTypeAudio }.ok_or("AVMediaTypeAudio unavailable")?;
// SAFETY: `asset` is a live `AVURLAsset` and `audio` is the static `AVMediaTypeAudio` constant.
if unsafe { asset.tracksWithMediaType(audio) }.firstObject().is_none() {
return Err("no playable audio track (unreachable, or a format AVFoundation can't read)".into());
}
return Ok(Meta { duration: duration(), size: None, frame: 1.0 / 30.0, sound: true });
}
// SAFETY: `AVMediaTypeVideo` is an immutable static AVFoundation string constant.
let video = unsafe { AVMediaTypeVideo }.ok_or("AVMediaTypeVideo unavailable")?;
// SAFETY: `asset` is a live `AVURLAsset` and `video` is the static `AVMediaTypeVideo` constant.
let tracks = unsafe { asset.tracksWithMediaType(video) };
let Some(track) = tracks.firstObject() else {
return Err("no playable video track".into());
};
// SAFETY: `track` is a live `AVAssetTrack` retained from `tracks.firstObject()`.
let size = unsafe { track.naturalSize() };
// SAFETY: `track` is a live `AVAssetTrack` retained from `tracks.firstObject()`.
let t = unsafe { track.preferredTransform() };
let w = (size.width * t.a + size.height * t.c).abs().round();
let h = (size.width * t.b + size.height * t.d).abs().round();
// SAFETY: `track` is a live `AVAssetTrack` retained from `tracks.firstObject()`.
let min = seconds(unsafe { track.minFrameDuration() });
// SAFETY: `track` is a live `AVAssetTrack` retained from `tracks.firstObject()`.
let nominal = unsafe { track.nominalFrameRate() } as f64;
let frame = if min > 0.0 { min } else if nominal > 0.0 { 1.0 / nominal } else { 1.0 / 30.0 };
if w < 1.0 || h < 1.0 {
return Err("video track has no size".into());
}
Ok(Meta { duration: duration(), size: Some((w as u32, h as u32)), frame, sound: has_sound(asset) })
}
/// Whether the asset has a sound track. Blocks until its tracks load.
#[allow(deprecated)] // As `meta`: the synchronous loader.
pub(super) fn has_sound(asset: &AVAsset) -> bool {
// SAFETY: `AVMediaTypeAudio` is an immutable static AVFoundation string constant.
unsafe { AVMediaTypeAudio }.is_some_and(|audio| {
// SAFETY: `asset` is a live `AVAsset` and `audio` is the static `AVMediaTypeAudio` constant.
unsafe { asset.tracksWithMediaType(audio) }.firstObject().is_some()
})
}
/// How the first video track's buffers turn upright. Blocks until tracks load; free once an
/// item using the asset is ready to play.
#[allow(deprecated)]
pub(super) fn orient(asset: &AVAsset) -> Orient {
// SAFETY: `AVMediaTypeVideo` is an immutable static AVFoundation string constant.
let Some(video) = (unsafe { AVMediaTypeVideo }) else { return Orient::UP };
// SAFETY: `asset` is a live `AVAsset` and `video` is the static `AVMediaTypeVideo` constant.
let Some(track) = unsafe { asset.tracksWithMediaType(video) }.firstObject() else { return Orient::UP };
// SAFETY: `track` is a live `AVAssetTrack` retained from `tracksWithMediaType`.
let t = unsafe { track.preferredTransform() };
Orient::from_transform(t.a, t.b, t.c, t.d)
}
pub(super) fn generator(asset: &AVURLAsset, max: Option<f64>) -> Retained<AVAssetImageGenerator> {
// SAFETY: `asset` is a live `AVURLAsset`.
let g = unsafe { AVAssetImageGenerator::assetImageGeneratorWithAsset(asset) };
// SAFETY: `g` is a newly created, uniquely owned `AVAssetImageGenerator` not yet decoding.
unsafe {
g.setAppliesPreferredTrackTransform(true);
g.setRequestedTimeToleranceBefore(zero());
g.setRequestedTimeToleranceAfter(zero());
if let Some(max) = max {
g.setMaximumSize(CGSize::new(max, max));
}
}
g
}
#[allow(deprecated)] // copyCGImageAtTime is the synchronous form.
pub(super) fn image(generator: &AVAssetImageGenerator, at: f64) -> Result<ByteFrame, String> {
// SAFETY: `generator` is a live `AVAssetImageGenerator` and null `actualTime` is permitted by AVFoundation.
let image = unsafe { generator.copyCGImageAtTime_actualTime_error(cm(at), std::ptr::null_mut()) }
.map_err(|e| e.localizedDescription().to_string())?;
bgra(&image)
}
/// Draws a decoded image into sRGB BGRA bytes (opaque, so premultiplied equals straight).
fn bgra(image: &CGImage) -> Result<ByteFrame, String> {
let (w, h) = (CGImage::width(Some(image)), CGImage::height(Some(image)));
if w == 0 || h == 0 {
return Err("decoded an empty frame".into());
}
let mut bytes = vec![0u8; w * h * 4];
// SAFETY: `kCGColorSpaceSRGB` is an immutable static CoreGraphics color space name constant.
let space = CGColorSpace::with_name(Some(unsafe { kCGColorSpaceSRGB }));
let info = CGImageAlphaInfo::PremultipliedFirst.0 | CGImageByteOrderInfo::Order32Little.0;
// SAFETY: `bytes` has length `w * h * 4` matching 8 bpc BGRA with stride `w * 4`, and outlives `context`.
let context = unsafe { CGBitmapContextCreate(bytes.as_mut_ptr().cast(), w, h, 8, w * 4, space.as_deref(), info) }
.ok_or("CGBitmapContextCreate failed")?;
CGContext::draw_image(Some(&context), CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(w as f64, h as f64)), Some(image));
drop(context);
Ok(ByteFrame {
width: w as u32,
height: h as u32,
format: Format::Bgra,
color: ColorInfo { matrix: crate::native_surface::Matrix::Bt709, transfer: crate::native_surface::Transfer::Srgb },
planes: [bytes, Vec::new()],
})
}
pub(in crate::video) fn probe(native: &mut Native, source: &MediaSource, headers: &[(String, String)], kind: Kind) -> Result<Meta, String> {
let (asset, meta) = open(source, headers, kind, &native.decoded)?;
if kind == Kind::Video {
native.generator = Some(generator(&asset, None));
}
Ok(meta)
}
pub(in crate::video) fn decode(native: &mut Native, source: &MediaSource, headers: &[(String, String)], at: f64) -> Result<ByteFrame, String> {
if native.generator.is_none() {
let asset = asset(source, headers)?;
native.generator = Some(generator(&asset, None));
}
image(native.generator.as_ref().unwrap(), at)
}
/// A clip's frame at `at` upright (as posters and headless runs show it), and as its buffer
/// stores it (as the player hands it out) with how that turns upright.
#[cfg(test)]
pub(crate) fn test_frames(source: &MediaSource, at: f64) -> Result<(ByteFrame, ByteFrame, Orient), String> {
let asset = asset(source, &[])?;
let raw = generator(&asset, None);
// SAFETY: `raw` is a newly created, uniquely owned `AVAssetImageGenerator` not yet decoding.
unsafe { raw.setAppliesPreferredTrackTransform(false) };
Ok((image(&generator(&asset, None), at)?, image(&raw, at)?, orient(&asset)))
}
+374
View File
@@ -0,0 +1,374 @@
//! AVFoundation: AVPlayer + AVPlayerItemVideoOutput for windows, AVAssetImageGenerator for
//! posters and headless frames, and a bare AVPlayer for audio.
mod asset;
mod park;
mod port;
#[cfg(test)]
pub(super) use asset::extension;
#[cfg(test)]
pub(crate) use asset::test_frames;
pub(super) use asset::{decode, probe};
#[cfg(test)]
pub(super) use park::{held_capacity, on_kept, parked_free, parked_with};
use super::phases::{Effect, Event, step};
use super::turn::{self, Turn};
use super::{Control, Kind, Meta, Shared, playback_enabled};
use crate::native_surface::{ByteFrame, NativeSurface, Orient};
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_av_foundation::{AVAssetImageGenerator, AVPlayer, AVPlayerItem, AVPlayerItemVideoOutput};
use port::Av;
use rune_core::machine::{Attempt, Effects};
use rune_core::main_queue::on_main;
use rune_core::time::Instant;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, Weak};
use std::time::Duration;
/// Posters never need more than this many pixels per side; headless frames keep full size.
const POSTER_MAX: f64 = 1920.0;
/// How often playing audio checks for its end, loops and loading.
const AUDIO_TICK: Duration = Duration::from_millis(50);
#[derive(Default)]
pub(crate) struct Native {
/// Headless decodes reuse one generator.
pub(super) generator: Option<Retained<AVAssetImageGenerator>>,
pub(super) player: Option<Player>,
pub(super) posters: Arc<Mutex<Posters>>,
pub(super) decoded: Decoded,
}
/// Audio AVFoundation can't read, decoded once on the load worker (or a headless probe) to a WAV
/// it can, which every player for the clip then opens.
#[cfg(feature = "ogg-audio")]
pub(super) type Decoded = Arc<std::sync::OnceLock<Result<Option<super::foreign::Wav>, String>>>;
#[cfg(not(feature = "ogg-audio"))]
pub(super) type Decoded = ();
// SAFETY: the generator is only used under the Shared mutex. Player objects are created, used and
// released on the main thread: pulls and audio ticks run there and `Player`'s drop hops to it.
#[allow(unsafe_code)]
unsafe impl Send for Native {}
#[derive(Default)]
pub(super) struct Posters {
want: Option<(f64, Attempt)>,
busy: bool,
/// The asking attempt, and a video poster and its facts, or (no frame) an audio clip's facts.
pub(super) done: Option<(Attempt, Result<(Option<ByteFrame>, Meta), String>)>,
}
pub(super) struct Player {
// Some until dropped; `Drop` moves the objects to the main thread.
pub(super) objects: Option<Objects>,
/// Video: how its buffers turn upright (they ignore the track's `preferredTransform`).
pub(super) orient: Orient,
}
pub(super) struct Objects {
pub(super) player: Retained<AVPlayer>,
pub(super) item: Retained<AVPlayerItem>,
/// None for audio.
pub(super) output: Option<Retained<AVPlayerItemVideoOutput>>,
}
impl Player {
pub(super) fn new(objects: Objects) -> Self {
Self { objects: Some(objects), orient: Orient::UP }
}
}
impl Drop for Player {
#[allow(unsafe_code)]
fn drop(&mut self) {
let Some(objects) = self.objects.take() else { return };
if MainThreadMarker::new().is_some() {
// SAFETY: on the main thread (checked above) and `objects.player` is a live `AVPlayer`.
unsafe { objects.player.pause() };
return;
}
// The last handle went away on another thread: release on the main queue.
struct Release(Objects);
// SAFETY: `Release` only transfers `Objects` into `on_main` so `AVPlayer` is paused and dropped on the main thread.
unsafe impl Send for Release {}
let release = Release(objects);
on_main(move || {
let release = release; // Whole, so the closure is Send.
// SAFETY: dispatched onto the main queue where `AVPlayer` is owned, and `release.0.player` is live.
unsafe { release.0.player.pause() };
});
}
}
/// Every live audio player, for the tick.
static AUDIO: Mutex<Vec<Weak<Shared>>> = Mutex::new(Vec::new());
/// Some audio clip wants ticking. Written on the main thread.
static AUDIO_BUSY: AtomicBool = AtomicBool::new(false);
/// The tick thread is running.
static TICKING: AtomicBool = AtomicBool::new(false);
pub(super) fn created(shared: &Arc<Shared>) {
if let Some(e) = asset::unsupported_format(&shared.source, shared.kind) {
shared.ctl.lock().unwrap().fail(e);
return;
}
if shared.kind == Kind::Audio {
AUDIO.lock().unwrap().push(Arc::downgrade(shared));
if playback_enabled() {
load_audio(shared);
}
}
}
/// The window loop is starting: load audio clips made before it.
pub(super) fn enable() {
let clips: Vec<Arc<Shared>> = AUDIO.lock().unwrap().iter().filter_map(Weak::upgrade).collect();
for clip in clips {
load_audio(&clip);
on_main(move || drive(&clip));
}
}
/// Read an audio clip's duration on a worker, so tiles know it before they play.
fn load_audio(shared: &Arc<Shared>) {
let mut native = shared.native.lock().unwrap();
let mut c = shared.ctl.lock().unwrap();
let effects = step(&mut c, Event::LoadAudio);
drop(c);
ask_posters(shared, &mut native, effects);
}
/// Whether a poster decode has landed, and with a picture.
#[cfg(test)]
pub(crate) fn test_poster(shared: &Shared) -> Option<bool> {
let native = shared.native.lock().unwrap();
let posters = native.posters.lock().unwrap();
posters.done.as_ref().map(|(_, d)| matches!(d, Ok((Some(_), _))))
}
/// An app warming the page it shows next: decode the clip's first frame now, so the first frame
/// that draws it already has it. Nothing once a poster or player has started, or for audio.
pub(super) fn preload(shared: &Arc<Shared>) {
let mut native = shared.native.lock().unwrap();
let mut c = shared.ctl.lock().unwrap();
let effects = step(&mut c, Event::Preload);
drop(c);
ask_posters(shared, &mut native, effects);
}
/// Starts the worker for a load `step` asked for. Call without the control lock.
fn ask_posters(shared: &Arc<Shared>, native: &mut Native, effects: Effects<Effect>) {
for effect in effects {
if let Effect::AskPoster(at, attempt) = effect {
request_poster(shared, native, at, attempt);
}
}
}
/// One worker per clip opens it and decodes the newest requested poster (none for audio),
/// then wakes its windows, or for audio drives it on the main queue. Called only while no
/// player runs, so a video's poster may land.
fn request_poster(shared: &Arc<Shared>, native: &mut Native, at: f64, attempt: Attempt) {
let mut slot = native.posters.lock().unwrap();
slot.want = Some((at, attempt));
if slot.busy {
return;
}
slot.busy = true;
let posters = native.posters.clone();
let clip = Arc::downgrade(shared);
let (source, headers, kind, decoded) = (shared.source.clone(), shared.headers.clone(), shared.kind, native.decoded.clone());
std::thread::Builder::new()
.name("rune-media-poster".into())
.spawn(move || {
let mut opened: Option<(Option<Retained<AVAssetImageGenerator>>, Meta)> = None;
loop {
let Some((at, attempt)) = ({
let mut slot = posters.lock().unwrap();
let want = slot.want.take();
if want.is_none() {
slot.busy = false;
}
want
}) else {
return;
};
if clip.strong_count() == 0 {
return;
}
// AVFoundation autoreleases; this thread has no pool of its own.
let result = objc2::rc::autoreleasepool(|_| {
if opened.is_none() {
let (asset, meta) = asset::open(&source, &headers, kind, &decoded)?;
opened = Some(((kind == Kind::Video).then(|| asset::generator(&asset, Some(POSTER_MAX))), meta));
}
let (generator, meta) = opened.as_ref().unwrap();
let frame = match generator {
Some(g) => Some(asset::image(g, meta.frame_time(meta.frame_index(at)))?),
None => None,
};
Ok((frame, *meta))
});
posters.lock().unwrap().done = Some((attempt, result));
let Some(clip) = clip.upgrade() else { return };
match kind {
Kind::Video => clip.wake_windows(),
Kind::Audio => on_main(move || drive(&clip)),
}
}
})
.expect("spawn media poster worker");
}
/// Applies a handle edit at once on the main thread, so a paused, undrawn video stops (and goes
/// quiet) without waiting for a frame that draws it. Edits from other threads hop to it.
pub(super) fn apply(shared: &Arc<Shared>) {
if !playback_enabled() || shared.ctl.lock().unwrap().failed() {
return;
}
let Some(mtm) = MainThreadMarker::new() else {
let clip = Arc::downgrade(shared);
on_main(move || {
if let Some(clip) = clip.upgrade() {
apply(&clip);
}
});
return;
};
if shared.kind == Kind::Audio {
drive(shared);
return;
}
// Already being pulled further up this stack; that pull reconciles.
let Ok(mut native) = shared.native.try_lock() else { return };
if native.player.is_none() {
return;
}
let playing = {
let mut c = shared.ctl.lock().unwrap();
turn::reconcile(&mut c, &mut Av::new(shared, &mut native, Some(mtm), None), rune_core::time::now());
c.playing()
};
drop(native);
// A parked player that plays again must not be released.
if playing {
park::unpark(shared);
}
}
/// Audio, on the main thread: what a live player (`Control::live`) reports now, while it plays.
/// `live`: the player's own position is the one to read (`Control::live`).
#[allow(unsafe_code)]
pub(super) fn live_time(shared: &Shared, live: bool) -> Option<f64> {
if !live || shared.kind != Kind::Audio || MainThreadMarker::new().is_none() {
return None;
}
let native = shared.native.try_lock().ok()?;
let p = native.player.as_ref()?;
// SAFETY: on the main thread (checked above) under `shared.native` lock; `player` is a live `AVPlayer`.
let time = asset::seconds(unsafe { p.objects.as_ref()?.player.currentTime() });
let c = shared.ctl.lock().unwrap();
c.playing().then(|| c.duration.map_or(time, |d| time.clamp(0.0, d)))
}
pub(super) fn pull(shared: &Arc<Shared>, surface: &NativeSurface, target: Instant) -> bool {
let now = rune_core::time::now();
let mut native = shared.native.lock().unwrap();
let mut c = shared.ctl.lock().unwrap();
let mut av = Av::new(shared, &mut native, None, Some((surface, target)));
let turn = turn::turn(&mut c, &mut av, now);
let asked = av.asked;
finish(shared, native, c, turn, asked)
}
/// The display link draws a playing clip every refresh.
pub(super) fn due(_: &Shared) -> Option<Instant> {
None
}
/// Poster requests and parking, shared by video pulls and audio drives. Returns whether the
/// clip is playing, seeking or loading (a seek waits for it).
fn finish(shared: &Arc<Shared>, mut native: MutexGuard<'_, Native>, c: MutexGuard<'_, Control>, turn: Turn, asked: Option<(f64, Attempt)>) -> bool {
match turn {
Turn::Idle => {
drop(c);
if let Some((at, attempt)) = asked {
request_poster(shared, &mut native, at, attempt);
}
false
}
Turn::Loading => true,
Turn::Finished => {
let (active, should_park) = (c.active(), c.parkable());
drop(c);
drop(native);
if should_park { park::park(shared) } else { park::unpark(shared) }
active
}
}
}
/// Audio, on the main thread: take a finished load, make or update the player, follow it to
/// the end, tell the app about changes, and keep the tick going while it plays or seeks.
pub(super) fn drive(shared: &Arc<Shared>) {
if step_audio(shared) {
AUDIO_BUSY.store(true, Ordering::SeqCst);
start_ticking();
}
shared.settle(true);
}
/// Returns whether the clip needs ticking.
fn step_audio(shared: &Arc<Shared>) -> bool {
let Some(mtm) = MainThreadMarker::new() else { return false };
let now = rune_core::time::now();
// Already being driven further up this stack (a waker that edits the clip).
let Ok(mut native) = shared.native.try_lock() else { return true };
let mut c = shared.ctl.lock().unwrap();
let mut av = Av::new(shared, &mut native, Some(mtm), None);
let turn = turn::turn(&mut c, &mut av, now);
let asked = av.asked;
finish(shared, native, c, turn, asked)
}
/// Main thread: drive every audio clip that might be playing.
fn tick() {
let clips: Vec<Arc<Shared>> = {
let mut audio = AUDIO.lock().unwrap();
audio.retain(|w| w.strong_count() > 0);
audio.iter().filter_map(Weak::upgrade).collect()
};
let mut busy = false;
for clip in &clips {
busy |= step_audio(clip);
clip.settle(true);
}
AUDIO_BUSY.store(busy, Ordering::SeqCst);
}
/// A thread that posts `tick` to the main queue every `AUDIO_TICK` while audio is busy.
fn start_ticking() {
// SeqCst throughout: each side stores one flag, then loads the other.
if TICKING.swap(true, Ordering::SeqCst) {
return;
}
std::thread::Builder::new()
.name("rune-audio-tick".into())
.spawn(|| {
loop {
std::thread::sleep(AUDIO_TICK);
if !AUDIO_BUSY.load(Ordering::SeqCst) {
TICKING.store(false, Ordering::SeqCst);
// Something started between the check and the store: keep going if no
// other ticker took over.
if !AUDIO_BUSY.load(Ordering::SeqCst) || TICKING.swap(true, Ordering::SeqCst) {
return;
}
}
on_main(tick);
}
})
.expect("spawn audio tick");
}
@@ -0,0 +1,101 @@
//! Parked paused player pool: keeps at most `PARKED_PLAYERS` native players for fast resume
//! and evicts the oldest without dropping clip owners while holding the pool lock.
use crate::video::Shared;
use crate::video::phases::{Event, step};
use std::sync::{Arc, Mutex, Weak};
/// Paused players that keep a native player (and its decoder) for a quick resume. Older paused
/// players are released; a video's last frame stays on screen and resuming recreates it.
const PARKED_PLAYERS: usize = 4;
/// Paused players holding a native player, oldest first.
static PARKED: Mutex<Vec<Weak<Shared>>> = Mutex::new(Vec::new());
pub(super) fn unpark(shared: &Arc<Shared>) {
PARKED.lock().unwrap().retain(|w| w.strong_count() > 0 && !std::ptr::eq(w.as_ptr(), Arc::as_ptr(shared)));
}
/// Keep at most `PARKED_PLAYERS` paused players; release the oldest. Main thread only.
pub(super) fn park(shared: &Arc<Shared>) {
for clip in parked_with(shared) {
// A video's last frame stays on its surface; resuming recreates the player.
let player = {
let mut native = clip.native.lock().unwrap();
step(&mut clip.ctl.lock().unwrap(), Event::Parked);
native.player.take()
};
drop(player);
}
}
/// Parks `shared` and returns the clips to release: the oldest past `PARKED_PLAYERS`. A clip
/// that plays again (before its next pull unparks it) leaves the list and is never released.
pub(in crate::video) fn parked_with(shared: &Arc<Shared>) -> Vec<Arc<Shared>> {
// A clip being edited on another thread right now counts as playing.
let playing = |clip: &Shared| clip.ctl.try_lock().map_or(true, |c| c.playing());
// Every upgrade outlives PARKED: dropping the last owner here would run the clip's
// destructor, its app waker captures possibly playing another parked clip and re-entering
// unpark. The buffer is taken out for the pass, so it keeps its capacity and a pass over a
// parked clip that changes nothing allocates nothing.
let mut held = HELD.with(|slot| std::mem::take(&mut *slot.borrow_mut()));
let mut parked = PARKED.lock().unwrap();
parked.retain(|w| match w.upgrade() {
Some(clip) => {
let keep = Arc::ptr_eq(&clip, shared) || !playing(&clip);
held.push(clip);
#[cfg(test)]
kept();
keep
}
None => false,
});
if !parked.iter().any(|w| std::ptr::eq(w.as_ptr(), Arc::as_ptr(shared))) {
parked.push(Arc::downgrade(shared));
}
let excess = parked.len().saturating_sub(PARKED_PLAYERS);
let released = parked.drain(..excess).filter_map(|w| w.upgrade()).collect();
drop(parked);
// The last owners drop here, after the lock. Empty rather than dropped, so the capacity
// survives: a destructor that parks again on this thread gets the empty buffer.
held.clear();
HELD.with(|slot| *slot.borrow_mut() = held);
released
}
thread_local! {
/// The parking pass's upgraded owners, kept between passes so a warm redraw allocates nothing.
static HELD: std::cell::RefCell<Vec<Arc<Shared>>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Test-only: the scratch buffer's capacity, which a pass that allocates nothing leaves alone.
#[cfg(test)]
pub(in crate::video) fn held_capacity() -> usize {
HELD.with(|slot| slot.borrow().capacity())
}
/// Test-only: runs once inside the next parking pass, while PARKED is held, so a test can drop a
/// clip's last owner at the moment the pass holds an upgrade.
#[cfg(test)]
pub(in crate::video) fn on_kept(hook: impl FnOnce() + 'static) {
KEPT.with(|slot| *slot.borrow_mut() = Some(Box::new(hook)));
}
#[cfg(test)]
thread_local! {
static KEPT: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
}
#[cfg(test)]
fn kept() {
let hook = KEPT.with(|slot| slot.borrow_mut().take());
if let Some(hook) = hook {
hook();
}
}
/// Test-only: whether PARKED is free right now, without waiting for it.
#[cfg(test)]
pub(in crate::video) fn parked_free() -> bool {
PARKED.try_lock().is_ok()
}
@@ -0,0 +1,235 @@
//! `AVPlayer` + `AVPlayerItemVideoOutput` construction and the `turn::Port` adapter (`Av`).
#![allow(unsafe_code)]
use super::{Decoded, Native, Objects, Player, asset, park};
use crate::native_surface::macos::PixelBuffer;
use crate::native_surface::{ByteFrame, NativeSurface};
use crate::video::phases::Item;
use crate::video::turn::Port;
use crate::video::{Kind, MediaSource, Meta, Shared};
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2::{AnyThread, MainThreadMarker};
use objc2_av_foundation::{AVPlayer, AVPlayerItem, AVPlayerItemStatus, AVPlayerItemVideoOutput};
use objc2_core_foundation::{CFBoolean, CFDictionary, CFNumber, CFRetained, CFString, CFType};
use objc2_core_video::{
CVGetCurrentHostTime, CVGetHostClockFrequency, kCVPixelBufferIOSurfacePropertiesKey, kCVPixelBufferMetalCompatibilityKey,
kCVPixelBufferPixelFormatTypeKey, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
};
use objc2_foundation::{NSDictionary, NSString};
use rune_core::machine::Attempt;
use rune_core::time::Instant;
use std::sync::Arc;
fn create_player(source: &MediaSource, headers: &[(String, String)], kind: Kind, decoded: &Decoded, mtm: MainThreadMarker) -> Result<Objects, String> {
let asset = asset::player_asset(source, headers, decoded)?;
// SAFETY: `asset` is a live `AVURLAsset` and `mtm` proves we are on the main thread.
let item = unsafe { AVPlayerItem::playerItemWithAsset(&asset, mtm) };
let output = (kind == Kind::Video).then(|| {
let empty = CFDictionary::<CFString, CFType>::from_slices(&[], &[]);
let format = CFNumber::new_i32(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange as i32);
// SAFETY: the three `kCVPixelBuffer*` keys are immutable static `CFString` constants and values are live `CFType`s.
let attributes = unsafe {
CFDictionary::<CFString, CFType>::from_slices(
&[kCVPixelBufferPixelFormatTypeKey, kCVPixelBufferIOSurfacePropertiesKey, kCVPixelBufferMetalCompatibilityKey],
&[format.as_ref(), AsRef::<CFType>::as_ref(&*empty), CFBoolean::new(true).as_ref()],
)
};
// SAFETY: `CFDictionary` and `NSDictionary` are toll-free bridged, and the reference does not outlive `attributes`.
let attributes = unsafe { &*(CFRetained::as_ptr(&attributes).as_ptr() as *const NSDictionary<NSString, AnyObject>) };
// SAFETY: `attributes` is a valid pixel-buffer dictionary, `output` is freshly allocated, and `item` is a live `AVPlayerItem` on the main thread.
unsafe {
let output = AVPlayerItemVideoOutput::initWithPixelBufferAttributes(AVPlayerItemVideoOutput::alloc(), Some(attributes));
output.setSuppressesPlayerRendering(true);
item.addOutput(&output);
output
}
});
// SAFETY: `item` is a live `AVPlayerItem` and `mtm` proves we are on the main thread.
let player = unsafe { AVPlayer::playerWithPlayerItem(Some(&item), mtm) };
Ok(Objects { player, item, output })
}
/// Seconds on the host clock (`CACurrentMediaTime`'s) for an `Instant`.
fn host_seconds(at: Instant) -> f64 {
let now = rune_core::time::now();
let host = CVGetCurrentHostTime() as f64 / CVGetHostClockFrequency();
if at >= now { host + (at - now).as_secs_f64() } else { host - (now - at).as_secs_f64() }
}
/// A clip's native side for one turn, with its locks held. Reads and does what it's asked.
pub(super) struct Av<'a> {
shared: &'a Arc<Shared>,
native: &'a mut Native,
/// Filled by the caller that already checked, or by the turn when it first needs to know.
mtm: Option<MainThreadMarker>,
/// Video, during a pull: the surface and the presentation time its frame is for.
target: Option<(&'a NativeSurface, Instant)>,
/// A finished poster load's frame.
poster: Option<ByteFrame>,
/// A poster the turn asked for, started once the control lock is released.
pub(super) asked: Option<(f64, Attempt)>,
}
impl<'a> Av<'a> {
pub(super) fn new(
shared: &'a Arc<Shared>,
native: &'a mut Native,
mtm: Option<MainThreadMarker>,
target: Option<(&'a NativeSurface, Instant)>,
) -> Self {
Self { shared, native, mtm, target, poster: None, asked: None }
}
fn player(&mut self) -> &mut Player {
self.native.player.as_mut().unwrap()
}
fn objects(&self) -> &Objects {
self.native.player.as_ref().unwrap().objects.as_ref().unwrap()
}
}
impl Port for Av<'_> {
fn on_main(&mut self) -> bool {
self.mtm = self.mtm.or_else(MainThreadMarker::new);
self.mtm.is_some()
}
fn take_poster(&mut self) -> Option<(Attempt, Result<Meta, String>)> {
let (attempt, done) = self.native.posters.lock().unwrap().done.take()?;
Some((attempt, done.map(|(bytes, meta)| {
self.poster = bytes;
meta
})))
}
fn show_poster(&mut self, next_id: &mut dyn FnMut() -> u64) -> Result<(), String> {
let (Some(bytes), Some((surface, _))) = (self.poster.take(), self.target) else { return Ok(()) };
surface.push_bytes(bytes, next_id())
}
fn ask_poster(&mut self, at: f64, attempt: Attempt) {
self.asked = Some((at, attempt));
}
fn make_player(&mut self) -> Result<Instant, String> {
let shared = self.shared;
let objects = create_player(&shared.source, &shared.headers, shared.kind, &self.native.decoded, self.mtm.unwrap())?;
self.native.player = Some(Player::new(objects));
Ok(rune_core::time::now())
}
fn drop_player(&mut self) {
self.native.player = None;
}
fn unpark(&mut self) {
park::unpark(self.shared);
}
fn item(&self) -> Item {
let item = &self.objects().item;
// SAFETY: `item` is a live `AVPlayerItem` accessed on the main thread under `shared.native`.
let status = unsafe { item.status() };
if status == AVPlayerItemStatus::Failed {
// SAFETY: `item` is a live `AVPlayerItem` in `Failed` status accessed on the main thread.
let error = unsafe { item.error() };
Item::Failed(error.map_or_else(|| "playback failed".into(), |e| e.localizedDescription().to_string()))
} else if status == AVPlayerItemStatus::ReadyToPlay {
Item::Ready
} else {
Item::Loading
}
}
fn orient(&mut self) {
let o = self.objects();
if o.output.is_some() {
// SAFETY: `o.item` is a live `AVPlayerItem` accessed on the main thread.
let asset = unsafe { o.item.asset() };
let orient = asset::orient(&asset);
self.player().orient = orient;
}
}
fn item_facts(&self) -> Meta {
let item = &self.objects().item;
// SAFETY: `item` is a live `AVPlayerItem` accessed on the main thread.
let size = unsafe { item.presentationSize() };
// SAFETY: `item` is a live `AVPlayerItem` accessed on the main thread.
let duration = asset::seconds(unsafe { item.duration() });
let size = (size.width >= 1.0 && size.height >= 1.0).then(|| (size.width.round() as u32, size.height.round() as u32));
// SAFETY: `item` is a live `AVPlayerItem` accessed on the main thread.
let asset = unsafe { item.asset() };
Meta { duration, size, frame: 1.0 / 30.0, sound: asset::has_sound(&asset) }
}
fn alive(&self) -> bool {
self.native.player.as_ref().is_some_and(|p| p.objects.is_some())
}
fn set_muted(&mut self, muted: bool) {
// SAFETY: `player` is a live `AVPlayer` accessed on the main thread.
unsafe { self.objects().player.setMuted(muted) };
}
fn set_volume(&mut self, volume: f32) {
// SAFETY: `player` is a live `AVPlayer` accessed on the main thread.
unsafe { self.objects().player.setVolume(volume) };
}
fn seek_to(&mut self, at: f64) {
// SAFETY: `player` is a live `AVPlayer` accessed on the main thread with valid `CMTime` values.
unsafe { self.objects().player.seekToTime_toleranceBefore_toleranceAfter(asset::cm(at), asset::zero(), asset::zero()) };
}
fn set_rate(&mut self, rate: f32) {
let player = &self.objects().player;
// SAFETY: `player` is a live `AVPlayer` accessed on the main thread.
unsafe { if rate > 0.0 { player.setRate(rate) } else { player.pause() } };
}
fn restart(&mut self, rate: f32) {
let player = &self.objects().player;
// SAFETY: `player` is a live `AVPlayer` accessed on the main thread with valid `CMTime` values.
unsafe {
player.seekToTime_toleranceBefore_toleranceAfter(asset::zero(), asset::zero(), asset::zero());
player.setRate(rate);
}
}
fn frame(&mut self, next_id: &mut dyn FnMut() -> u64) -> (f64, Result<Option<f64>, String>) {
let (surface, target) = self.target.unwrap();
let p = self.native.player.as_ref().unwrap();
let output = p.objects.as_ref().unwrap().output.as_ref().unwrap();
// SAFETY: `output` is a live `AVPlayerItemVideoOutput` attached to this player's item.
let item_time = unsafe { output.itemTimeForHostTime(host_seconds(target)) };
let mut shown = item_time;
let mut landed = Ok(None);
// SAFETY: `output` is a live `AVPlayerItemVideoOutput` and `item_time` came from `itemTimeForHostTime`.
if unsafe { output.hasNewPixelBufferForItemTime(item_time) }
&& let Some(buffer) =
// SAFETY: `output` is live and `&mut shown` is a valid writable `CMTime` out-pointer.
unsafe { output.copyPixelBufferForItemTime_itemTimeForDisplay(item_time, &mut shown) }
{
let id = next_id();
// SAFETY: AVPlayerItemVideoOutput hands out finished buffers it no longer writes.
let pushed = unsafe { PixelBuffer::from_raw(Retained::as_ptr(&buffer) as *mut _) }
.and_then(|b| surface.push_oriented(b, id, p.orient));
landed = pushed.map(|_| Some(asset::seconds(shown)));
}
(asset::seconds(item_time), landed)
}
fn current(&self) -> f64 {
// SAFETY: `player` is a live `AVPlayer` accessed on the main thread.
asset::seconds(unsafe { self.objects().player.currentTime() })
}
fn stopped(&mut self) -> bool {
// SAFETY: `player` is a live `AVPlayer` accessed on the main thread.
unsafe { self.objects().player.rate() == 0.0 }
}
}
+766
View File
@@ -0,0 +1,766 @@
//! Media playback: a cheap, cloneable [`Player`] handle for video drawn into a
//! [`NativeSurface`], or for audio with no element at all.
//!
//! The handle only records intent (play, pause, seek, rate, looping, muted).
//!
//! Video: each frame that draws the element reconciles that intent with the platform player on
//! the UI thread and pulls the frame for the frame's presentation time, so a paused or hidden
//! video costs nothing per frame. On macOS, AVPlayer + AVPlayerItemVideoOutput pull
//! IOSurface-backed `CVPixelBuffer`s for the display link's target time, zero-copy. Until a
//! video first plays, and after its player is parked, it shows a poster frame decoded on a
//! worker thread, with no player or decoder session held.
//!
//! Audio ([`Player::audio`]): no surface and no frames. In a window, edits apply on the main
//! thread at once, and a 20 Hz main-queue tick runs only while some clip plays, loads to play
//! or seeks, to notice the end, loop and loading. Nothing redraws for it: apps read
//! [`Player::time`] on their own frames (see [`Player::set_waker`]).
//!
//! Headless runs (virtual clock) never create a player and never make sound. Video decodes the
//! frame at its virtual time synchronously, so `--snap` and `--frames` are deterministic: time
//! starts on the first frame that draws the element after `play`, and advances by the runtime
//! clock times `rate`. Audio opens synchronously on the first read of its state, duration or
//! time (or on a frame once it plays), and its time follows the clock of the runtime stepping
//! on the thread that made it, from the first frame or edit after `play`: pausing, seeking,
//! rate, looping and the end (which wakes the app's waker) all as in a window, silently.
//!
//! On Windows, Media Foundation decodes on a thread per clip, on the GPU where it can, into
//! shared NV12 textures Rune samples in place; WASAPI plays the sound (`windows`).
//!
//! Other platforms report [`PlayerState::Failed`] and draw a neutral placeholder for video.
#[cfg(all(target_os = "macos", feature = "ogg-audio"))]
mod foreign;
#[cfg(target_os = "macos")]
mod macos;
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
mod phases;
#[cfg(target_os = "macos")]
use macos as backend;
#[cfg(all(test, target_os = "macos"))]
pub(crate) use macos::test_frames;
#[cfg(any(target_os = "macos", test))]
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
mod turn;
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
mod unsupported;
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
use unsupported as backend;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
use self::windows as backend;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub use self::windows::LayerStatus;
#[cfg(target_os = "windows")]
pub(crate) use self::windows::release_removed_device;
mod waker;
use phases::{Effect, Event, Run, Stage, step};
pub(crate) use waker::WakerSlot;
use crate::native_surface::{ByteFrame, ColorInfo, Format, NativeSurface};
use rune_core::machine::Seq;
use rune_core::time::Instant;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, Weak};
/// A playing clip whose next picture is due sooner than this (seconds) draws every refresh;
/// later, the window sleeps until then.
#[doc(hidden)]
pub const WAKE_MIN: f64 = 0.002;
/// The platform player's entry points that a window reaches through a clip it draws, called through
/// the clip so that only an app that makes a [Player] links them (the decoder, the audio
/// stream, Media Foundation): a window links this module's code whether or not it ever draws video.
pub(crate) struct Backend {
probe: fn(&mut backend::Native, &MediaSource, &[(String, String)], Kind) -> Result<Meta, String>,
decode: fn(&mut backend::Native, &MediaSource, &[(String, String)], f64) -> Result<ByteFrame, String>,
drive: fn(&Arc<Shared>),
pull: fn(&Arc<Shared>, &NativeSurface, Instant) -> bool,
due: fn(&Shared) -> Option<Instant>,
#[cfg(target_os = "windows")]
layer: fn(&Arc<Shared>, Option<(u32, u32)>) -> LayerStatus,
#[cfg(target_os = "windows")]
unlayer: fn(&Arc<Shared>, &NativeSurface),
}
static BACKEND: Backend = Backend {
probe: backend::probe,
decode: backend::decode,
drive: backend::drive,
pull: backend::pull,
due: backend::due,
#[cfg(target_os = "windows")]
layer: backend::layer,
#[cfg(target_os = "windows")]
unlayer: backend::unlayer,
};
/// Windows: shows shared's video in a compositor layer, or (None) asks for none.
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub fn layer(shared: &Arc<Shared>, ask: Option<(u32, u32)>) -> LayerStatus { (shared.backend.layer)(shared, ask) }
/// Windows: takes shared's video out of its compositor layer, back to surface.
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub fn unlayer(shared: &Arc<Shared>, surface: &NativeSurface) { (shared.backend.unlayer)(shared, surface) }
/// Set once a window event loop runs. Until then (headless runs, tests) no player is created.
static PLAYBACK: AtomicBool = AtomicBool::new(false);
/// Called by the windowed shell before its event loop starts.
#[doc(hidden)]
pub fn enable_playback() {
if !PLAYBACK.swap(true, Ordering::AcqRel) {
backend::enable();
}
}
pub(crate) fn playback_enabled() -> bool {
PLAYBACK.load(Ordering::Acquire)
}
/// Headless: the clock of the runtime stepping on this thread, and the audio clips made here.
#[derive(Default)]
struct Headless {
clock: Option<f64>,
audio: Vec<Weak<Shared>>,
}
thread_local! {
static HEADLESS: std::cell::RefCell<Headless> = std::cell::RefCell::default();
}
/// A headless runtime starts a frame at `clock`: audio clips made on this thread follow it,
/// and the app's waker hears one end.
#[doc(hidden)]
pub fn headless_frame(clock: f64) {
let clips: Vec<Arc<Shared>> = HEADLESS.with_borrow_mut(|h| {
h.clock = Some(clock);
h.audio.retain(|w| w.strong_count() > 0);
h.audio.iter().filter_map(Weak::upgrade).collect()
});
for clip in clips {
clip.follow_clock();
}
}
/// A new runtime on this thread starts its clock at 0, replacing an earlier runtime's.
#[doc(hidden)]
pub fn headless_reset() {
HEADLESS.with_borrow_mut(|h| h.clock = Some(0.0));
}
/// Never panics, so destructors can ask (`None` while the thread's storage is torn down).
pub(crate) fn headless_clock() -> Option<f64> {
HEADLESS.try_with(|h| h.try_borrow().ok().and_then(|h| h.clock)).ok().flatten()
}
/// Where media comes from. Strings containing `://` are URLs; anything else is a file path.
///
/// Local file sources ([`MediaSource::File`] and `file:` URLs) open strictly as self-contained
/// local media files: macOS forbids external references (`AVAssetReferenceRestrictions::ForbidAll`),
/// and Windows requires a plain local disk path with a direct media container extension and
/// resolves it from a local byte stream without wildcard handler fallback. Network `http(s)://`
/// URLs keep URL resolution unchanged.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MediaSource {
File(PathBuf),
Url(String),
}
impl From<&str> for MediaSource {
fn from(s: &str) -> Self {
if s.contains("://") { Self::Url(s.into()) } else { Self::File(s.into()) }
}
}
impl From<String> for MediaSource {
fn from(s: String) -> Self {
if s.contains("://") { Self::Url(s) } else { Self::File(s.into()) }
}
}
impl From<PathBuf> for MediaSource {
fn from(path: PathBuf) -> Self {
Self::File(path)
}
}
impl From<&Path> for MediaSource {
fn from(path: &Path) -> Self {
Self::File(path.into())
}
}
/// A media URL with HTTP request headers, for clips behind authentication. Build it with
/// [`Player::request`], then make the player with [`audio`](Self::audio) or
/// [`video`](Self::video). Every request the player makes for the clip sends the headers.
/// Header values never appear in `Debug` output or logs.
///
/// ```no_run
/// let token = "…";
/// let clip = rune_media::Player::request("https://example.com/media/clip.m4a")
/// .header("Authorization", format!("Bearer {token}"))
/// .audio();
/// clip.play();
/// ```
#[derive(Clone)]
pub struct MediaRequest {
url: String,
headers: Vec<(String, String)>,
}
impl std::fmt::Debug for MediaRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let names: Vec<&str> = self.headers.iter().map(|(name, _)| name.as_str()).collect();
f.debug_struct("MediaRequest").field("url", &self.url).field("headers", &names).finish()
}
}
impl MediaRequest {
/// Adds a header sent with every request for the clip. A repeated name replaces the earlier
/// value.
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
let (name, value) = (name.into(), value.into());
self.headers.retain(|(n, _)| !n.eq_ignore_ascii_case(&name));
self.headers.push((name, value));
self
}
/// An audio clip, as [`Player::audio`].
pub fn audio(self) -> Player {
Player::create(MediaSource::Url(self.url), Kind::Audio, self.headers)
}
/// A video, muted, as [`Player::url`].
pub fn video(self) -> Player {
Player::create(MediaSource::Url(self.url), Kind::Video, self.headers)
}
}
/// Playback state. Video reports it as of the last frame that drew it; audio as of its last
/// tick or edit.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PlayerState {
/// Opening the source (and, for video, decoding its first frame).
Loading,
/// Loaded and paused.
Ready,
Playing,
/// Reached the end without looping. `play` starts again from the beginning.
Ended,
Failed(String),
}
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Video,
Audio,
}
/// A video or audio clip. Clones share one player; dropping the last clone (and, for video,
/// every element showing it) stops and frees it. Video starts muted; audio starts unmuted.
///
/// ```ignore
/// let clip = rune::Player::file("capture.mov");
/// clip.set_looping(true);
/// clip.play();
/// // In a view: size the element to the clip's aspect ratio once it is known.
/// let (w, h) = clip.natural_size().unwrap_or((16, 9));
/// let player = rune::el().w(480.0).h(480.0 * h as f32 / w as f32)
/// .video(&clip, rune::SurfaceFit::Fit);
///
/// let tap = rune::Player::audio("sounds/tap.m4a");
/// tap.play(); // audible: audio isn't muted
/// let progress = tap.time() / tap.duration().unwrap_or(1.0);
/// ```
#[derive(Clone)]
pub struct Player {
surface: NativeSurface,
shared: Arc<Shared>,
}
/// [`Player`], named for the element builder it pairs with (`El::video`).
pub type Video = Player;
impl std::fmt::Debug for Player {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let c = self.shared.ctl.lock().unwrap();
f.debug_struct("Player")
.field("kind", &self.shared.kind)
.field("source", &self.shared.source)
.field("state", &c.state())
.field("time", &c.time)
.finish_non_exhaustive()
}
}
impl Player {
/// A video, muted.
pub fn new(source: MediaSource) -> Self {
Self::create(source, Kind::Video, Vec::new())
}
/// A local movie file (mp4, mov; H.264 or HEVC), muted.
pub fn file(path: impl Into<PathBuf>) -> Self {
Self::new(MediaSource::File(path.into()))
}
/// A video at an `http(s)://` or `file://` URL, muted.
pub fn url(url: impl Into<String>) -> Self {
Self::new(MediaSource::Url(url.into()))
}
/// An audio clip (mp3, m4a/AAC, wav, aiff, flac; Ogg Vorbis, Ogg Opus and WebM Opus with
/// the default `ogg-audio` feature) from a path or URL, unmuted. It plays without any
/// element, draws nothing and pulls no frames.
pub fn audio(source: impl Into<MediaSource>) -> Self {
Self::create(source.into(), Kind::Audio, Vec::new())
}
/// A URL to open with request headers: `Player::request(url).header(name, value).audio()`
/// (or `.video()`). See [`MediaRequest`].
pub fn request(url: impl Into<String>) -> MediaRequest {
MediaRequest { url: url.into(), headers: Vec::new() }
}
fn create(source: MediaSource, kind: Kind, headers: Vec<(String, String)>) -> Self {
let ctl = Control { muted: kind == Kind::Video, kind, ..Control::default() };
let shared = Arc::new(Shared {
source,
headers,
kind,
ctl: Mutex::new(ctl),
wakes: Mutex::new(Vec::new()),
waker: WakerSlot::default(),
notified: AtomicU64::new(0),
native: Mutex::new(backend::Native::default()),
backend: &BACKEND,
});
backend::created(&shared);
if kind == Kind::Audio && !playback_enabled() {
HEADLESS.with_borrow_mut(|h| h.audio.push(Arc::downgrade(&shared)));
}
Self { surface: NativeSurface::with_video(shared.clone()), shared }
}
pub fn source(&self) -> &MediaSource {
&self.shared.source
}
/// Whether this is an audio-only player from [`Player::audio`].
pub fn is_audio(&self) -> bool {
self.shared.kind == Kind::Audio
}
/// Decode the first frame now, off the main thread, so the first frame that draws this clip
/// shows it rather than an empty box: for the page an app expects to show next. Headless
/// runs decode frames as they draw, so there it does nothing.
pub fn preload(&self) {
if playback_enabled() {
backend::preload(&self.shared);
}
}
/// Start or resume playback. After [`PlayerState::Ended`] it starts from the beginning.
pub fn play(&self) {
self.send(Event::Play);
}
pub fn pause(&self) {
self.send(Event::Pause);
}
/// Jump to `seconds` (clamped to the clip). Keeps playing if it was playing.
pub fn seek(&self, seconds: f64) {
self.send(Event::Seek(seconds));
}
/// Playback speed while playing; 1 is normal. Negative and non-finite rates are ignored.
pub fn set_rate(&self, rate: f32) {
if rate.is_finite() && rate > 0.0 {
self.send(Event::Rate(rate));
}
}
pub fn set_looping(&self, looping: bool) {
self.edit(|c| c.looping = looping);
}
/// Sound plays only while unmuted. Videos start muted, audio clips unmuted.
pub fn set_muted(&self, muted: bool) {
self.edit(|c| c.muted = muted);
}
/// The sound's gain while unmuted, from 0 (silent) to 1 (as recorded, the default).
/// Non-finite values are ignored.
pub fn set_volume(&self, volume: f32) {
if volume.is_finite() {
self.edit(|c| c.volume = volume.clamp(0.0, 1.0));
}
}
/// Called, from any thread, when the state changes: loaded, ended, failed, or started
/// again by a loop. Hand it the app's `setup` waker so `poll` sees an audio clip end
/// without ticking. Nothing calls it for progress. If the state already changed (loaded, or
/// failed at once on an unsupported format), it's called once right away.
pub fn set_waker(&self, waker: rune_core::Waker) {
self.shared.waker.set(waker);
self.shared.settle(false);
}
pub fn state(&self) -> PlayerState {
self.read().state()
}
/// Whether `play` is in effect (also true while loading after `play`).
pub fn is_playing(&self) -> bool {
self.shared.ctl.lock().unwrap().playing()
}
/// Playback position in seconds. Video: as of the last drawn frame (or the last `seek`).
/// Audio: read from the player when called on the main thread while it plays.
pub fn time(&self) -> f64 {
let (time, live) = {
let c = self.read();
(c.time, c.live())
};
backend::live_time(&self.shared, live).unwrap_or(time)
}
/// Length in seconds, once loaded.
pub fn duration(&self) -> Option<f64> {
self.read().duration
}
/// Display size in pixels (rotation applied), once a video loads. None for audio.
/// Whether the clip has a sound track it can play (a page's media controls grey the mute
/// button for one without); None until the clip's facts are read.
pub fn has_sound(&self) -> Option<bool> {
self.shared.ctl.lock().unwrap().meta.map(|m| m.sound)
}
pub fn natural_size(&self) -> Option<(u32, u32)> {
self.shared.ctl.lock().unwrap().size
}
pub fn rate(&self) -> f32 {
self.shared.ctl.lock().unwrap().rate
}
pub fn looping(&self) -> bool {
self.shared.ctl.lock().unwrap().looping
}
pub fn muted(&self) -> bool {
self.shared.ctl.lock().unwrap().muted
}
pub fn volume(&self) -> f32 {
self.shared.ctl.lock().unwrap().volume
}
/// The surface video frames land in: for frame observers and draw counts.
pub fn surface(&self) -> &NativeSurface {
&self.surface
}
fn read(&self) -> MutexGuard<'_, Control> {
if self.shared.kind == Kind::Audio && !playback_enabled() {
self.shared.open_now();
self.shared.follow_clock();
}
self.shared.ctl.lock().unwrap()
}
/// A handle edit that changes the clip's phase. Handle edits ask for no effects.
fn send(&self, event: Event) {
self.edit(|c| {
step(c, event);
});
}
fn edit(&self, f: impl FnOnce(&mut Control)) {
// Headless audio: fold in the time played up to now at the old rate, then restart the
// clock from the edit.
let clock = (self.shared.kind == Kind::Audio && !playback_enabled()).then(headless_clock).flatten();
if clock.is_some() {
self.shared.open_now();
}
{
let mut c = self.shared.ctl.lock().unwrap();
if let Some(now) = clock {
c.advance_virtual(now);
}
f(&mut c);
if let Some(now) = clock {
c.advance_virtual(now);
}
}
if clock.is_some() {
self.shared.settle(false);
}
backend::apply(&self.shared);
self.shared.wake_windows();
}
}
/// The clock a pull samples: a window's next presentation, or a headless run's virtual time.
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub enum Clock {
Display(Instant),
Virtual(f64),
}
/// What one pull tells the runtime.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Pulled {
/// Keep drawing frames: playing, or waiting on a seek.
pub active: bool,
/// Changes when state, duration or size change, so views reading them re-run.
pub generation: u64,
/// While active: no frame is needed before this, when the next picture is due. None asks
/// for every refresh.
pub due: Option<Instant>,
}
/// Folds one drawn video's `generation` into a frame's signature, which changes, re-running
/// views, only when some video's state does. Order-free, so paint order doesn't count.
#[doc(hidden)]
pub fn fold(signature: u64, generation: u64, key: usize) -> u64 {
signature.wrapping_add((generation ^ (key as u64).rotate_left(32)).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(31))
}
/// [`fold`] for an element that isn't pulled this frame (out of sight, transparent): what it
/// last heard, without pulling a frame. Nothing for a surface with no video.
#[doc(hidden)]
pub fn fold_unpulled(signature: u64, surface: &NativeSurface) -> u64 {
match surface.video() {
Some(video) => fold(signature, video.ctl.lock().unwrap().generation, surface.key()),
None => signature,
}
}
/// What `--tree` reports for a media element.
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq)]
pub struct Snapshot {
pub kind: Kind,
pub state: PlayerState,
pub time: f64,
pub duration: Option<f64>,
pub size: Option<(u32, u32)>,
pub rate: f32,
pub looping: bool,
pub muted: bool,
}
/// Clip facts read once when it opens.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Meta {
pub duration: f64,
/// None for audio.
pub size: Option<(u32, u32)>,
/// Seconds per frame, for snapping virtual time to whole frames.
pub frame: f64,
/// The clip has a sound track the player can play.
pub sound: bool,
}
#[doc(hidden)]
pub struct Shared {
source: MediaSource,
/// HTTP request headers for a URL source. Never logged.
headers: Vec<(String, String)>,
kind: Kind,
ctl: Mutex<Control>,
wakes: Mutex<Vec<Weak<rune_core::live::Wake>>>,
waker: WakerSlot,
/// The generation windows last heard about.
notified: AtomicU64,
native: Mutex<backend::Native>,
backend: &'static Backend,
}
impl Shared {
#[doc(hidden)]
pub fn snapshot(&self) -> Snapshot {
let c = self.ctl.lock().unwrap();
Snapshot {
kind: self.kind,
state: c.state(),
time: c.time,
duration: c.duration,
size: c.size,
rate: c.rate,
looping: c.looping,
muted: c.muted,
}
}
/// Redraw every window that has drawn this player. Safe from any thread.
fn wake_windows(&self) {
let wakes: Vec<_> = self.wakes.lock().unwrap().iter().filter_map(Weak::upgrade).collect();
for wake in wakes {
wake.notify();
}
}
/// Tell the app's waker (and, outside a frame, the windows) that the state changed.
/// Call with no locks held.
fn settle(&self, windows: bool) {
let generation = self.ctl.lock().unwrap().generation;
self.waker.tell(generation);
if self.notified.swap(generation, Ordering::AcqRel) != generation && windows {
self.wake_windows();
}
}
fn register(&self, wake: &Arc<rune_core::live::Wake>) {
let mut wakes = self.wakes.lock().unwrap();
wakes.retain(|w| w.strong_count() > 0);
if !wakes.iter().any(|w| std::ptr::eq(w.as_ptr(), Arc::as_ptr(wake))) {
wakes.push(Arc::downgrade(wake));
}
}
/// Headless: open the clip synchronously, once.
fn open_now(&self) {
let mut native = self.native.lock().unwrap();
if !self.ctl.lock().unwrap().opened() {
let meta = (self.backend.probe)(&mut native, &self.source, &self.headers, self.kind);
self.ctl.lock().unwrap().open(meta);
drop(native);
self.settle(false);
}
}
/// Headless audio: playback time follows the runtime clock of this thread, if one steps.
fn follow_clock(&self) {
if self.kind != Kind::Audio || playback_enabled() {
return;
}
let Some(now) = headless_clock() else { return };
if self.ctl.lock().unwrap().playing() {
self.open_now();
}
self.ctl.lock().unwrap().advance_virtual(now);
self.settle(false);
}
/// Runs on the UI thread for each element that draws this player, once per frame.
#[doc(hidden)]
pub fn pull(self: &Arc<Self>, surface: &NativeSurface, clock: Clock, wake: &Arc<rune_core::live::Wake>) -> Pulled {
self.register(wake);
if self.kind == Kind::Audio {
// Nothing to draw: the element only re-runs its view when the state changes.
match clock {
Clock::Virtual(_) => self.open_now(),
Clock::Display(_) => (self.backend.drive)(self),
}
return Pulled { active: false, generation: self.ctl.lock().unwrap().generation, due: None };
}
let (active, due) = match clock {
Clock::Virtual(now) => (self.pull_virtual(surface, now), None),
Clock::Display(target) => ((self.backend.pull)(self, surface, target), (self.backend.due)(self)),
};
let pulled = {
let mut c = self.ctl.lock().unwrap();
for effect in step(&mut c, Event::Drawn) {
if effect == Effect::Placeholder {
push_placeholder(surface);
}
}
Pulled { active: active && !c.failed(), generation: c.generation, due }
};
self.settle(false);
pulled
}
/// Headless: decode the frame at the virtual playback time, synchronously.
fn pull_virtual(&self, surface: &NativeSurface, now: f64) -> bool {
self.open_now();
let mut native = self.native.lock().unwrap();
let (meta, frame, shown) = {
let mut c = self.ctl.lock().unwrap();
let Some(meta) = c.meta.filter(|_| !c.failed()) else { return false };
c.advance_virtual(now);
(meta, meta.frame_index(c.time), c.shown)
};
if shown != Some(frame) {
let decoded = (self.backend.decode)(&mut native, &self.source, &self.headers, meta.frame_time(frame));
let mut c = self.ctl.lock().unwrap();
c.shown = Some(frame);
let id = c.next_frame_id();
if let Err(e) = decoded.and_then(|bytes| surface.push_bytes(bytes, id)) {
c.fail(e);
}
}
self.ctl.lock().unwrap().playing()
}
}
impl Meta {
pub(crate) fn frames(&self) -> i64 {
((self.duration / self.frame).round() as i64).max(1)
}
pub(crate) fn frame_index(&self, t: f64) -> i64 {
((t / self.frame + 1e-6).floor() as i64).clamp(0, self.frames() - 1)
}
/// The middle of frame `i`, so decoders never land on a neighbour's boundary.
pub(crate) fn frame_time(&self, i: i64) -> f64 {
((i as f64 + 0.5) * self.frame).min(self.duration)
}
}
/// A clip's state, stepped by [`phases::step`].
#[derive(Clone, Debug)]
pub(crate) struct Control {
kind: Kind,
// Intent, from the handle.
pub rate: f32,
pub looping: bool,
pub muted: bool,
pub volume: f32,
/// A seek not yet carried out, by a player, a poster, a decoder or the headless clock.
seek: Option<f64>,
// Reported by pulls and ticks.
pub time: f64,
pub duration: Option<f64>,
pub size: Option<(u32, u32)>,
pub meta: Option<Meta>,
run: Run,
stage: Stage,
/// Fences poster requests: a request for a new time or a native player taking over moves
/// it on.
posters: Seq,
/// The time the current poster attempt asked for; None once a player took over.
poster_at: Option<f64>,
generation: u64,
frame_id: u64,
/// Headless: the frame index on the surface.
shown: Option<i64>,
}
impl Default for Control {
fn default() -> Self {
Self {
kind: Kind::Video,
rate: 1.0,
looping: false,
muted: true,
volume: 1.0,
seek: None,
time: 0.0,
duration: None,
size: None,
meta: None,
run: Run::default(),
stage: Stage::default(),
posters: Seq::default(),
poster_at: None,
generation: 0,
frame_id: 0,
shown: None,
}
}
}
/// A 16:9 mid-grey frame for videos that can't play.
fn push_placeholder(surface: &NativeSurface) {
let (w, h) = (32, 18);
let grey = [0x46u8, 0x46, 0x46, 0xff];
let rgba: Vec<u8> = grey.iter().copied().cycle().take(w * h * 4).collect();
let frame = ByteFrame {
width: w as u32,
height: h as u32,
format: Format::Bgra,
color: ColorInfo { matrix: crate::native_surface::Matrix::Bt709, transfer: crate::native_surface::Transfer::Srgb },
planes: [rgba, Vec::new()],
};
surface.push_bytes(frame, u64::MAX).ok();
}
#[cfg(test)]
mod tests;
+575
View File
@@ -0,0 +1,575 @@
//! A clip's phases as one machine, apart from AVFoundation so they're plain data: whether it
//! plays ([`Run`]), and what stands behind its surface ([`Stage`]): nothing yet, a poster, or a
//! native player and where that player's last seek stands ([`Settle`]). The handle, the clocks,
//! the poster worker and the native player all report to [`step`], and what it asks for comes
//! back as [`Effect`]s, carried out by `turn` or the caller.
use super::{Control, Kind, Meta, PlayerState};
use rune_core::machine::{Attempt, Effects};
use rune_core::time::Instant;
use std::time::Duration;
/// A seek that never lands stops requesting redraws (or ticks) after this long.
const SEEK_PATIENCE: Duration = Duration::from_secs(2);
/// An audio seek has landed once the player reports a time this close to the target.
const AUDIO_SEEK_SLOP: f64 = 0.25;
/// A player item that never becomes ready fails after this long.
const LOAD_PATIENCE: Duration = Duration::from_secs(30);
/// Whether the clip plays. Loading is apart from this: `play` is intent until the clip opens.
#[derive(Clone, Debug, Default, PartialEq)]
pub(super) enum Run {
#[default]
Paused,
/// Headless, `anchor` is (runtime clock, playback time) when playback last (re)started.
Playing { anchor: Option<(f64, f64)> },
/// Reached the end without looping.
Ended,
/// `drawn` once a video's placeholder is on its surface.
Failed { error: String, drawn: bool },
}
/// What stands behind the clip's surface.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) enum Stage {
/// No player, and no poster asked for since the clip was made or since a player that never
/// showed a frame was released.
#[default]
Unasked,
/// No player, and a poster asked for: a finished one replaces the surface's frame.
Poster,
/// No player, and a finished load brings only the clip's facts: the clip is audio, or a
/// released player's frame stays on the surface.
Bare,
/// A player that can't play yet.
Loading { created: Instant, muted: bool, volume: f32 },
/// A player that can. `rate` was last applied to it (0 = paused); `shown` is the item time
/// of the frame on the surface.
Ready { created: Instant, muted: bool, volume: f32, rate: f32, settle: Settle, shown: Option<f64> },
}
impl Stage {
pub(super) fn has_player(self) -> bool {
matches!(self, Stage::Loading { .. } | Stage::Ready { .. })
}
pub(super) fn ready(self) -> bool {
matches!(self, Stage::Ready { .. })
}
/// The player was last told to run.
pub(super) fn running(self) -> bool {
matches!(self, Stage::Ready { rate, .. } if rate > 0.0)
}
}
/// Where the player's last seek stands.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) enum Settle {
#[default]
Still,
/// Waiting for the frame at `to` (for audio, the position), since `since`.
Seeking { since: Instant, to: f64 },
/// A paused seek within the frame on screen: nothing to wait for, but the player may report
/// the old position until it lands, so the handle's time holds.
Holding { to: f64 },
}
impl Settle {
/// A seek to `to`, `same_frame` when it's paused within the frame on screen. It replaces
/// any earlier seek, as the player cancels that one.
pub(super) fn seek(&mut self, to: f64, same_frame: bool, now: Instant) {
*self = if same_frame { Settle::Holding { to } } else { Settle::Seeking { since: now, to } };
}
/// A new frame reached the surface.
pub(super) fn framed(&mut self) {
if let Settle::Seeking { .. } = self {
*self = Settle::Still;
}
}
/// The player reports `current`. Audio has no frames, so its seek lands at the position;
/// a hold ends once the player catches up, or when playback moves on from it.
pub(super) fn observe(&mut self, current: f64, playing: bool, audio: bool) {
match *self {
Settle::Seeking { to, .. } if audio && (current - to).abs() < AUDIO_SEEK_SLOP => *self = Settle::Still,
Settle::Holding { to } if playing || (current - to).abs() < 1e-3 => *self = Settle::Still,
_ => {}
}
}
/// A seek that hasn't landed by `now` stops being waited for.
pub(super) fn expire(&mut self, now: Instant) {
if let Settle::Seeking { since, .. } = *self
&& now.saturating_duration_since(since) > SEEK_PATIENCE
{
*self = Settle::Still;
}
}
/// The player may still report the position from before the seek.
pub(super) fn pending(self) -> bool {
self != Settle::Still
}
/// A frame (or position) is still to come.
pub(super) fn waiting(self) -> bool {
matches!(self, Settle::Seeking { .. })
}
}
/// What the player item reports.
#[derive(Clone, Debug, PartialEq)]
pub(super) enum Item {
Loading,
Ready,
Failed(String),
}
#[derive(Clone, Debug, PartialEq)]
pub(super) enum Event {
// The handle.
Play,
Pause,
Seek(f64),
Rate(f32),
// The clip's facts, or why there are none.
Open(Result<Meta, String>),
Fail(String),
/// The headless clock reads this.
Clock(f64),
/// A pull drew the clip.
Drawn,
/// An app warms the page it shows next.
Preload,
/// The window loop can load an audio clip.
LoadAudio,
/// The poster worker finished the request made under `attempt`: the clip's facts, or why it
/// couldn't open.
PosterDone { attempt: Attempt, result: Result<Meta, String> },
/// A pull or tick reached a clip that hasn't failed, on the main thread.
Pull,
PlayerMade { created: Instant },
Item { item: Item, now: Instant },
/// The handle's intent is due at the player.
Reconcile { now: Instant },
/// A new frame reached the surface, at this item time.
Framed { shown: f64 },
/// The player reports its position, and that it stopped though told to run; `frame_time`
/// is the frame's item time, for video.
Follow { current: f64, stopped: bool, frame_time: Option<f64>, now: Instant },
/// The turn is over.
Finish { now: Instant },
/// The player goes because the clip failed.
Release,
/// The player goes because parked players are over their limit.
Parked,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Effect {
/// Draw the neutral placeholder.
Placeholder,
/// Have the worker open the clip and decode this time, answering under this attempt.
AskPoster(f64, Attempt),
/// A finished poster may land on the surface.
ShowPoster,
MakePlayer,
DropPlayer,
/// The item just became ready: read how its buffers turn upright.
Orient,
/// Nothing opened the clip before its item did: read the facts from the item.
ReadFacts,
SetMuted(bool),
SetVolume(f32),
SeekTo(f64),
/// 0 pauses.
SetRate(f32),
/// Back to zero at this rate, for a loop.
Restart(f32),
}
/// The one place a clip's phases change.
pub(super) fn step(c: &mut Control, event: Event) -> Effects<Effect> {
match event {
Event::Play => {
match c.run {
Run::Failed { .. } => return Effects::none(),
Run::Ended => {
c.seek = Some(0.0);
c.time = 0.0;
}
Run::Paused | Run::Playing { .. } => {}
}
c.run = Run::Playing { anchor: None };
}
Event::Pause => {
if let Run::Playing { .. } = c.run {
c.run = Run::Paused;
}
}
Event::Seek(seconds) => {
let seconds = if seconds.is_finite() { seconds.max(0.0) } else { 0.0 };
let seconds = c.duration.map_or(seconds, |d| seconds.min(d));
c.seek = Some(seconds);
c.time = seconds;
match c.run {
Run::Ended => c.run = Run::Paused,
Run::Playing { .. } => c.run = Run::Playing { anchor: None },
Run::Paused | Run::Failed { .. } => {}
}
}
Event::Rate(rate) => {
c.rate = rate;
if let Run::Playing { .. } = c.run {
c.run = Run::Playing { anchor: None };
}
}
Event::Open(Ok(meta)) => opened(c, meta),
Event::Open(Err(error)) | Event::Fail(error) => failed(c, error),
Event::Clock(now) => advance(c, now),
Event::Drawn => {
if let Run::Failed { drawn, .. } = &mut c.run
&& !*drawn
{
*drawn = true;
return Effects::one(Effect::Placeholder);
}
}
Event::Preload => {
if c.kind != Kind::Audio && c.stage == Stage::Unasked && !c.failed() {
let at = c.time;
return ask_poster(c, at);
}
}
Event::LoadAudio => {
if c.stage == Stage::Unasked && !c.opened() {
return ask_poster(c, 0.0);
}
}
Event::PosterDone { attempt, result } => {
// A failed clip keeps its placeholder.
if c.failed() {
return Effects::none();
}
// A request a player or a newer request took over from still brings the clip's facts
// (its true frame timing), but its frame and its errors are for a time or a surface
// that has moved on.
let current = attempt == c.posters.current();
match result {
Ok(meta) => {
if !c.opened() {
opened(c, meta);
}
// A late poster never covers a frame a player made, or one a seek moved past.
if current && !overtaken(c) && c.stage == Stage::Poster {
return Effects::one(Effect::ShowPoster);
}
}
// Audio's load only opens it: once another open did, its error is old news.
Err(error) if current && !overtaken(c) && (c.kind == Kind::Video || !c.opened()) => failed(c, error),
Err(_) => {}
}
}
Event::Pull => return pull(c),
Event::PlayerMade { created } => {
// A fresh player starts at the handle's position.
if c.time > 0.0 && c.seek.is_none() {
c.seek = Some(c.time);
}
// Posters still in flight are for a surface the player now owns. Audio's load has
// no surface to lose, so its answer always counts.
if c.kind == Kind::Video {
c.posters.next();
c.poster_at = None;
}
c.stage = Stage::Loading { created, muted: false, volume: 1.0 };
}
Event::Item { item, now } => return item_reports(c, item, now),
Event::Reconcile { now } => return reconcile(c, now),
Event::Framed { shown: at } => {
if let Stage::Ready { shown, settle, .. } = &mut c.stage {
*shown = Some(at);
settle.framed();
}
}
Event::Follow { current, stopped, frame_time, now } => return follow(c, current, stopped, frame_time, now),
Event::Finish { now } => {
if let Stage::Ready { settle, .. } = &mut c.stage {
settle.expire(now);
}
}
Event::Release => {
if c.stage.has_player() {
c.stage = Stage::Bare;
return Effects::one(Effect::DropPlayer);
}
}
Event::Parked => {
// A video that never showed a frame shows a poster instead.
let shown = matches!(c.stage, Stage::Ready { shown: Some(_), .. });
if c.stage.has_player() {
c.stage = if c.kind == Kind::Video && !shown { Stage::Unasked } else { Stage::Bare };
}
}
}
Effects::none()
}
/// A seek made since the poster request names another time, so its answer is for a time the
/// clip has left even before the next pull asks for the new one. Both times clamp to the clip's
/// length first: a seek past the end lands on the poster's own time, which is the same picture.
/// // differs from dev: dev had no fence, and failed the clip on the old answer.
fn overtaken(c: &Control) -> bool {
let clamp = |t: f64| c.duration.map_or(t, |d| t.min(d));
c.poster_at.is_some_and(|asked| c.seek.is_some_and(|target| clamp(target) != clamp(asked)))
}
fn opened(c: &mut Control, meta: Meta) {
c.meta = Some(meta);
c.duration = Some(meta.duration);
c.size = meta.size;
c.time = c.time.min(meta.duration);
c.seek = c.seek.map(|t| t.min(meta.duration));
c.generation += 1;
}
fn failed(c: &mut Control, error: String) {
if !c.failed() {
c.run = Run::Failed { error, drawn: false };
c.generation += 1;
}
}
/// Headless clock: playback time follows the runtime clock from the first pull after `play`,
/// `seek` or a rate change.
fn advance(c: &mut Control, now: f64) {
let Some(meta) = c.meta else { return };
if let Some(t) = c.seek.take() {
c.time = t.min(meta.duration);
if let Run::Playing { anchor } = &mut c.run {
*anchor = None;
}
}
let Run::Playing { anchor } = &mut c.run else { return };
// A clock behind the anchor (another runtime on this thread) restarts from here.
let (start_clock, start_time) = match *anchor {
Some((clock, time)) if clock <= now => (clock, time),
_ => *anchor.insert((now, c.time)),
};
let t = start_time + (now - start_clock).max(0.0) * c.rate as f64;
if t < meta.duration {
c.time = t;
} else if c.looping && meta.duration > 0.0 {
c.time = t % meta.duration;
} else {
c.time = meta.duration;
c.run = Run::Ended;
c.generation += 1;
}
}
/// Audio has no poster, so its worker only opens it. Called only while no player runs. A video's
/// request for a new time supersedes the ones before it, which may still be decoding an older
/// time; one for the same time shares their attempt.
fn ask_poster(c: &mut Control, at: f64) -> Effects<Effect> {
if c.kind == Kind::Video && c.poster_at != Some(at) {
c.posters.next();
c.poster_at = Some(at);
}
c.stage = if c.kind == Kind::Video { Stage::Poster } else { Stage::Bare };
Effects::one(Effect::AskPoster(at, c.posters.current()))
}
/// Nothing to do with a player already there. Without one, a paused video shows a poster, with
/// no player and no decoder session; a clip that should play gets one.
fn pull(c: &mut Control) -> Effects<Effect> {
if c.stage.has_player() {
return Effects::none();
}
if !c.playing() {
if c.kind == Kind::Video
&& let Some(at) = c.seek.take().or_else(|| (c.stage == Stage::Unasked).then_some(c.time))
{
return ask_poster(c, at);
}
return Effects::none();
}
// Audio opens on the load worker first, which may find it needs decoding (an Ogg clip at a
// URL with no extension); the worker then drives the clip again, starting a queued play.
if c.kind == Kind::Audio && !c.opened() {
if c.stage == Stage::Unasked {
return ask_poster(c, 0.0);
}
return Effects::none();
}
Effects::one(Effect::MakePlayer)
}
/// Fails the clip if its item failed or never loaded; marks it ready once it can play.
fn item_reports(c: &mut Control, item: Item, now: Instant) -> Effects<Effect> {
let (Stage::Loading { created, muted, volume } | Stage::Ready { created, muted, volume, .. }) = c.stage else { return Effects::none() };
let failure = match &item {
Item::Failed(error) => Some(error.clone()),
Item::Loading if now.saturating_duration_since(created) > LOAD_PATIENCE => {
Some(format!("timed out loading after {} s", LOAD_PATIENCE.as_secs()))
}
_ => None,
};
if let Some(error) = failure {
failed(c, error);
c.stage = Stage::Bare;
return Effects::one(Effect::DropPlayer);
}
if item == Item::Ready && !c.stage.ready() {
c.stage = Stage::Ready { created, muted, volume, rate: 0.0, settle: Settle::Still, shown: None };
let mut effects = Effects::one(Effect::Orient);
if !c.opened() {
effects.push(Effect::ReadFacts);
}
return effects;
}
Effects::none()
}
/// Brings the player in line with the handle: mute, volume, seek, rate. Seeks wait for the item to be
/// ready, which drops earlier ones.
fn reconcile(c: &mut Control, now: Instant) -> Effects<Effect> {
let mut effects = Effects::none();
if let Stage::Loading { muted, .. } | Stage::Ready { muted, .. } = &mut c.stage
&& *muted != c.muted
{
*muted = c.muted;
effects.push(Effect::SetMuted(c.muted));
}
if let Stage::Loading { volume, .. } | Stage::Ready { volume, .. } = &mut c.stage
&& *volume != c.volume
{
*volume = c.volume;
effects.push(Effect::SetVolume(c.volume));
}
let playing = c.playing();
if let Stage::Ready { rate, settle, shown, .. } = &mut c.stage {
if let Some(t) = c.seek.take() {
effects.push(Effect::SeekTo(t));
// A paused seek within the frame on screen brings no new frame to wait for.
let same_frame = !playing && c.meta.zip(*shown).is_some_and(|(m, shown)| m.frame_index(shown) == m.frame_index(t));
settle.seek(t, same_frame, now);
}
let want = if playing { c.rate } else { 0.0 };
if *rate != want {
*rate = want;
effects.push(Effect::SetRate(want));
}
}
effects
}
/// Folds the player's position into the state: seeks landing, the end, loops.
fn follow(c: &mut Control, current: f64, stopped: bool, frame_time: Option<f64>, now: Instant) -> Effects<Effect> {
let playing = c.playing();
let Stage::Ready { settle, .. } = &mut c.stage else { return Effects::none() };
settle.observe(current, playing, frame_time.is_none());
// Seeks land asynchronously: until then the player still reports the old position, which
// may be the end.
let seeking = settle.pending();
let at_end = !seeking && (c.duration.is_some_and(|d| current >= d - 1e-3) || stopped);
let time = if seeking {
c.time
} else if playing && !at_end {
frame_time.unwrap_or(current).max(0.0)
} else {
current
};
let restart = c.observe(time, at_end);
let playing = c.playing();
let Stage::Ready { rate, settle, .. } = &mut c.stage else { return Effects::none() };
if restart {
*rate = c.rate;
settle.seek(0.0, false, now);
// A loop is news for anything showing play counts or progress from zero.
c.generation += 1;
return Effects::one(Effect::Restart(c.rate));
}
if !playing {
*rate = 0.0;
}
Effects::none()
}
impl Control {
pub(crate) fn state(&self) -> PlayerState {
if let Run::Failed { error, .. } = &self.run {
PlayerState::Failed(error.clone())
} else if self.meta.is_none() {
PlayerState::Loading
} else {
match self.run {
Run::Playing { .. } => PlayerState::Playing,
Run::Ended => PlayerState::Ended,
_ => PlayerState::Ready,
}
}
}
pub(crate) fn playing(&self) -> bool {
matches!(self.run, Run::Playing { .. })
}
pub(crate) fn failed(&self) -> bool {
matches!(self.run, Run::Failed { .. })
}
pub(crate) fn opened(&self) -> bool {
self.meta.is_some() || self.failed()
}
pub(crate) fn open(&mut self, meta: Result<Meta, String>) {
step(self, Event::Open(meta));
}
pub(crate) fn fail(&mut self, error: String) {
step(self, Event::Fail(error));
}
pub(crate) fn advance_virtual(&mut self, now: f64) {
step(self, Event::Clock(now));
}
pub(crate) fn next_frame_id(&mut self) -> u64 {
self.frame_id += 1;
self.frame_id
}
/// Whether the player's own position is the one to read: it runs, and no seek is under way.
pub(super) fn live(&self) -> bool {
matches!(self.stage, Stage::Ready { rate, settle, .. } if rate > 0.0 && !settle.waiting())
}
/// Whether the clip is playing, seeking or loading (a seek waits for it).
pub(super) fn active(&self) -> bool {
match self.stage {
Stage::Ready { settle, .. } => self.playing() || settle.waiting(),
_ => true,
}
}
/// Whether the player may be kept only as a parked one.
pub(super) fn parkable(&self) -> bool {
self.stage.ready() && !self.active()
}
/// The player reports `time`, at the end or not. Returns true when it should restart from
/// zero.
pub(super) fn observe(&mut self, time: f64, at_end: bool) -> bool {
self.time = self.duration.map_or(time, |d| time.clamp(0.0, d));
if !(self.playing() && at_end) {
return false;
}
if self.looping {
self.time = 0.0;
return true;
}
self.run = Run::Ended;
self.generation += 1;
false
}
}
#[cfg(test)]
#[path = "phases_tests.rs"]
mod tests;
@@ -0,0 +1,610 @@
//! A transcription of the pre-machine fields and branches, which calls none of `phases` or `turn`,
//! used as an oracle by the exhaustive sequence tests in `phases_tests.rs`.
use super::*;
#[derive(Clone, Copy, Debug, PartialEq)]
struct OldMeta {
duration: f64,
size: Option<(u32, u32)>,
frame: f64,
}
impl OldMeta {
fn frames(&self) -> i64 {
((self.duration / self.frame).round() as i64).max(1)
}
fn frame_index(&self, t: f64) -> i64 {
((t / self.frame + 1e-6).floor() as i64).clamp(0, self.frames() - 1)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum OldSettle {
Still,
Seeking { since: Instant, to: f64 },
Holding { to: f64 },
}
impl OldSettle {
fn seek(&mut self, to: f64, same_frame: bool, now: Instant) {
*self = if same_frame { OldSettle::Holding { to } } else { OldSettle::Seeking { since: now, to } };
}
fn framed(&mut self) {
if let OldSettle::Seeking { .. } = self {
*self = OldSettle::Still;
}
}
fn observe(&mut self, current: f64, playing: bool, audio: bool) {
match *self {
OldSettle::Seeking { to, .. } if audio && (current - to).abs() < 0.25 => *self = OldSettle::Still,
OldSettle::Holding { to } if playing || (current - to).abs() < 1e-3 => *self = OldSettle::Still,
_ => {}
}
}
fn expire(&mut self, now: Instant) {
if let OldSettle::Seeking { since, .. } = *self
&& now.saturating_duration_since(since) > Duration::from_secs(2)
{
*self = OldSettle::Still;
}
}
fn pending(self) -> bool {
self != OldSettle::Still
}
fn waiting(self) -> bool {
matches!(self, OldSettle::Seeking { .. })
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OldPoster {
Unasked,
Due,
Withheld,
}
#[derive(Clone, Copy, Debug)]
struct OldPlayer {
rate: f32,
muted: bool,
ready: bool,
created: Instant,
settle: OldSettle,
shown: Option<f64>,
}
#[derive(Clone)]
pub(super) struct Old {
audio: bool,
playing: bool,
rate: f32,
looping: bool,
muted: bool,
seek: Option<f64>,
time: f64,
duration: Option<f64>,
size: Option<(u32, u32)>,
meta: Option<OldMeta>,
ended: bool,
failed: Option<String>,
placeholder: bool,
generation: u64,
frame_id: u64,
anchor: Option<(f64, f64)>,
player: Option<OldPlayer>,
poster: OldPoster,
// A finished poster answers the request that asked for it.
done: Option<(u32, Done)>,
// Each video player fences the poster requests made before it.
fence: u32,
// The fence the newest request was made under.
asked: u32,
// differs from dev: the time the fence's requests asked for, until a player takes over.
fence_at: Option<f64>,
// The requests the worker still owes, oldest (in flight) first.
pending: Vec<u32>,
now: Instant,
pub(super) log: Vec<Cmd>,
}
impl Old {
pub(super) fn new(audio: bool, now: Instant) -> Self {
Self {
audio,
playing: false,
rate: 1.0,
looping: false,
muted: !audio,
seek: None,
time: 0.0,
duration: None,
size: None,
meta: None,
ended: false,
failed: None,
placeholder: false,
generation: 0,
frame_id: 0,
anchor: None,
player: None,
poster: OldPoster::Unasked,
done: None,
fence: 0,
asked: 0,
fence_at: None,
pending: Vec::new(),
now,
log: Vec::new(),
}
}
fn play(&mut self) {
if self.failed.is_some() {
return;
}
if self.ended {
self.ended = false;
self.seek = Some(0.0);
self.time = 0.0;
}
self.playing = true;
self.anchor = None;
}
fn pause(&mut self) {
self.playing = false;
self.anchor = None;
}
fn seek(&mut self, seconds: f64) {
let seconds = if seconds.is_finite() { seconds.max(0.0) } else { 0.0 };
let seconds = self.duration.map_or(seconds, |d| seconds.min(d));
self.seek = Some(seconds);
self.time = seconds;
self.ended = false;
self.anchor = None;
}
fn set_rate(&mut self, rate: f32) {
self.rate = rate;
self.anchor = None;
}
fn state(&self) -> PlayerState {
if let Some(e) = &self.failed {
PlayerState::Failed(e.clone())
} else if self.meta.is_none() {
PlayerState::Loading
} else if self.playing {
PlayerState::Playing
} else if self.ended {
PlayerState::Ended
} else {
PlayerState::Ready
}
}
fn opened(&self) -> bool {
self.meta.is_some() || self.failed.is_some()
}
fn open(&mut self, meta: Result<OldMeta, String>) {
match meta {
Ok(meta) => {
self.meta = Some(meta);
self.duration = Some(meta.duration);
self.size = meta.size;
self.time = self.time.min(meta.duration);
self.seek = self.seek.map(|t| t.min(meta.duration));
self.generation += 1;
}
Err(e) => self.fail(e),
}
}
fn fail(&mut self, error: String) {
if self.failed.is_none() {
self.failed = Some(error);
self.playing = false;
self.generation += 1;
}
}
fn next_frame_id(&mut self) -> u64 {
self.frame_id += 1;
self.frame_id
}
fn advance_virtual(&mut self, now: f64) {
let Some(meta) = self.meta else { return };
if let Some(t) = self.seek.take() {
self.time = t.min(meta.duration);
self.anchor = None;
}
if !self.playing {
return;
}
let (start_clock, start_time) = match self.anchor {
Some((clock, time)) if clock <= now => (clock, time),
_ => *self.anchor.insert((now, self.time)),
};
let t = start_time + (now - start_clock).max(0.0) * self.rate as f64;
if t < meta.duration {
self.time = t;
} else if self.looping && meta.duration > 0.0 {
self.time = t % meta.duration;
} else {
self.time = meta.duration;
self.playing = false;
self.ended = true;
self.anchor = None;
self.generation += 1;
}
}
fn observe(&mut self, time: f64, at_end: bool) -> bool {
self.time = self.duration.map_or(time, |d| time.clamp(0.0, d));
if !(self.playing && at_end) {
return false;
}
if self.looping {
self.time = 0.0;
return true;
}
self.playing = false;
self.ended = true;
self.generation += 1;
false
}
fn load_audio(&mut self) {
if self.poster == OldPoster::Unasked && !self.opened() {
self.request_poster(0.0);
}
}
fn preload(&mut self) {
if self.audio || self.player.is_some() || self.poster != OldPoster::Unasked || self.failed.is_some() {
return;
}
let at = self.time;
self.request_poster(at);
}
fn request_poster(&mut self, at: f64) {
self.poster = if !self.audio { OldPoster::Due } else { OldPoster::Withheld };
// differs from dev: a video request for a new time fences the ones before it.
if !self.audio && self.fence_at != Some(at) {
self.fence += 1;
self.fence_at = Some(at);
}
// The request remembers the fence it was made under.
self.asked = self.fence;
queue(&mut self.pending, self.fence);
self.log.push(Cmd::Ask(at));
}
fn take_poster(&mut self, surface: bool) {
let Some((asked, done)) = self.done.take() else { return };
// A failed clip ignores the answer.
if self.failed.is_some() {
return;
}
// A request a player fenced brings facts, but no error or frame.
let current = asked == self.fence;
match done {
Done::Err => {
// differs from dev: an audio load error after the clip opened is ignored.
if current && !self.overtaken() && (!self.audio || !self.opened()) {
self.fail("load failed".into());
}
}
Done::Facts | Done::Frame | Done::FrameFails => {
if !self.opened() {
self.open(Ok(old_meta()));
}
if current && !self.overtaken() && done != Done::Facts && surface && self.player.is_none() && self.poster == OldPoster::Due {
let id = self.next_frame_id();
if done == Done::FrameFails {
self.fail("poster push failed".into());
} else {
self.log.push(Cmd::Poster(id));
}
}
}
}
}
/// differs from dev: a seek made since the request names another time, so its answer is for
/// a time the clip has left even before the next pull asks for the new one. Both clamp to
/// the clip's length, so a seek past the end is the poster's own time.
fn overtaken(&self) -> bool {
let clamp = |t: f64| self.duration.map_or(t, |d| t.min(d));
self.fence_at.is_some_and(|asked| self.seek.is_some_and(|target| clamp(target) != clamp(asked)))
}
fn drop_player(&mut self) {
if self.player.take().is_some() {
self.log.push(Cmd::Drop);
}
}
fn check_item(&mut self, s: &Script, now: Instant) -> bool {
let p = self.player.as_mut().unwrap();
let failure = if s.item == Reports::Failed {
Some("item failed".to_string())
} else if s.item != Reports::Ready && now.saturating_duration_since(p.created) > Duration::from_secs(30) {
Some("timed out loading after 30 s".to_string())
} else {
None
};
if let Some(e) = failure {
self.fail(e);
self.drop_player();
return false;
}
if s.item == Reports::Ready && !p.ready {
p.ready = true;
self.log.push(Cmd::Orient);
if !self.opened() {
self.open(Ok(old_item_meta()));
}
}
true
}
fn ensure_player(&mut self, s: &Script, now: Instant) -> bool {
if self.player.is_some() {
return true;
}
if self.audio && !self.opened() {
if self.poster == OldPoster::Unasked {
self.request_poster(0.0);
}
return false;
}
if s.make_fails {
self.fail("couldn't make a player".into());
return false;
}
self.log.push(Cmd::Make);
if self.time > 0.0 && self.seek.is_none() {
self.seek = Some(self.time);
}
self.player = Some(OldPlayer { rate: 0.0, muted: false, ready: false, created: now, settle: OldSettle::Still, shown: None });
// A video player fences the poster requests before it.
if !self.audio {
self.fence += 1;
// differs from dev: the next request is new, whatever its time.
self.fence_at = None;
}
self.poster = OldPoster::Withheld;
true
}
fn reconcile(&mut self, now: Instant) {
let p = self.player.as_mut().unwrap();
if p.muted != self.muted {
self.log.push(Cmd::Muted(self.muted));
p.muted = self.muted;
}
if p.ready
&& let Some(t) = self.seek.take()
{
self.log.push(Cmd::Seek(t));
let same_frame = !self.playing && self.meta.zip(p.shown).is_some_and(|(m, shown)| m.frame_index(shown) == m.frame_index(t));
p.settle.seek(t, same_frame, now);
}
if p.ready {
let rate = if self.playing { self.rate } else { 0.0 };
if p.rate != rate {
self.log.push(Cmd::Rate(rate));
p.rate = rate;
}
}
}
fn follow(&mut self, s: &Script, now: Instant, frame_time: Option<f64>) {
let mut p = self.player.unwrap();
p.settle.observe(s.current, self.playing, frame_time.is_none());
let seeking = p.settle.pending();
let stopped = p.rate > 0.0 && {
self.log.push(Cmd::ReadRate);
s.player_rate == 0.0
};
let at_end = !seeking && (self.duration.is_some_and(|d| s.current >= d - 1e-3) || stopped);
let time = if seeking {
self.time
} else if self.playing && !at_end {
frame_time.unwrap_or(s.current).max(0.0)
} else {
s.current
};
if self.observe(time, at_end) {
self.log.push(Cmd::Restart(self.rate));
p.rate = self.rate;
p.settle.seek(0.0, false, now);
self.generation += 1;
} else if !self.playing {
p.rate = 0.0;
}
self.player = Some(p);
}
fn finish(&mut self, now: Instant) -> bool {
let p = self.player.as_mut().unwrap();
p.settle.expire(now);
let active = self.playing || p.settle.waiting() || !p.ready;
let park = p.ready && !active;
self.log.push(if park { Cmd::Park } else { Cmd::Unpark });
active
}
fn pull(&mut self, s: &Script) -> bool {
let now = self.now;
self.take_poster(true);
if self.failed.is_some() {
self.drop_player();
return false;
}
self.log.push(Cmd::OnMain);
if !s.on_main {
return false;
}
if self.player.is_none() && !self.playing {
let want = self.seek.take().or_else(|| (self.poster == OldPoster::Unasked).then_some(self.time));
if let Some(at) = want {
self.request_poster(at);
}
return false;
}
let fresh = self.player.is_none();
if !self.ensure_player(s, now) {
return false;
}
if fresh {
self.log.push(Cmd::Unpark);
}
if !self.check_item(s, now) {
return false;
}
self.reconcile(now);
if self.player.unwrap().ready {
match s.frame {
Frame::Same => {}
Frame::New(shown) => {
let id = self.next_frame_id();
self.log.push(Cmd::Frame(id));
let p = self.player.as_mut().unwrap();
p.shown = Some(shown);
p.settle.framed();
}
Frame::PushFails => {
self.next_frame_id();
self.fail("frame push failed".into());
self.drop_player();
return false;
}
}
self.follow(s, now, Some(s.item_time));
}
self.finish(now)
}
fn step_audio(&mut self, s: &Script) -> bool {
self.log.push(Cmd::OnMain);
if !s.on_main {
return false;
}
let now = self.now;
self.take_poster(false);
if self.failed.is_some() {
self.drop_player();
return false;
}
if self.player.is_none() && !self.playing {
return false;
}
let fresh = self.player.is_none();
if !self.ensure_player(s, now) {
return false;
}
if fresh {
self.log.push(Cmd::Unpark);
}
if !self.check_item(s, now) {
return false;
}
self.reconcile(now);
if !self.player.unwrap().ready {
return true;
}
self.follow(s, now, None);
self.finish(now)
}
/// One element's pull, as the runtime made it.
fn shared_pull(&mut self, s: &Script) -> bool {
if self.audio {
return self.step_audio(s);
}
let active = self.pull(s);
if self.failed.is_some() && !self.placeholder {
self.placeholder = true;
self.log.push(Cmd::Placeholder);
}
active && self.failed.is_none()
}
fn apply(&mut self, s: &Script) {
if self.failed.is_some() {
return;
}
if self.audio {
let needs_tick = self.step_audio(s);
self.log.push(Cmd::Returned(needs_tick));
return;
}
if self.player.is_none() {
return;
}
let now = self.now;
self.reconcile(now);
if self.playing {
self.log.push(Cmd::Unpark);
}
}
fn park(&mut self) {
let player = self.player.take();
if !self.audio && player.as_ref().is_some_and(|p| p.shown.is_none()) {
self.poster = OldPoster::Unasked;
}
}
pub(super) fn run(&mut self, sym: Sym) {
match sym {
Sym::Play => self.play(),
Sym::Pause => self.pause(),
Sym::Seek(t) => self.seek(t),
Sym::Rate(r) => self.set_rate(r),
Sym::Looping(l) => self.looping = l,
Sym::Muted(m) => self.muted = m,
Sym::Open => self.open(Ok(old_meta())),
Sym::OpenFails => self.open(Err("open failed".into())),
Sym::Fail => self.fail("failed".into()),
Sym::Clock(t) => self.advance_virtual(t),
Sym::Preload => self.preload(),
Sym::LoadAudio => self.load_audio(),
Sym::Done(done) => self.done = Some((answer(&mut self.pending, self.asked), done)),
Sym::Wait(s) => self.now += Duration::from_secs(s),
Sym::Park => self.park(),
Sym::Apply => self.apply(&Script::READY),
Sym::Pull(s) => {
let active = self.shared_pull(&s);
self.log.push(Cmd::Returned(active));
}
}
}
pub(super) fn view(&self) -> View {
let p = self.player.as_ref();
View {
state: self.state(),
playing: self.playing,
ended: self.ended && self.failed.is_none(),
drawn: self.placeholder && self.failed.is_some(),
anchor: if self.playing { self.anchor } else { None },
rate: self.rate,
seek: self.seek,
time: self.time,
duration: self.duration,
size: self.size,
generation: self.generation,
frame_id: self.frame_id,
poster: match self.poster {
OldPoster::Unasked => 0,
OldPoster::Due => 1,
OldPoster::Withheld => 2,
},
fence: self.fence,
player: p.is_some(),
ready: p.is_some_and(|p| p.ready),
created: p.map(|p| p.created),
player_muted: p.is_some_and(|p| p.muted),
player_rate: p.map_or(0.0, |p| p.rate),
settle: p.map_or(SettleView::Still, |p| match p.settle {
OldSettle::Still => SettleView::Still,
OldSettle::Seeking { since, to } => SettleView::Seeking(since, to),
OldSettle::Holding { to } => SettleView::Holding(to),
}),
shown: p.and_then(|p| p.shown),
live: p.is_some_and(|p| p.ready && p.rate > 0.0 && !p.settle.waiting()),
log: self.log.clone(),
}
}
}
fn old_meta() -> OldMeta {
OldMeta { duration: 1.0, size: Some((64, 36)), frame: 0.25 }
}
fn old_item_meta() -> OldMeta {
OldMeta { duration: 2.0, size: Some((32, 18)), frame: 1.0 / 30.0 }
}
@@ -0,0 +1,253 @@
//! Poster answers that arrive too late to count: after the clip failed, or after a newer request
//! or a native player took over from the request. Each runs the real [`step`] and turn on the scripted player.
use super::*;
fn clip(audio: bool, script: &[Sym]) -> New {
let mut new = New::new(audio, rune_core::time::now());
for &sym in script {
new.run(sym);
}
new
}
fn posters_shown(new: &New) -> usize {
new.fake.log.iter().filter(|cmd| matches!(cmd, Cmd::Poster(_))).count()
}
#[test]
fn a_poster_after_a_failed_one_leaves_the_placeholder() {
let mut new = clip(false, &[Pull(Script::LOADING), Seek(0.3), Pull(Script::LOADING), Land(Done::Err), Pull(Script::LOADING)]);
assert_eq!(new.fake.log.iter().filter(|cmd| matches!(cmd, Cmd::Ask(_))).count(), 2, "two decodes queued");
assert!(!new.c.failed(), "the first decode was for a time the handle left");
new.run(Land(Done::Err));
new.run(Pull(Script::LOADING));
assert_eq!(new.c.run, Run::Failed { error: "load failed".into(), drawn: true });
assert!(new.fake.log.contains(&Cmd::Placeholder));
let frame_id = new.c.frame_id;
new.fake.done = Some((new.fake.asked, Done::Frame));
new.run(Pull(Script::LOADING));
assert_eq!(posters_shown(&new), 0, "nothing would redraw the placeholder it covered");
assert_eq!(new.c.frame_id, frame_id);
assert_eq!(new.c.run, Run::Failed { error: "load failed".into(), drawn: true });
}
#[test]
fn a_late_poster_error_leaves_a_working_player_playing() {
let mut new = clip(false, &[Preload, Play, Pull(Script::FRAME)]);
assert!(new.fake.log.contains(&Cmd::Frame(1)), "a native frame arrived");
let generation = new.c.generation;
new.run(Land(Done::Err));
new.run(Pull(Script::FRAME));
assert!(new.c.playing());
assert!(new.c.stage.ready());
assert!(!new.fake.log.contains(&Cmd::Drop));
assert_eq!(new.c.generation, generation);
}
#[test]
fn a_request_from_before_a_player_does_not_answer_the_one_after_it() {
let mut new = clip(false, &[Preload, Play, Pull(Script::LOADING), Pause, Park, Pull(Script::LOADING)]);
let (stale, current) = (Attempt::default(), new.fake.asked);
assert_ne!(stale, current);
assert_eq!(new.c.stage, Stage::Poster);
new.fake.done = Some((stale, Done::Frame));
new.run(Pull(Script::LOADING));
assert_eq!(posters_shown(&new), 0, "the stale frame is for an older position");
assert!(new.c.meta.is_some(), "its facts still count");
new.fake.done = Some((current, Done::Frame));
new.run(Pull(Script::LOADING));
assert_eq!(posters_shown(&new), 1);
}
#[test]
fn a_poster_for_an_older_paused_seek_neither_shows_nor_fails() {
let mut new = clip(false, &[Pull(Script::LOADING), Seek(0.3), Pull(Script::LOADING)]);
assert_eq!(new.fake.log.iter().filter(|cmd| matches!(cmd, Cmd::Ask(_))).count(), 2, "a decode at 0, then at 0.3");
let (older, newer) = (new.fake.pending[0], new.fake.asked);
assert_ne!(older, newer);
new.fake.done = Some((older, Done::Frame));
new.run(Pull(Script::LOADING));
assert_eq!(posters_shown(&new), 0, "frame 0 isn't the picture at 0.3");
assert!(new.c.meta.is_some(), "its facts still count");
new.fake.done = Some((older, Done::Err));
new.run(Pull(Script::LOADING));
assert!(!new.c.failed(), "0.3 may still decode");
new.fake.done = Some((newer, Done::Frame));
new.run(Pull(Script::LOADING));
assert_eq!(posters_shown(&new), 1);
}
/// The worker answers for a time the handle left before the next pull can ask for the seek's
/// time: its error is for a poster nobody wants, and the seek still decodes. // differs from dev
#[test]
fn a_poster_error_overtaken_by_a_seek_waits_for_the_new_time() {
let mut new = clip(false, &[Pull(Script::LOADING), Seek(0.3)]);
let stale = new.fake.asked;
new.fake.done = Some((stale, Done::Err));
new.run(Pull(Script::LOADING));
assert!(!new.c.failed(), "the seek at 0.3 may still decode");
assert!(new.fake.log.contains(&Cmd::Ask(0.3)), "the same pull asked for the time the handle wants");
let current = new.fake.asked;
assert_ne!(current, stale);
new.fake.done = Some((current, Done::Frame));
new.run(Pull(Script::LOADING));
assert_eq!(posters_shown(&new), 1, "the poster at 0.3 shows");
}
/// A successful answer for a time the handle left brings the clip's facts but never its frame.
/// // differs from dev: dev showed it until the new time decoded.
#[test]
fn a_poster_frame_overtaken_by_a_seek_does_not_show_before_the_new_time() {
let mut new = clip(false, &[Pull(Script::LOADING), Seek(0.3)]);
let stale = new.fake.asked;
new.fake.done = Some((stale, Done::Frame));
new.run(Pull(Script::LOADING));
assert_eq!(posters_shown(&new), 0, "frame 0 isn't the picture at 0.3");
assert!(new.c.meta.is_some(), "its facts still count");
let current = new.fake.asked;
assert_ne!(current, stale, "the pull asked for 0.3");
new.fake.done = Some((current, Done::Frame));
new.run(Pull(Script::LOADING));
assert_eq!(posters_shown(&new), 1);
}
/// A seek past the end that the clip's own length clamps back onto the poster's time is the same
/// picture, so the finished poster shows rather than waiting for a redundant decode of the end.
/// // differs from dev: dev compared the raw times, which left the surface blank.
#[test]
fn a_seek_past_the_end_still_shows_the_poster_its_length_clamps_to() {
let mut new = clip(false, &[Seek(1.0), Pull(Script::LOADING), Seek(2.0)]);
let stale = new.fake.asked;
new.fake.done = Some((stale, Done::Frame));
new.run(Pull(Script::LOADING));
assert_eq!(new.c.duration, Some(1.0), "the answer opened the clip");
assert_eq!(posters_shown(&new), 1, "the poster at the end is the picture the seek asks for");
}
/// A slow worker, each answer one request behind, while the app seeks to the same time again
/// and again: every answer is for the time asked for, so each shows.
#[test]
fn posters_for_repeated_seeks_to_one_time_all_show() {
let mut c = Control::default();
let meta = Meta { duration: 1.0, size: Some((64, 36)), frame: 0.25, sound: false };
let (mut owed, mut shown) = (None, 0);
for _ in 0..30 {
step(&mut c, Event::Seek(0.3));
let AskPoster(_, attempt) = only(step(&mut c, Event::Pull)) else { panic!("asks for a poster") };
if let Some(answered) = owed.replace(attempt)
&& step(&mut c, Event::PosterDone { attempt: answered, result: Ok(meta) }) == Effects::one(Effect::ShowPoster)
{
shown += 1;
}
}
assert_eq!(shown, 29);
}
#[test]
fn a_superseded_poster_keeps_the_clips_frame_timing() {
let mut c = Control::default();
let AskPoster(0.0, stale) = only(step(&mut c, Event::Preload)) else { panic!("asks for a poster") };
step(&mut c, Event::Play);
step(&mut c, Event::PlayerMade { created: rune_core::time::now() });
// The poster lands after the player took over, before its item is ready.
let sixty = Meta { duration: 1.0, size: Some((64, 36)), frame: 1.0 / 60.0, sound: false };
assert!(step(&mut c, Event::PosterDone { attempt: stale, result: Ok(sixty) }).is_empty());
let now = rune_core::time::now();
for effect in step(&mut c, Event::Item { item: Item::Ready, now }) {
if effect == Effect::ReadFacts {
// What a ready item reports, which has no frame timing of its own.
c.open(Ok(Meta { duration: 1.0, size: Some((64, 36)), frame: 1.0 / 30.0, sound: false }));
}
}
step(&mut c, Event::Framed { shown: 0.0 });
step(&mut c, Event::Pause);
step(&mut c, Event::Seek(0.02));
step(&mut c, Event::Reconcile { now });
assert_eq!(c.meta.map(|m| m.frame), Some(1.0 / 60.0));
let Stage::Ready { settle, .. } = c.stage else { panic!("ready") };
assert!(settle.waiting(), "20 ms is the next frame at 60 fps, so the pull waits for it");
}
fn only(effects: Effects<Effect>) -> Effect {
let mut effects = effects.into_iter();
let effect = effects.next().unwrap();
assert!(effects.next().is_none());
effect
}
use Effect::AskPoster;
#[test]
fn an_audio_load_failure_fails_the_clip() {
let new = clip(true, &[LoadAudio, Land(Done::Err), Pull(Script::READY)]);
assert_eq!(new.c.state(), PlayerState::Failed("load failed".into()));
}
#[test]
fn an_audio_load_error_after_another_open_changes_nothing() {
let mut new = clip(true, &[LoadAudio, Open, Play, Pull(Script::READY)]);
assert!(new.c.stage.ready());
let generation = new.c.generation;
new.run(Land(Done::Err));
new.run(Pull(Script::READY));
assert_eq!(new.c.state(), PlayerState::Playing);
assert!(!new.fake.log.contains(&Cmd::Drop));
assert_eq!(new.c.generation, generation);
}
#[test]
fn an_audio_load_error_before_another_open_fails_the_clip() {
let mut new = clip(true, &[LoadAudio, Play, Land(Done::Err), Pull(Script::READY)]);
assert_eq!(new.c.state(), PlayerState::Failed("load failed".into()));
new.run(Open);
new.run(Pull(Script::READY));
assert_eq!(new.c.state(), PlayerState::Failed("load failed".into()));
assert!(!new.fake.log.contains(&Cmd::Make));
}
/// A request before a player and one after it, both owed: each answer carries its own request.
#[test]
fn overlapping_requests_either_side_of_a_player_answer_for_themselves() {
walk(
&[Preload, Play, Pull(Script::LOADING), Pause, Park, Pull(Script::LOADING)],
&[Play, Pause, Seek(0.3), Land(Done::Err), Land(Done::Frame), Land(Done::Facts), Park, Pull(Script::LOADING), Pull(Script::FRAME)],
6,
);
}
/// Two paused seeks' requests, both owed, and what lands for each in any order.
#[test]
fn paused_seeks_answer_for_their_own_requests() {
walk(
&[Pull(Script::LOADING), Seek(0.3), Pull(Script::LOADING)],
&[Seek(0.6), Land(Done::Err), Land(Done::Frame), Land(Done::FrameFails), Open, Play, Pull(Script::LOADING), Pull(Script::FRAME)],
6,
);
}
/// Every order of two requests either side of a player, with answers that fail or land.
#[test]
fn late_poster_answers_in_any_order_match_the_fenced_flags() {
walk(
&[],
&[Play, Pause, Seek(0.3), Preload, Land(Done::Err), Land(Done::Frame), Land(Done::FrameFails), Fail, Park, Pull(Script::LOADING), Pull(Script::FRAME)],
6,
);
}
@@ -0,0 +1,600 @@
//! Every short sequence through a clip's machine, since the handle, the clocks, the poster worker
//! and the native player report in whatever order they like. The real [`step`] and the real
//! [`turn`](super::super::turn::turn) run against a scripted native player; beside them runs
//! `Old`, a transcription of the fields and branches the machine replaced, which calls none of it.
use super::super::turn::{Port, Turn, reconcile, turn};
use super::*;
use rune_core::machine::Attempt;
#[path = "phases_old_tests.rs"]
mod old;
use old::Old;
// The script both sides follow.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Reports {
Loading,
Ready,
Failed,
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Frame {
Same,
New(f64),
PushFails,
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Script {
on_main: bool,
make_fails: bool,
item: Reports,
frame: Frame,
item_time: f64,
current: f64,
player_rate: f32,
}
impl Script {
const LOADING: Script = Script { on_main: true, make_fails: false, item: Reports::Loading, frame: Frame::Same, item_time: 0.0, current: 0.0, player_rate: 0.0 };
const READY: Script = Script { item: Reports::Ready, player_rate: 1.0, item_time: 0.4, current: 0.4, ..Script::LOADING };
const FRAME: Script = Script { frame: Frame::New(0.3), item_time: 0.3, current: 0.3, ..Script::READY };
const AT_SEEK: Script = Script { item_time: 0.3, current: 0.3, ..Script::READY };
const END: Script = Script { item_time: 1.0, current: 1.0, ..Script::READY };
const STOPPED: Script = Script { player_rate: 0.0, ..Script::READY };
const ITEM_FAILS: Script = Script { item: Reports::Failed, ..Script::LOADING };
const MAKE_FAILS: Script = Script { make_fails: true, ..Script::LOADING };
const PUSH_FAILS: Script = Script { frame: Frame::PushFails, ..Script::READY };
const OFF_MAIN: Script = Script { on_main: false, ..Script::READY };
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Done {
Facts,
Frame,
FrameFails,
Err,
}
#[derive(Clone, Copy, Debug)]
enum Sym {
Play,
Pause,
Seek(f64),
Rate(f32),
Looping(bool),
Muted(bool),
Open,
OpenFails,
Fail,
Clock(f64),
Preload,
LoadAudio,
Done(Done),
Wait(u64),
Park,
Apply,
Pull(Script),
}
/// What the native side was told to do, in order.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Cmd {
Ask(f64),
Poster(u64),
Make,
Drop,
Unpark,
Park,
Orient,
Muted(bool),
Seek(f64),
Rate(f32),
Restart(f32),
Frame(u64),
Placeholder,
Returned(bool),
/// Checked for the main thread.
OnMain,
/// Read the player's rate.
ReadRate,
}
#[derive(Clone, Debug, PartialEq)]
enum SettleView {
Still,
Seeking(Instant, f64),
Holding(f64),
}
/// Everything either side can show.
#[derive(Clone, Debug, PartialEq)]
struct View {
state: PlayerState,
playing: bool,
ended: bool,
drawn: bool,
anchor: Option<(f64, f64)>,
rate: f32,
seek: Option<f64>,
time: f64,
duration: Option<f64>,
size: Option<(u32, u32)>,
generation: u64,
frame_id: u64,
poster: u8,
fence: u32,
player: bool,
ready: bool,
created: Option<Instant>,
player_muted: bool,
player_rate: f32,
settle: SettleView,
shown: Option<f64>,
live: bool,
log: Vec<Cmd>,
}
// The new code, on a scripted native player.
#[derive(Clone)]
struct Fake {
script: Script,
/// The caller already checked for the main thread, as an audio tick does.
checked: bool,
surface: bool,
done: Option<(Attempt, Done)>,
kept: Option<Done>,
/// The attempt of the newest poster request.
asked: Attempt,
/// The requests the worker still owes, oldest (in flight) first.
pending: Vec<Attempt>,
player: bool,
now: Instant,
log: Vec<Cmd>,
}
impl Port for Fake {
fn on_main(&mut self) -> bool {
if !self.checked {
self.checked = true;
self.log.push(Cmd::OnMain);
}
self.script.on_main
}
fn take_poster(&mut self) -> Option<(Attempt, Result<Meta, String>)> {
let (attempt, done) = self.done.take()?;
if done == Done::Err {
return Some((attempt, Err("load failed".into())));
}
self.kept = Some(done);
Some((attempt, Ok(Meta { duration: 1.0, size: Some((64, 36)), frame: 0.25, sound: false })))
}
fn show_poster(&mut self, next_id: &mut dyn FnMut() -> u64) -> Result<(), String> {
match (self.kept.take(), self.surface) {
(Some(Done::Frame), true) => {
let id = next_id();
self.log.push(Cmd::Poster(id));
Ok(())
}
(Some(Done::FrameFails), true) => {
next_id();
Err("poster push failed".into())
}
_ => Ok(()),
}
}
fn ask_poster(&mut self, at: f64, attempt: Attempt) {
self.asked = attempt;
queue(&mut self.pending, attempt);
self.log.push(Cmd::Ask(at));
}
fn make_player(&mut self) -> Result<Instant, String> {
if self.script.make_fails {
return Err("couldn't make a player".into());
}
self.log.push(Cmd::Make);
self.player = true;
Ok(self.now)
}
fn drop_player(&mut self) {
self.player = false;
self.log.push(Cmd::Drop);
}
fn unpark(&mut self) {
self.log.push(Cmd::Unpark);
}
fn item(&self) -> Item {
match self.script.item {
Reports::Loading => Item::Loading,
Reports::Ready => Item::Ready,
Reports::Failed => Item::Failed("item failed".into()),
}
}
fn orient(&mut self) {
self.log.push(Cmd::Orient);
}
fn item_facts(&self) -> Meta {
Meta { duration: 2.0, size: Some((32, 18)), frame: 1.0 / 30.0, sound: false }
}
fn alive(&self) -> bool {
self.player
}
fn set_muted(&mut self, muted: bool) {
self.log.push(Cmd::Muted(muted));
}
fn set_volume(&mut self, _: f32) {}
fn seek_to(&mut self, at: f64) {
self.log.push(Cmd::Seek(at));
}
fn set_rate(&mut self, rate: f32) {
self.log.push(Cmd::Rate(rate));
}
fn restart(&mut self, rate: f32) {
self.log.push(Cmd::Restart(rate));
}
fn frame(&mut self, next_id: &mut dyn FnMut() -> u64) -> (f64, Result<Option<f64>, String>) {
let landed = match self.script.frame {
Frame::Same => Ok(None),
Frame::New(shown) => {
let id = next_id();
self.log.push(Cmd::Frame(id));
Ok(Some(shown))
}
Frame::PushFails => {
next_id();
Err("frame push failed".into())
}
};
(self.script.item_time, landed)
}
fn current(&self) -> f64 {
self.script.current
}
fn stopped(&mut self) -> bool {
self.log.push(Cmd::ReadRate);
self.script.player_rate == 0.0
}
}
#[derive(Clone)]
struct New {
c: Control,
fake: Fake,
}
impl New {
fn new(audio: bool, now: Instant) -> Self {
let kind = if audio { Kind::Audio } else { Kind::Video };
Self {
c: Control { muted: !audio, kind, ..Control::default() },
fake: Fake { script: Script::READY, checked: false, surface: !audio, done: None, kept: None, asked: Attempt::default(), pending: Vec::new(), player: false, now, log: Vec::new() },
}
}
/// `macos::step_audio` and `macos::finish`, around the real turn.
fn tick(&mut self, script: Script) -> bool {
let audio = self.c.kind == Kind::Audio;
if audio {
self.fake.log.push(Cmd::OnMain);
if !script.on_main {
return false;
}
}
self.fake.script = script;
self.fake.checked = audio;
let now = self.fake.now;
match turn(&mut self.c, &mut self.fake, now) {
Turn::Idle => false,
Turn::Loading => true,
Turn::Finished => {
let (active, park) = (self.c.active(), self.c.parkable());
self.fake.log.push(if park { Cmd::Park } else { Cmd::Unpark });
active
}
}
}
/// `Shared::pull`, around the real turn.
fn shared_pull(&mut self, script: Script) -> bool {
let active = self.tick(script);
if self.c.kind == Kind::Audio {
return active;
}
for effect in step(&mut self.c, Event::Drawn) {
if effect == Effect::Placeholder {
self.fake.log.push(Cmd::Placeholder);
}
}
active && !self.c.failed()
}
/// `macos::apply`, around the real reconcile.
fn apply(&mut self) {
if self.c.failed() {
return;
}
if self.c.kind == Kind::Audio {
let needs_tick = self.tick(Script::READY);
self.fake.log.push(Cmd::Returned(needs_tick));
return;
}
if !self.fake.player {
return;
}
let now = self.fake.now;
self.fake.script = Script::READY;
reconcile(&mut self.c, &mut self.fake, now);
if self.c.playing() {
self.fake.log.push(Cmd::Unpark);
}
}
fn send(&mut self, event: Event) {
let effects = step(&mut self.c, event);
super::super::turn::carry(&mut self.c, &mut self.fake, effects);
}
fn run(&mut self, sym: Sym) {
match sym {
Sym::Play => self.send(Event::Play),
Sym::Pause => self.send(Event::Pause),
Sym::Seek(t) => self.send(Event::Seek(t)),
Sym::Rate(r) => self.send(Event::Rate(r)),
Sym::Looping(l) => self.c.looping = l,
Sym::Muted(m) => self.c.muted = m,
Sym::Open => self.c.open(Ok(Meta { duration: 1.0, size: Some((64, 36)), frame: 0.25, sound: false })),
Sym::OpenFails => self.c.open(Err("open failed".into())),
Sym::Fail => self.c.fail("failed".into()),
Sym::Clock(t) => self.c.advance_virtual(t),
Sym::Preload => self.send(Event::Preload),
Sym::LoadAudio => self.send(Event::LoadAudio),
Sym::Done(done) => self.fake.done = Some((answer(&mut self.fake.pending, self.fake.asked), done)),
Sym::Wait(s) => self.fake.now += Duration::from_secs(s),
Sym::Park => {
step(&mut self.c, Event::Parked);
self.fake.player = false;
}
Sym::Apply => self.apply(),
Sym::Pull(s) => {
let active = self.shared_pull(s);
self.fake.log.push(Cmd::Returned(active));
}
}
}
fn view(&self) -> View {
let c = &self.c;
assert_eq!(c.stage.has_player(), self.fake.player, "the stage says what the native side holds");
let (created, player_muted, player_rate, settle, shown) = match c.stage {
Stage::Loading { created, muted, .. } => (Some(created), muted, 0.0, Settle::Still, None),
Stage::Ready { created, muted, rate, settle, shown, .. } => (Some(created), muted, rate, settle, shown),
_ => (None, false, 0.0, Settle::Still, None),
};
View {
state: c.state(),
playing: c.playing(),
ended: c.run == Run::Ended,
drawn: matches!(c.run, Run::Failed { drawn: true, .. }),
anchor: if let Run::Playing { anchor } = c.run { anchor } else { None },
rate: c.rate,
seek: c.seek,
time: c.time,
duration: c.duration,
size: c.size,
generation: c.generation,
frame_id: c.frame_id,
poster: match c.stage {
Stage::Unasked => 0,
Stage::Poster => 1,
_ => 2,
},
fence: c.posters.current().0,
player: c.stage.has_player(),
ready: c.stage.ready(),
created,
player_muted,
player_rate,
settle: match settle {
Settle::Still => SettleView::Still,
Settle::Seeking { since, to } => SettleView::Seeking(since, to),
Settle::Holding { to } => SettleView::Holding(to),
},
shown,
live: c.live(),
log: self.fake.log.clone(),
}
}
}
/// The poster worker's queue: the request in flight, then the newest one waiting, which a
/// later request replaces.
fn queue<T>(pending: &mut Vec<T>, request: T) {
if pending.len() == 2 {
pending.pop();
}
pending.push(request);
}
/// The request a finished load answers: the one in flight, else (a load the script made up) the
/// newest.
fn answer<T: Copy>(pending: &mut Vec<T>, newest: T) -> T {
if pending.is_empty() { newest } else { pending.remove(0) }
}
/// Walks every sequence up to `depth` from `(new, old)`, comparing after every symbol.
fn descend(new: &New, old: &Old, alphabet: &[Sym], depth: usize, seq: &mut Vec<Sym>, walked: &mut u64) {
if depth == 0 {
return;
}
for &sym in alphabet {
let (mut n, mut o) = (new.clone(), old.clone());
seq.push(sym);
n.run(sym);
o.run(sym);
assert_eq!(n.view(), o.view(), "after {seq:?}");
n.fake.log.clear();
o.log.clear();
*walked += 1;
descend(&n, &o, alphabet, depth - 1, seq, walked);
seq.pop();
}
}
/// Each kind of clip, from the state `prefix` leaves it in.
fn walk(prefix: &[Sym], alphabet: &[Sym], depth: usize) {
let now = rune_core::time::now();
for audio in [false, true] {
let (mut new, mut old) = (New::new(audio, now), Old::new(audio, now));
let mut seq = Vec::new();
for &sym in prefix {
seq.push(sym);
new.run(sym);
old.run(sym);
assert_eq!(new.view(), old.view(), "after {seq:?}");
new.fake.log.clear();
old.log.clear();
}
let mut walked = 0;
descend(&new, &old, alphabet, depth, &mut seq, &mut walked);
assert!(walked >= alphabet.len().pow(depth as u32) as u64);
}
}
use Sym::{Apply, Done as Land, Fail, LoadAudio, Looping, Muted, Open, OpenFails, Park, Pause, Play, Preload, Pull, Rate, Seek, Wait};
#[test]
fn the_handle_and_the_headless_clock_match_the_old_flags() {
let clock = Sym::Clock;
walk(&[], &[Play, Pause, Seek(0.3), Seek(9.0), Seek(f64::NAN), Rate(2.0), Looping(true), Open, OpenFails, Fail, clock(0.0), clock(0.4), clock(2.0)], 5);
}
#[test]
fn a_playing_headless_clip_ends_loops_and_rewinds_like_the_old_flags() {
let clock = Sym::Clock;
walk(&[Open, Play], &[Play, Pause, Seek(0.3), Rate(2.0), Looping(true), Looping(false), clock(0.0), clock(0.4), clock(2.0)], 6);
}
#[test]
fn every_report_in_any_order_matches_the_old_flags() {
walk(
&[],
&[
Play,
Pause,
Seek(0.3),
Muted(false),
Land(Done::Frame),
Land(Done::Facts),
Land(Done::FrameFails),
Land(Done::Err),
Preload,
LoadAudio,
Fail,
Park,
Apply,
Wait(31),
Pull(Script::LOADING),
Pull(Script::FRAME),
Pull(Script::END),
Pull(Script::STOPPED),
Pull(Script::ITEM_FAILS),
Pull(Script::MAKE_FAILS),
Pull(Script::PUSH_FAILS),
Pull(Script::OFF_MAIN),
],
5,
);
}
#[test]
fn posters_and_players_race_like_the_old_flags() {
walk(
&[],
&[Play, Pause, Seek(0.3), Land(Done::Frame), Land(Done::Facts), Preload, Pull(Script::LOADING), Pull(Script::FRAME), Park],
7,
);
}
#[test]
fn a_failing_poster_or_frame_stops_the_clip_like_the_old_flags() {
walk(&[], &[Play, Land(Done::FrameFails), Land(Done::Frame), Pull(Script::LOADING), Pull(Script::PUSH_FAILS), Pull(Script::FRAME), Park], 6);
}
#[test]
fn a_ready_player_seeks_ends_and_parks_like_the_old_flags() {
walk(
&[Open, Play, Pull(Script::READY)],
&[Play, Pause, Seek(0.3), Seek(0.31), Rate(2.0), Looping(true), Wait(3), Apply, Park, Pull(Script::FRAME), Pull(Script::AT_SEEK), Pull(Script::END), Pull(Script::STOPPED)],
6,
);
}
#[test]
fn a_loading_player_times_out_like_the_old_flags() {
walk(&[Play, Land(Done::Facts), Pull(Script::LOADING)], &[Seek(0.3), Muted(false), Pause, Wait(31), Wait(3), Apply, Pull(Script::LOADING), Pull(Script::READY), Park], 5);
}
#[path = "phases_poster_tests.rs"]
mod poster;
#[test]
fn the_newest_seek_replaces_an_earlier_one() {
let now = rune_core::time::now();
let mut s = Settle::default();
s.seek(3.0, false, now);
assert!(s.waiting());
// Paused, back within the frame on screen before the far seek landed: that frame is
// already showing, so there's nothing left to wait for.
s.seek(0.5, true, now);
assert!(!s.waiting() && s.pending());
s.observe(0.5, false, false);
assert_eq!(s, Settle::Still);
}
#[test]
fn a_seek_lands_with_a_frame_or_for_audio_at_its_position() {
let now = rune_core::time::now();
let mut video = Settle::default();
video.seek(2.0, false, now);
video.observe(2.0, false, false);
assert!(video.waiting(), "video waits for the frame, not the position");
video.framed();
assert_eq!(video, Settle::Still);
let mut audio = Settle::default();
audio.seek(2.0, false, now);
audio.observe(1.0, true, true);
assert!(audio.waiting());
audio.observe(2.1, true, true);
assert_eq!(audio, Settle::Still);
}
#[test]
fn a_hold_ends_when_playback_moves_on_and_a_frame_does_not_end_it() {
let now = rune_core::time::now();
let mut s = Settle::default();
s.seek(0.5, true, now);
s.framed();
assert_eq!(s, Settle::Holding { to: 0.5 });
s.observe(0.4, true, false);
assert_eq!(s, Settle::Still);
}
#[test]
fn a_seek_that_never_lands_expires() {
let now = rune_core::time::now();
let mut s = Settle::default();
s.seek(2.0, false, now);
s.expire(now + SEEK_PATIENCE);
assert!(s.waiting());
s.expire(now + SEEK_PATIENCE + Duration::from_millis(1));
assert_eq!(s, Settle::Still);
// A hold has nothing to wait for, so nothing expires it.
s.seek(1.0, true, now);
s.expire(now + Duration::from_secs(60));
assert_eq!(s, Settle::Holding { to: 1.0 });
}
+516
View File
@@ -0,0 +1,516 @@
use super::*;
fn meta() -> Meta {
Meta { duration: 1.0, size: Some((64, 36)), frame: 0.25, sound: false }
}
#[test]
fn new_videos_are_muted_paused_and_loading() {
let v = Video::file("missing.mp4");
assert!(v.muted());
assert!(!v.looping());
assert!(!v.is_playing());
assert_eq!(v.rate(), 1.0);
assert_eq!(v.time(), 0.0);
assert_eq!(v.duration(), None);
assert_eq!(v.natural_size(), None);
assert!(!v.is_audio());
#[cfg(target_os = "macos")]
assert_eq!(v.state(), PlayerState::Loading);
assert_eq!(v.source(), &MediaSource::File("missing.mp4".into()));
}
#[test]
fn sources_tell_urls_from_paths() {
assert_eq!(MediaSource::from("https://example.com/a.mp3"), MediaSource::Url("https://example.com/a.mp3".into()));
assert_eq!(MediaSource::from("file:///tmp/a.wav".to_string()), MediaSource::Url("file:///tmp/a.wav".into()));
assert_eq!(MediaSource::from("sounds/a.m4a"), MediaSource::File("sounds/a.m4a".into()));
assert_eq!(MediaSource::from(std::path::Path::new("a.mp3")), MediaSource::File("a.mp3".into()));
}
#[test]
fn audio_starts_unmuted_with_no_size() {
let a = Player::audio("missing.m4a");
assert!(a.is_audio());
assert!(!a.muted(), "audio is audible by default");
assert_eq!(a.natural_size(), None);
}
/// A clip's extension comes from the last segment of its path, never the host or query.
#[cfg(target_os = "macos")]
#[test]
fn extensions_come_from_the_last_path_segment() {
let ext = |s: &str| super::macos::extension(&MediaSource::from(s));
assert_eq!(ext("https://example.com/media/clip"), None);
assert_eq!(ext("https://host.ogg/clip"), None);
assert_eq!(ext("https://host.ogg"), None);
assert_eq!(ext("https://example.com/a.b/clip?x=1.ogg#t=2.webm"), None);
assert_eq!(ext("https://example.com/media/clip.OGG?v=2#t"), Some("ogg".into()));
assert_eq!(ext("file:///tmp/a.b/clip.opus"), Some("opus".into()));
assert_eq!(ext("sounds.d/clip"), None);
assert_eq!(ext("sounds/clip.webm"), Some("webm".into()));
assert_eq!(ext("sounds/clip."), None);
}
/// Windows reads WebM and Ogg when the system has their extensions, so it finds out on open.
#[cfg(not(target_os = "windows"))]
#[test]
fn webm_video_fails_at_once() {
let a = Player::url("https://example.com/clips/tap.webm?v=2");
let PlayerState::Failed(message) = a.state() else { panic!("{:?}", a.state()) };
#[cfg(target_os = "macos")]
assert!(message.contains(".webm isn't supported on macOS"), "{message}");
#[cfg(not(target_os = "macos"))]
assert_eq!(message, "video playback isn't supported on this platform yet");
a.play();
assert!(!a.is_playing(), "a failed clip doesn't play");
}
/// An audio clip no backend has seen, so nothing has changed before the test starts.
fn bare_audio() -> Arc<Shared> {
Arc::new(Shared {
source: MediaSource::from("missing.m4a"),
headers: Vec::new(),
kind: Kind::Audio,
ctl: Mutex::new(Control { muted: false, kind: Kind::Audio, ..Control::default() }),
wakes: Mutex::new(Vec::new()),
waker: WakerSlot::default(),
notified: AtomicU64::new(0),
native: Mutex::new(backend::Native::default()),
backend: &BACKEND,
})
}
fn quiet_audio() -> Player {
let shared = bare_audio();
Player { surface: NativeSurface::with_video(shared.clone()), shared }
}
#[test]
fn the_waker_hears_each_state_change_once() {
let a = quiet_audio();
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let seen = calls.clone();
a.set_waker(Arc::new(move || {
seen.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}));
a.shared.settle(false);
assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 0, "nothing changed yet");
a.shared.ctl.lock().unwrap().open(Ok(Meta { duration: 2.0, size: None, frame: 1.0 / 30.0, sound: false }));
a.shared.settle(false);
a.shared.settle(false);
assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1);
a.shared.ctl.lock().unwrap().fail("gone".into());
a.shared.settle(false);
assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 2);
}
/// An unsupported format fails inside the constructor, before any waker can be set: setting
/// one afterwards still delivers that failure, once.
#[cfg(not(target_os = "windows"))]
#[test]
fn a_waker_set_after_a_failure_hears_it_once() {
let a = Player::url("tap.ogv");
assert!(matches!(a.shared.snapshot().state, PlayerState::Failed(_)));
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let seen = calls.clone();
a.set_waker(Arc::new(move || {
seen.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}));
a.shared.settle(true);
a.play();
assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1);
}
#[test]
fn a_seek_before_the_clip_opens_is_clamped_when_it_does() {
let v = Video::file("missing.mp4");
v.seek(30.0);
assert_eq!(v.shared.ctl.lock().unwrap().seek, Some(30.0), "no duration yet");
v.shared.ctl.lock().unwrap().open(Ok(meta()));
let c = v.shared.ctl.lock().unwrap();
assert_eq!((c.seek, c.time), (Some(1.0), 1.0));
}
/// The parked list is process-wide: these tests take turns so each sees only its own clips.
#[cfg(target_os = "macos")]
static PARKED_TESTS: Mutex<()> = Mutex::new(());
/// `play()` on a parked clip only unparks it on its next pull or edit on the main thread;
/// until then, parking others must not release it.
#[cfg(target_os = "macos")]
#[test]
fn parking_never_releases_a_playing_clip() {
let _only = PARKED_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let clips: Vec<Video> = (0..6).map(|_| Video::file(fixture())).collect();
let mut released = Vec::new();
released.extend(backend::parked_with(&clips[0].shared));
clips[0].play();
for clip in &clips[1..] {
released.extend(backend::parked_with(&clip.shared));
}
assert!(!released.iter().any(|r| Arc::ptr_eq(r, &clips[0].shared)), "the playing clip stays");
assert_eq!(released.len(), 1, "four of the five paused clips stay parked");
assert!(Arc::ptr_eq(&released[0], &clips[1].shared), "the oldest paused clip goes");
}
/// Records, on drop, whether the parking pass's lock was free: a destructor that takes it would
/// deadlock in the app.
#[cfg(target_os = "macos")]
struct DroppedDuringParking;
#[cfg(target_os = "macos")]
thread_local! {
/// None until a clip's destructor runs: Some(free) for whether PARKED was free then.
static DROPPED: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}
#[cfg(target_os = "macos")]
impl Drop for DroppedDuringParking {
fn drop(&mut self) {
DROPPED.with(|flag| flag.set(Some(macos::parked_free())));
}
}
/// A clip's last owner can go away while a parking pass holds PARKED. Its destructor runs app
/// code (the waker captures), which may play another parked clip and re-enter `unpark`, so it
/// must run after the lock is released. // differs from dev: dev dropped the upgrade in the pass.
#[cfg(target_os = "macos")]
#[test]
fn a_clip_dropped_during_a_parking_pass_is_destroyed_outside_the_lock() {
let _only = PARKED_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let target = bare_audio();
let probe = DroppedDuringParking;
target.waker.set(Arc::new(move || {
let _ = &probe;
}));
let other = bare_audio();
// Nothing to release: the list holds one paused clip.
assert!(backend::parked_with(&target).is_empty());
// The pass over `other` drops the target's last owner while it holds the target's upgrade.
macos::on_kept(move || drop(target));
assert!(backend::parked_with(&other).is_empty());
assert_eq!(
DROPPED.with(|flag| flag.take()),
Some(true),
"the clip's destructor ran while PARKED was held (it would deadlock here)"
);
}
/// A redraw of a parked clip re-parks it every frame, where dev allocated nothing: the pass's
/// upgraded owners keep their capacity across passes. // differs from dev: dev's temporary
/// upgrades needed no buffer at all.
#[cfg(target_os = "macos")]
#[test]
fn a_warm_parking_pass_keeps_its_buffers_capacity() {
let _only = PARKED_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let clips: Vec<Video> = (0..4).map(|_| Video::file(fixture())).collect();
// Park all four, then pass over them until the buffer fits them.
for _ in 0..5 {
for clip in &clips {
assert!(backend::parked_with(&clip.shared).is_empty(), "four parked clips fit");
}
}
let warm = macos::held_capacity();
assert!(warm >= clips.len(), "the pass keeps every upgraded clip: {warm}");
for _ in 0..100 {
for clip in &clips {
assert!(backend::parked_with(&clip.shared).is_empty(), "nothing is evicted");
}
}
assert_eq!(macos::held_capacity(), warm, "a warm redraw of parked clips allocates nothing");
}
/// Only formats that no build reads fail at once; with `ogg-audio`, Ogg audio opens later.
#[cfg(target_os = "macos")]
#[test]
fn only_formats_no_build_reads_fail_at_once() {
let ogv = Player::audio("https://example.com/clip.ogv");
assert!(matches!(ogv.shared.snapshot().state, PlayerState::Failed(e) if e.contains(".ogv")));
let ogg = Player::audio("https://example.com/clip.ogg");
let failed = matches!(ogg.shared.snapshot().state, PlayerState::Failed(_));
assert_eq!(failed, !cfg!(feature = "ogg-audio"), "{:?}", ogg.shared.snapshot().state);
}
#[test]
fn handle_edits_are_shared_and_validated() {
let v = Video::url("https://example.com/clip.mp4");
let other = v.clone();
other.set_rate(2.0);
other.set_rate(-1.0);
other.set_rate(f32::NAN);
other.set_looping(true);
other.set_muted(false);
other.seek(-3.0);
assert_eq!(v.rate(), 2.0);
assert!(v.looping());
assert!(!v.muted());
assert_eq!(v.time(), 0.0);
v.play();
#[cfg(target_os = "macos")]
{
assert!(other.is_playing());
// Still loading: playing is intent until the clip opens.
assert_eq!(v.state(), PlayerState::Loading);
}
}
#[test]
fn state_follows_open_play_end_and_failure() {
let mut c = Control::default();
c.open(Ok(meta()));
assert_eq!(c.state(), PlayerState::Ready);
assert_eq!((c.duration, c.size), (Some(1.0), Some((64, 36))));
step(&mut c, Event::Play);
assert_eq!(c.state(), PlayerState::Playing);
c.advance_virtual(10.0);
c.advance_virtual(10.5);
assert_eq!(c.time, 0.5);
let generation = c.generation;
c.advance_virtual(11.25);
assert_eq!((c.time, &c.run), (1.0, &Run::Ended));
assert_eq!(c.state(), PlayerState::Ended);
assert!(c.generation > generation, "ending re-runs views");
c.fail("boom".into());
c.fail("second".into());
assert_eq!(c.state(), PlayerState::Failed("boom".into()));
}
#[test]
fn virtual_time_loops_rates_and_seeks() {
let mut c = Control::default();
c.open(Ok(meta()));
step(&mut c, Event::Play);
c.looping = true;
c.rate = 2.0;
c.advance_virtual(0.0);
c.advance_virtual(0.6);
assert!((c.time - 0.2).abs() < 1e-9, "1.2 s wraps to 0.2: {}", c.time);
assert!(c.playing());
step(&mut c, Event::Seek(0.75));
c.advance_virtual(5.0);
assert_eq!(c.time, 0.75);
c.advance_virtual(5.1);
assert!((c.time - 0.95).abs() < 1e-9);
// Paused time stays put whatever the clock does.
step(&mut c, Event::Pause);
c.advance_virtual(9.0);
assert!((c.time - 0.95).abs() < 1e-9);
}
#[test]
fn playing_after_the_end_restarts_from_zero() {
let v = Video::file("missing.mp4");
{
let mut c = v.shared.ctl.lock().unwrap();
c.open(Ok(meta()));
c.time = 1.0;
c.run = Run::Ended;
}
assert_eq!(v.state(), PlayerState::Ended);
v.play();
let c = v.shared.ctl.lock().unwrap();
assert_eq!(c.seek, Some(0.0));
assert!(c.playing());
}
#[test]
fn display_positions_loop_or_end() {
let mut c = Control::default();
c.open(Ok(meta()));
step(&mut c, Event::Play);
assert!(!c.observe(0.4, false));
assert_eq!(c.time, 0.4);
c.looping = true;
assert!(c.observe(1.0, true), "looping restarts the player");
assert_eq!((c.time, c.playing()), (0.0, true));
c.looping = false;
assert!(!c.observe(1.2, true));
assert_eq!((c.time, c.playing(), c.state()), (1.0, false, PlayerState::Ended));
}
#[test]
fn frames_snap_to_whole_frames_inside_the_clip() {
let m = meta();
assert_eq!(m.frames(), 4);
assert_eq!(m.frame_index(0.0), 0);
assert_eq!(m.frame_index(0.2499), 0);
assert_eq!(m.frame_index(0.25), 1);
assert_eq!(m.frame_index(1.0), 3, "the end shows the last frame");
assert_eq!(m.frame_index(-1.0), 0);
assert_eq!(m.frame_time(1), 0.375);
assert_eq!(m.frame_time(3), 0.875);
}
#[test]
fn the_last_handle_or_element_frees_the_player() {
let v = Video::file("missing.mp4");
let shared = Arc::downgrade(&v.shared);
// An element keeps the surface, and through it the player.
let in_tree = v.surface().clone();
drop(v);
assert!(shared.upgrade().is_some());
drop(in_tree);
assert!(shared.upgrade().is_none());
}
#[cfg(target_os = "macos")]
fn fixture() -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../rune/tests/fixtures/rgbw.mp4")
}
#[cfg(target_os = "macos")]
fn sound(name: &str) -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../rune/tests/fixtures").join(name)
}
/// Headless audio opens on first read and never plays: no player, no sound. With no runtime
/// stepping on its thread, time holds.
#[cfg(target_os = "macos")]
#[test]
fn headless_audio_opens_on_read_and_holds_time() {
let a = Player::audio(sound("silence.m4a"));
a.set_muted(true);
assert_eq!(a.state(), PlayerState::Ready);
let d = a.duration().unwrap();
assert!((d - 1.0).abs() < 0.1, "{d}");
assert_eq!(a.natural_size(), None);
a.play();
assert_eq!(a.state(), PlayerState::Playing);
assert_eq!(a.time(), 0.0);
a.seek(0.4);
assert_eq!(a.time(), 0.4);
let wav = Player::audio(sound("silence.wav"));
assert!((wav.duration().unwrap() - 0.5).abs() < 0.01, "{:?}", wav.duration());
let video = Player::audio(fixture());
assert!(matches!(video.state(), PlayerState::Failed(e) if e.contains("no playable audio track")));
}
#[test]
fn requests_carry_headers_without_printing_their_values() {
let request = Player::request("https://example.com/media/a.m4a")
.header("Authorization", "Bearer secret-token")
.header("authorization", "Bearer newer-token")
.header("X-Board", "1");
let printed = format!("{request:?}");
assert!(printed.contains("Authorization") || printed.contains("authorization"), "{printed}");
assert!(!printed.contains("token"), "header values never print: {printed}");
let a = request.audio();
assert!(a.is_audio());
assert_eq!(a.source(), &MediaSource::Url("https://example.com/media/a.m4a".into()));
assert_eq!(a.shared.headers, [("authorization".to_string(), "Bearer newer-token".to_string()), ("X-Board".into(), "1".into())]);
assert!(!format!("{a:?}").contains("token"));
let v = Player::request("https://example.com/media/a.mp4").header("Authorization", "Bearer t").video();
assert!(!v.is_audio() && v.muted());
}
/// A local HTTP server that serves `body` (with byte ranges) only to requests carrying
/// `Authorization: Bearer let-me-in`, and counts the ones that didn't.
#[cfg(target_os = "macos")]
fn serve_with_auth(body: Vec<u8>, content_type: &'static str) -> (String, Arc<std::sync::atomic::AtomicUsize>) {
use std::io::{BufRead, BufReader, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://127.0.0.1:{}/media/clip", listener.local_addr().unwrap().port());
let refused = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let count = refused.clone();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { return };
let (body, count) = (body.clone(), count.clone());
std::thread::spawn(move || {
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut stream = stream;
loop {
let (mut authorized, mut range) = (false, None);
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 { return; }
loop {
let mut header = String::new();
if reader.read_line(&mut header).unwrap_or(0) == 0 { return; }
let header = header.trim_end();
if header.is_empty() { break; }
let (name, value) = header.split_once(':').unwrap_or((header, ""));
match name.trim().to_ascii_lowercase().as_str() {
"authorization" => authorized = value.trim() == "Bearer let-me-in",
"range" => range = value.trim().strip_prefix("bytes=").map(str::to_owned),
_ => {}
}
}
if !authorized {
count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
stream.write_all(b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n").ok();
continue;
}
let len = body.len();
let (start, end) = range.and_then(|r| {
let (a, b) = r.split_once('-')?;
let a: usize = a.parse().ok()?;
let b = b.parse::<usize>().map_or(len - 1, |b| b.min(len - 1));
Some((a, b))
}).unwrap_or((0, len - 1));
let head = format!(
"HTTP/1.1 206 Partial Content\r\nContent-Type: {content_type}\r\nAccept-Ranges: bytes\r\nContent-Range: bytes {start}-{end}/{len}\r\nContent-Length: {}\r\n\r\n",
end + 1 - start
);
if stream.write_all(head.as_bytes()).and_then(|_| stream.write_all(&body[start..=end])).is_err() { return; }
}
});
}
});
(url, refused)
}
/// AVFoundation sends the request's headers: the clip opens from a server that refuses
/// anything without them, and fails without them.
#[cfg(target_os = "macos")]
#[test]
fn headless_audio_opens_with_request_headers() {
let (url, refused) = serve_with_auth(std::fs::read(sound("silence.wav")).unwrap(), "audio/wav");
let a = Player::request(format!("{url}.wav")).header("Authorization", "Bearer let-me-in").audio();
assert_eq!(a.state(), PlayerState::Ready);
assert!((a.duration().unwrap() - 0.5).abs() < 0.01, "{:?}", a.duration());
assert_eq!(refused.load(std::sync::atomic::Ordering::SeqCst), 0, "every request carried the header");
let without = Player::audio(format!("{url}-2.wav"));
assert!(matches!(without.state(), PlayerState::Failed(_)), "{:?}", without.state());
assert!(refused.load(std::sync::atomic::Ordering::SeqCst) > 0);
}
/// A replaced waker's captures drop after the slot's lock: one may read the clip's state and
/// would deadlock there. // differs from dev: dev dropped the old waker under the lock.
#[test]
fn a_replaced_waker_is_dropped_outside_the_slots_lock() {
static FREED: Mutex<Option<bool>> = Mutex::new(None);
struct Probe(Arc<WakerSlot>);
impl Drop for Probe {
fn drop(&mut self) {
*FREED.lock().unwrap() = Some(self.0.free());
}
}
let slot = Arc::new(WakerSlot::default());
let first = Probe(slot.clone());
slot.set(Arc::new(move || {
let _ = &first;
}));
slot.set(Arc::new(|| {}));
assert_eq!(*FREED.lock().unwrap(), Some(true), "the replaced waker dropped while the slot's lock was held");
}
#[cfg(target_os = "macos")]
#[test]
fn preload_decodes_the_first_frame_before_anything_draws_it() {
let v = Video::file(fixture());
assert_eq!(macos::test_poster(&v.shared), None);
// Preload is a no-op headless (frames decode as they draw), so call the backend directly.
macos::preload(&v.shared);
let start = rune_core::time::now();
while macos::test_poster(&v.shared).is_none() && start.elapsed() < std::time::Duration::from_secs(10) {
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert_eq!(macos::test_poster(&v.shared), Some(true), "the first frame decoded off the main thread");
v.preload();
let audio = Player::audio(sound("silence.wav"));
macos::preload(&audio.shared);
assert_eq!(macos::test_poster(&audio.shared), None, "audio has no poster to warm");
}
+155
View File
@@ -0,0 +1,155 @@
//! The order of one video pull or audio tick, apart from AVFoundation: each piece of news goes
//! to [`step`], and what it asks for goes to a [`Port`], so the order runs in tests with no
//! native player.
use super::Control;
use super::Kind;
use super::Meta;
use super::phases::{Effect, Event, Item, step};
use rune_core::machine::{Attempt, Effects};
use rune_core::time::Instant;
/// What a clip's native side can read and do. Holds no phase of its own.
pub(super) trait Port {
fn on_main(&mut self) -> bool;
/// A finished poster load and the attempt it answers, keeping its frame for
/// [`show_poster`](Self::show_poster).
fn take_poster(&mut self) -> Option<(Attempt, Result<Meta, String>)>;
/// Puts the kept frame on the surface, if there is one and a surface to take it.
fn show_poster(&mut self, next_id: &mut dyn FnMut() -> u64) -> Result<(), String>;
fn ask_poster(&mut self, at: f64, attempt: Attempt);
/// Returns when the player was made.
fn make_player(&mut self) -> Result<Instant, String>;
fn drop_player(&mut self);
fn unpark(&mut self);
fn item(&self) -> Item;
fn orient(&mut self);
fn item_facts(&self) -> Meta;
/// Whether the player still holds its objects.
fn alive(&self) -> bool;
fn set_muted(&mut self, muted: bool);
fn set_volume(&mut self, volume: f32);
fn seek_to(&mut self, at: f64);
fn set_rate(&mut self, rate: f32);
fn restart(&mut self, rate: f32);
/// The item time for this frame, and the new frame's item time if one reached the surface.
fn frame(&mut self, next_id: &mut dyn FnMut() -> u64) -> (f64, Result<Option<f64>, String>);
/// The player's position.
fn current(&self) -> f64;
/// Whether the player has stopped. Asked only of one told to run.
fn stopped(&mut self) -> bool;
}
/// How a turn ended.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Turn {
/// Nothing more to do this frame.
Idle,
/// Audio still loading: tick until it does, or times out, so a pending seek or play lands.
Loading,
/// The player was driven: `Control::active` and `Control::parkable` say what's next.
Finished,
}
/// Carries out what `step` asked for. [`Effect::Placeholder`] is drawn by the pull itself.
pub(super) fn carry(c: &mut Control, port: &mut impl Port, effects: Effects<Effect>) {
for effect in effects {
match effect {
Effect::Placeholder => {}
Effect::AskPoster(at, attempt) => port.ask_poster(at, attempt),
Effect::ShowPoster => {
if let Err(e) = port.show_poster(&mut || c.next_frame_id()) {
c.fail(e);
}
}
Effect::MakePlayer => match port.make_player() {
Ok(created) => {
step(c, Event::PlayerMade { created });
}
Err(e) => c.fail(e),
},
Effect::DropPlayer => port.drop_player(),
Effect::Orient => port.orient(),
Effect::ReadFacts => c.open(Ok(port.item_facts())),
Effect::SetMuted(muted) => port.set_muted(muted),
Effect::SetVolume(volume) => port.set_volume(volume),
Effect::SeekTo(at) => port.seek_to(at),
Effect::SetRate(rate) => port.set_rate(rate),
Effect::Restart(rate) => port.restart(rate),
}
}
}
fn send(c: &mut Control, port: &mut impl Port, event: Event) {
let effects = step(c, event);
carry(c, port, effects);
}
/// Bring the player in line with the handle.
pub(super) fn reconcile(c: &mut Control, port: &mut impl Port, now: Instant) {
if port.alive() {
send(c, port, Event::Reconcile { now });
}
}
/// Takes a finished poster load: the clip's facts and, for video, its poster frame.
fn take_poster(c: &mut Control, port: &mut impl Port) {
if let Some((attempt, result)) = port.take_poster() {
send(c, port, Event::PosterDone { attempt, result });
}
}
fn follow(c: &mut Control, port: &mut impl Port, frame_time: Option<f64>, now: Instant) {
let current = port.current();
let stopped = c.stage.running() && port.stopped();
send(c, port, Event::Follow { current, stopped, frame_time, now });
}
/// One pull of a video, or one tick of audio: take a finished load, make or update the player,
/// pull its frame and follow it to the end.
pub(super) fn turn(c: &mut Control, port: &mut impl Port, now: Instant) -> Turn {
take_poster(c, port);
if c.failed() {
send(c, port, Event::Release);
return Turn::Idle;
}
if !port.on_main() {
return Turn::Idle;
}
let fresh = !c.stage.has_player();
send(c, port, Event::Pull);
if !c.stage.has_player() {
return Turn::Idle;
}
if fresh {
port.unpark();
}
let item = port.item();
send(c, port, Event::Item { item, now });
if !c.stage.has_player() {
return Turn::Idle;
}
reconcile(c, port, now);
match (c.kind, c.stage.ready()) {
(Kind::Video, true) => {
let (item_time, landed) = port.frame(&mut || c.next_frame_id());
match landed {
Ok(Some(shown)) => {
step(c, Event::Framed { shown });
}
Ok(None) => {}
Err(e) => {
c.fail(e);
send(c, port, Event::Release);
return Turn::Idle;
}
}
follow(c, port, Some(item_time), now);
}
(Kind::Video, false) => {}
(Kind::Audio, false) => return Turn::Loading,
(Kind::Audio, true) => follow(c, port, None, now),
}
step(c, Event::Finish { now });
Turn::Finished
}
@@ -0,0 +1,45 @@
//! Platforms without a player yet: every clip fails with a clear message, and video draws the
//! neutral placeholder.
use super::*;
fn unsupported(kind: Kind) -> String {
match kind {
Kind::Video => "video playback isn't supported on this platform yet".into(),
Kind::Audio => "audio playback isn't supported on this platform yet".into(),
}
}
#[derive(Default)]
pub(crate) struct Native;
pub(super) fn created(shared: &Arc<Shared>) {
shared.ctl.lock().unwrap().fail(unsupported(shared.kind));
}
pub(super) fn enable() {}
pub(super) fn probe(_: &mut Native, _: &MediaSource, _: &[(String, String)], kind: Kind) -> Result<Meta, String> {
Err(unsupported(kind))
}
pub(super) fn decode(_: &mut Native, _: &MediaSource, _: &[(String, String)], _: f64) -> Result<ByteFrame, String> {
Err(unsupported(Kind::Video))
}
pub(super) fn apply(_: &Arc<Shared>) {}
pub(super) fn drive(_: &Arc<Shared>) {}
pub(super) fn preload(_: &Arc<Shared>) {}
pub(super) fn live_time(_: &Shared, _: bool) -> Option<f64> {
None
}
pub(super) fn pull(_: &Arc<Shared>, _: &NativeSurface, _: Instant) -> bool {
false
}
pub(super) fn due(_: &Shared) -> Option<Instant> {
None
}
+40
View File
@@ -0,0 +1,40 @@
//! The app's waker on a media handle ([`Player`](crate::Player), [`Recorder`](crate::Recorder)),
//! told once per change of the handle's state.
use std::sync::Mutex;
/// The app's waker and the generation it last heard. The generation it compares against is the
/// handle's own, so a change made while no waker was set is told when one is.
#[derive(Default)]
pub(crate) struct WakerSlot(Mutex<Option<(rune_core::Waker, u64)>>);
impl WakerSlot {
/// Installs `waker`, which hears the next [`tell`](Self::tell) of any generation but 0.
pub(crate) fn set(&self, waker: rune_core::Waker) {
// The replaced waker's captures drop after the lock: one may read this handle and would
// deadlock here.
let old = self.0.lock().unwrap().replace((waker, 0));
drop(old);
}
/// Calls the waker if `generation` is news to it. Call with no other locks held: the waker
/// runs app code.
pub(crate) fn tell(&self, generation: u64) {
let waker = match &mut *self.0.lock().unwrap() {
Some((waker, heard)) if *heard != generation => {
*heard = generation;
Some(waker.clone())
}
_ => None,
};
if let Some(waker) = waker {
waker();
}
}
/// Whether the slot's lock is free right now, without waiting for it.
#[cfg(test)]
pub(crate) fn free(&self) -> bool {
self.0.try_lock().is_ok()
}
}
@@ -0,0 +1,147 @@
//! A video's sound, read ahead of the clock on a source reader and a thread of its own. The
//! decoder's reader can't do it: it decodes only a few pictures ahead, and on the layer it waits
//! for each picture's time, while the sound output needs more than 100 ms queued at every write.
#![allow(unsafe_code)]
use super::audio::{Queue, push_sample};
use super::mf::{self, Decode, Sound};
use super::super::{Kind, MediaSource};
use std::sync::Arc;
use std::time::Duration;
use windows::Win32::Media::MediaFoundation::{MF_SOURCE_READERF_ENDOFSTREAM, MF_SOURCE_READERF_ERROR, IMFSourceReader};
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
/// How long a reader with a full queue sleeps when nothing wakes it.
const PATIENCE: Duration = Duration::from_millis(250);
/// Where a video's sound comes from.
pub(super) struct Read {
pub source: MediaSource,
/// Unwrapped seconds to start at.
pub at: f64,
pub duration: f64,
}
/// Starts the reader thread; it runs until the output stops.
pub(super) fn start(read: Read, queue: Arc<Queue>, sound: Sound) -> Result<(), String> {
std::thread::Builder::new()
.name("rune-video-sound-read".into())
.spawn(move || {
// SAFETY: COM for this thread, matched below.
let com = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.is_ok();
if let Err(e) = run(&read, &queue, sound) {
eprintln!("rune: the clip's sound stopped: {e}");
}
if com {
// SAFETY: matches the initialisation above; the reader is gone.
unsafe { CoUninitialize() };
}
})
.map(|_| ())
.map_err(|e| e.to_string())
}
/// A seek's place on an unwrapped time: the loops before it, and the clip's own seconds.
fn place(at: f64, duration: f64) -> (f64, f64) {
if duration > 0.0 {
let epoch = (at / duration).floor() * duration;
(epoch, at - epoch)
} else {
(0.0, at)
}
}
struct Reader {
reader: IMFSourceReader,
index: u32,
/// Added to stream times: the loops so far times the duration.
epoch: f64,
/// Sound before this unwrapped time (a seek's pre-roll) is dropped.
skip_before: f64,
/// Not at the stream's end.
open: bool,
/// A sample came since the last seek: a loop has sound to go back to.
got: bool,
}
impl Reader {
fn seek(&mut self, at: f64, duration: f64) -> Result<(), String> {
let (epoch, to) = place(at, duration);
mf::seek(&self.reader, to)?;
(self.epoch, self.skip_before, self.open, self.got) = (epoch, at, true, false);
Ok(())
}
}
fn run(read: &Read, queue: &Queue, sound: Sound) -> Result<(), String> {
let lib = mf::library()?;
let target = mf::Target::from_source(&read.source)?;
let source = lib.resolve(&target)?;
let opened = mf::open(lib, &source, Kind::Audio, Decode::Cpu, true)?;
let index = opened.audio.ok_or("no audio stream")?;
if opened.sound != Some(sound) {
return Err("the sound's format differs from the clip's".into());
}
let mut r = Reader { reader: opened.reader, index, epoch: 0.0, skip_before: 0.0, open: true, got: false };
r.seek(read.at, read.duration)?;
loop {
let mut feed = queue.lock();
loop {
if feed.stop {
return Ok(());
}
if let Some(to) = feed.seek.take() {
feed.clear();
drop(feed);
r.seek(to, read.duration)?;
feed = queue.lock();
continue;
}
// Looping turned on after the sound's end: on into the next loop.
if !r.open && r.got && feed.looping && read.duration > 0.0 {
let next = r.epoch + read.duration;
drop(feed);
r.seek(next, read.duration)?;
feed = queue.lock();
continue;
}
if r.open && !queue.full(&feed, sound) {
break;
}
feed = queue.wait(feed, PATIENCE);
}
let looping = feed.looping;
drop(feed);
let mut got = mf::read(&r.reader, r.index)?;
if got.flags & MF_SOURCE_READERF_ERROR.0 != 0 {
return Err("the decoder stopped with an error".into());
}
if let Some(sample) = got.sample.take() {
r.got = true;
push_sample(queue, sound, &sample, r.epoch + got.time, r.skip_before);
}
if got.flags & MF_SOURCE_READERF_ENDOFSTREAM.0 != 0 {
if looping && r.got && read.duration > 0.0 {
let next = r.epoch + read.duration;
r.seek(next, read.duration)?;
} else {
r.open = false;
}
}
}
}
#[cfg(test)]
mod tests {
use super::place;
#[test]
fn a_seek_on_an_unwrapped_time_lands_in_its_loop() {
assert_eq!(place(25.0, 10.0), (20.0, 5.0));
assert_eq!(place(7.5, 10.0), (0.0, 7.5));
assert_eq!(place(7.5, 0.0), (0.0, 7.5));
}
}
@@ -0,0 +1,446 @@
//! Sound for a clip: a WASAPI shared-mode stream on the default output device, fed by the
//! decoder (audio clips) or by a reader of its own (`ahead`, video), and timed by the player's
//! clock. Each time the device asks for more, it writes the samples for the moment they'll be
//! heard, from the device's own position, padding with silence or skipping ahead when the clock
//! jumped (a start, a seek, a stall). While it plays on, the sound is the master: where the
//! device clock drifts from the player's, the player's clock moves to the sound, so the
//! pictures follow what is heard and the sound never skips.
#![allow(unsafe_code)]
use super::ahead::{self, Read};
use rune_core::time::Instant;
use super::machine::Anchor;
use super::mf::Sound;
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::Duration;
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};
use windows::Win32::Media::Audio::*;
use windows::Win32::Media::MediaFoundation::IMFSample;
use windows::Win32::System::Com::{CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize};
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
/// The device's buffer: long enough to ride out a busy decoder, short enough to react.
const BUFFER: Duration = Duration::from_millis(100);
/// Sound decoded ahead of what's heard; the reader waits beyond it.
const AHEAD: f64 = 1.0;
/// How far written sound may be from the clock before it jumps back in line: a start, a seek, a
/// stall, a clock the UI set again.
const SLOP: f64 = 0.04;
/// How far the sound may run from the clock, on average, before the clock moves to the sound:
/// a quarter of a picture at 60 fps, so one move never crosses a picture's boundary.
const NUDGE: f64 = 0.004;
/// Moves this soon after a start correct the start's estimate of the device's latency too.
const SETTLE: Duration = Duration::from_secs(1);
/// A stopped stream's unplayed sound is read again from this far before the clock stopped.
const REREAD: f64 = 0.1;
/// Each write's weight in that average.
const SMOOTH: f64 = 0.1;
/// The device's position is trusted only this far past the estimate from its buffer.
const POSITION_SLACK: f64 = 0.5;
/// The playback clock the UI sets and the sound follows: none while paused, stalled or ended.
#[derive(Default)]
pub(super) struct Clock {
anchor: Mutex<Option<Anchor>>,
changed: Condvar,
}
impl Clock {
pub(super) fn set(&self, anchor: Option<Anchor>) {
*self.anchor.lock().unwrap() = anchor;
self.changed.notify_all();
}
pub(super) fn get(&self) -> Option<Anchor> {
*self.anchor.lock().unwrap()
}
/// Moves the clock `by` seconds to where the sound plays, unless it was set again since
/// `anchor` was read.
fn nudge(&self, anchor: Anchor, by: f64) {
let mut current = self.anchor.lock().unwrap();
if *current == Some(anchor) {
*current = Some(Anchor { pos: anchor.pos + by, ..anchor });
}
}
/// Sleeps until the clock runs at 1x (or patience passes) while it doesn't: sound plays
/// only at normal speed.
fn wait_while_stopped(&self, patience: Duration) {
let anchor = self.anchor.lock().unwrap();
if anchor.is_none_or(|a| (a.rate - 1.0).abs() >= 1e-6) {
self.changed.wait_timeout(anchor, patience).ok();
}
}
}
struct Chunk {
pts: f64,
samples: Vec<f32>,
}
#[derive(Default)]
pub(super) struct Feed {
chunks: VecDeque<Chunk>,
/// Interleaved samples buffered.
samples: usize,
gain: f32,
pub stop: bool,
/// Media time of the next sample the device gets, once it's writing in line with the clock.
cursor: Option<f64>,
/// For the reader: an unwrapped time to read from next. Without a reader, nobody reads it.
pub seek: Option<f64>,
pub looping: bool,
}
impl Feed {
/// Forgets queued sound.
pub(super) fn clear(&mut self) {
self.chunks.clear();
self.samples = 0;
self.cursor = None;
}
}
/// The sound between whoever decodes it and the device; `room` wakes the reader when the device
/// took some, or something changed.
#[derive(Default)]
pub(super) struct Queue {
feed: Mutex<Feed>,
room: Condvar,
}
impl Queue {
pub(super) fn lock(&self) -> MutexGuard<'_, Feed> {
self.feed.lock().unwrap()
}
pub(super) fn wait<'a>(&self, feed: MutexGuard<'a, Feed>, patience: Duration) -> MutexGuard<'a, Feed> {
self.room.wait_timeout(feed, patience).unwrap().0
}
/// Enough is queued; whoever decodes may wait.
pub(super) fn full(&self, feed: &Feed, sound: Sound) -> bool {
feed.samples as f64 >= AHEAD * f64::from(sound.rate) * f64::from(sound.channels)
}
}
/// Queues a decoded float sample at `pts` seconds; sound before `skip_before` (a seek's
/// pre-roll) is dropped.
pub(super) fn push_sample(queue: &Queue, sound: Sound, sample: &IMFSample, pts: f64, skip_before: f64) {
let Some(samples) = samples(sample) else { return };
let channels = usize::from(sound.channels);
let end = pts + (samples.len() / channels) as f64 / f64::from(sound.rate);
if end <= skip_before {
return;
}
let mut feed = queue.lock();
feed.samples += samples.len();
feed.chunks.push_back(Chunk { pts, samples });
}
/// A clip's sound output; dropping it stops the stream and its reader.
pub(super) struct Output {
queue: Arc<Queue>,
clock: Arc<Clock>,
sound: Sound,
/// A reader of its own feeds it (`read`); else the decoder pushes.
reads: bool,
}
impl Output {
/// Opens the stream; with `read`, a reader of its own reads the sound ahead.
pub(super) fn open(sound: Sound, clock: Arc<Clock>, read: Option<Read>) -> Result<Self, String> {
let queue = Arc::new(Queue::default());
queue.lock().gain = 1.0;
let (thread_queue, thread_clock) = (queue.clone(), clock.clone());
let (ready, started) = std::sync::mpsc::sync_channel(1);
std::thread::Builder::new()
.name("rune-video-sound".into())
.spawn(move || {
// SAFETY: COM for this thread, matched below.
let com = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.is_ok();
match Stream::new(sound) {
Ok(stream) => {
ready.send(Ok(())).ok();
stream.run(&thread_queue, &thread_clock, sound);
}
Err(e) => {
ready.send(Err(e)).ok();
}
}
if com {
// SAFETY: matches the initialisation above.
unsafe { CoUninitialize() };
}
})
.map_err(|e| e.to_string())?;
started.recv().map_err(|_| "the sound thread stopped".to_string())??;
let output = Self { queue, clock, sound, reads: read.is_some() };
if let Some(read) = read {
ahead::start(read, output.queue.clone(), sound)?;
}
Ok(output)
}
/// Queues a decoded float sample at `pts` seconds, from the decoder.
pub(super) fn push(&self, sample: &IMFSample, pts: f64, skip_before: f64, _generation: u32) {
push_sample(&self.queue, self.sound, sample, pts, skip_before);
}
/// Forgets queued sound; a reader reads again from `to` (unwrapped seconds).
pub(super) fn seek(&self, to: f64) {
let mut feed = self.queue.lock();
feed.clear();
if self.reads {
feed.seek = Some(to);
}
drop(feed);
self.queue.room.notify_all();
}
pub(super) fn set_gain(&self, gain: f32) {
self.queue.lock().gain = gain.clamp(0.0, 1.0);
}
pub(super) fn set_looping(&self, looping: bool) {
self.queue.lock().looping = looping;
}
/// Enough is queued from the decoder; it may wait. A reader of its own keeps it full.
pub(super) fn full(&self) -> bool {
!self.reads && self.queue.full(&self.queue.lock(), self.sound)
}
/// Nothing plays: paused, stalled or ended.
pub(super) fn idle(&self) -> bool {
self.clock.get().is_none()
}
/// The decoder reached the end; what's queued still plays out.
pub(super) fn end(&self, _generation: u32) {}
}
impl Drop for Output {
fn drop(&mut self) {
self.queue.lock().stop = true;
self.clock.changed.notify_all();
self.queue.room.notify_all();
}
}
/// A decoded float sample's interleaved values.
fn samples(sample: &IMFSample) -> Option<Vec<f32>> {
// SAFETY: the buffer is locked for the copy and unlocked after it.
unsafe {
let buffer = sample.ConvertToContiguousBuffer().ok()?;
let (mut base, mut len) = (std::ptr::null_mut(), 0u32);
buffer.Lock(&mut base, None, Some(&mut len)).ok()?;
let values = std::slice::from_raw_parts(base.cast::<f32>(), len as usize / 4).to_vec();
buffer.Unlock().ok();
Some(values)
}
}
struct Stream {
client: IAudioClient,
render: IAudioRenderClient,
event: HANDLE,
frames: u32,
latency: Duration,
/// The device's position counter and its ticks per second, when it has one.
position: Option<(IAudioClock, u64)>,
}
impl Stream {
fn new(sound: Sound) -> Result<Self, String> {
// SAFETY: COM calls on this thread's objects; the format describes interleaved float.
unsafe {
let devices: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|e| e.message())?;
let device = devices.GetDefaultAudioEndpoint(eRender, eConsole).map_err(|_| "no sound output device".to_string())?;
let client: IAudioClient = device.Activate(CLSCTX_ALL, None).map_err(|e| e.message())?;
let block = 4 * sound.channels;
let format = WAVEFORMATEX {
wFormatTag: 3, // WAVE_FORMAT_IEEE_FLOAT
nChannels: sound.channels,
nSamplesPerSec: sound.rate,
nAvgBytesPerSec: sound.rate * u32::from(block),
nBlockAlign: block,
wBitsPerSample: 32,
cbSize: 0,
};
let flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
client.Initialize(AUDCLNT_SHAREMODE_SHARED, flags, BUFFER.as_nanos() as i64 / 100, 0, &format, None).map_err(|e| e.message())?;
let event = CreateEventW(None, false, false, None).map_err(|e| e.message())?;
client.SetEventHandle(event).map_err(|e| e.message())?;
let render: IAudioRenderClient = client.GetService().map_err(|e| e.message())?;
let frames = client.GetBufferSize().map_err(|e| e.message())?;
let latency = Duration::from_nanos(client.GetStreamLatency().unwrap_or(0).max(0) as u64 * 100);
let position = client.GetService::<IAudioClock>().ok().and_then(|c| c.GetFrequency().ok().filter(|f| *f > 0).map(|f| (c, f)));
Ok(Self { client, render, event, frames, latency, position })
}
}
/// When the next sample written will be heard. Running, from the device's position: what
/// was written and not yet played is still to come. Else from the buffer, the stream's
/// latency and `bias`, the error earlier starts found in that estimate.
fn heard(&self, now: Instant, written: u64, padding: u32, rate: f64, running: bool, bias: f64) -> Instant {
let buffered = (self.latency.as_secs_f64() + f64::from(padding) / rate + bias).max(0.0);
let from_buffer = now + Duration::from_secs_f64(buffered);
let Some((clock, frequency)) = self.position.as_ref().filter(|_| running) else { return from_buffer };
let (mut position, mut counter) = (0u64, 0u64);
// SAFETY: reads into locals from this stream's clock.
if unsafe { clock.GetPosition(&mut position, Some(&mut counter)) }.is_err() {
return from_buffer;
}
let played = position as f64 / *frequency as f64;
let age = performance_seconds() - counter as f64 / 1e7;
let wait = written as f64 / rate - played - age;
if (0.0..=buffered + POSITION_SLACK).contains(&wait) { now + Duration::from_secs_f64(wait) } else { from_buffer }
}
fn run(&self, queue: &Queue, clock: &Clock, sound: Sound) {
let channels = usize::from(sound.channels);
let rate = f64::from(sound.rate);
let mut started = false;
// Frames written since the stream started, and how far the sound runs from the clock.
let mut written = 0u64;
let mut drift = 0.0;
// When the stream last started, the clock it last played to, and the start estimate's error.
let mut since: Option<Instant> = None;
let mut last: Option<Anchor> = None;
let mut bias = 0.0;
loop {
if !started {
// Stopped: sleep until the clock runs, not on the device's period.
clock.wait_while_stopped(Duration::from_secs(1));
}
// SAFETY: a wait on this stream's own event.
let woke = started && unsafe { WaitForSingleObject(self.event, 20) } == WAIT_OBJECT_0;
if queue.lock().stop {
break;
}
let anchor = clock.get().filter(|a| (a.rate - 1.0).abs() < 1e-6);
let Some(anchor) = anchor else {
if started {
// SAFETY: stops and empties this stream.
unsafe {
self.client.Stop().ok();
self.client.Reset().ok();
}
started = false;
written = 0;
let mut feed = queue.lock();
// The device's unplayed sound is gone: a reader reads it again, unless a
// seek already cleared the queue.
if let (Some(_), Some(last)) = (feed.cursor.take(), last) {
feed.seek = Some(last.position(rune_core::time::now()) - REREAD);
drop(feed);
queue.room.notify_all();
}
}
drift = 0.0;
continue;
};
last = Some(anchor);
if started && !woke {
continue;
}
// SAFETY: buffer calls on this stream; the device buffer holds `free` frames.
let off = unsafe {
let padding = self.client.GetCurrentPadding().unwrap_or(self.frames);
let free = self.frames.saturating_sub(padding);
if free == 0 {
continue;
}
let Ok(data) = self.render.GetBuffer(free) else { continue };
let out = std::slice::from_raw_parts_mut(data.cast::<f32>(), free as usize * channels);
let heard = self.heard(rune_core::time::now(), written, padding, rate, started, bias);
let off = fill(&mut queue.lock(), out, channels, rate, anchor.position(heard));
self.render.ReleaseBuffer(free, 0).ok();
written += u64::from(free);
if !started {
started = self.client.Start().is_ok();
since = Some(rune_core::time::now());
}
off
};
queue.room.notify_all();
match off {
Some(off) => {
drift += (off - drift) * SMOOTH;
if drift.abs() > NUDGE {
clock.nudge(anchor, drift);
if since.is_some_and(|t| t.elapsed() < SETTLE) {
bias -= drift;
}
drift = 0.0;
}
}
None => drift = 0.0,
}
}
// SAFETY: stops this stream and closes its event.
unsafe {
self.client.Stop().ok();
CloseHandle(self.event).ok();
}
}
}
/// The performance counter now, in seconds: the clock the device's position is stamped with.
fn performance_seconds() -> f64 {
let (mut count, mut frequency) = (0i64, 0i64);
// SAFETY: plain reads of the performance counter into locals.
unsafe {
windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut count);
windows_sys::Win32::System::Performance::QueryPerformanceFrequency(&mut frequency);
}
count as f64 / frequency.max(1) as f64
}
/// Writes `out` with the sound from media time `want` on. Within `SLOP` of the last write's
/// end, it goes on from there and returns how far that runs from `want`; further off, it jumps
/// to `want` and returns None.
fn fill(feed: &mut Feed, out: &mut [f32], channels: usize, rate: f64, want: f64) -> Option<f64> {
let (mut cursor, off) = match feed.cursor {
Some(c) if (c - want).abs() < SLOP => (c, Some(c - want)),
_ => (want, None),
};
let frames = out.len() / channels;
let mut written = 0;
while written < frames {
while let Some(c) = feed.chunks.front() {
let end = c.pts + (c.samples.len() / channels) as f64 / rate;
if end > cursor + 0.5 / rate {
break;
}
feed.samples -= c.samples.len();
feed.chunks.pop_front();
}
let Some(chunk) = feed.chunks.front() else {
out[written * channels..].fill(0.0);
cursor += (frames - written) as f64 / rate;
break;
};
let start = ((cursor - chunk.pts) * rate).round() as i64;
let n = if start < 0 {
let n = ((-start) as usize).min(frames - written);
out[written * channels..(written + n) * channels].fill(0.0);
n
} else {
let start = start as usize;
let n = (chunk.samples.len() / channels - start).min(frames - written);
let gain = feed.gain;
for (o, s) in out[written * channels..(written + n) * channels].iter_mut().zip(&chunk.samples[start * channels..]) {
*o = s * gain;
}
n
};
written += n;
cursor += n as f64 / rate;
}
feed.cursor = Some(cursor);
off
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,70 @@
use super::*;
const RATE: f64 = 1000.0;
/// One mono chunk of `len` samples at `pts`, each sample its own index.
fn feed(pts: f64, len: usize) -> Feed {
let samples: Vec<f32> = (0..len).map(|i| i as f32).collect();
let mut feed = Feed { gain: 1.0, samples: samples.len(), ..Feed::default() };
feed.chunks.push_back(Chunk { pts, samples });
feed
}
#[test]
fn the_first_write_starts_at_the_clock() {
let mut f = feed(0.0, 1000);
let mut out = [0.0; 10];
assert_eq!(fill(&mut f, &mut out, 1, RATE, 0.1), None);
assert_eq!(out[0], 100.0);
assert_eq!(out[9], 109.0);
}
#[test]
fn a_write_close_to_the_clock_goes_on_without_a_skip_and_reports_the_drift() {
let mut f = feed(0.0, 1000);
let mut out = [0.0; 10];
fill(&mut f, &mut out, 1, RATE, 0.1);
let off = fill(&mut f, &mut out, 1, RATE, 0.105).unwrap();
assert!((off - 0.005).abs() < 1e-9, "{off}");
assert_eq!(out[0], 110.0);
}
#[test]
fn a_write_far_from_the_clock_jumps_to_it() {
let mut f = feed(0.0, 1000);
let mut out = [0.0; 10];
fill(&mut f, &mut out, 1, RATE, 0.1);
assert_eq!(fill(&mut f, &mut out, 1, RATE, 0.5), None);
assert_eq!(out[0], 500.0);
}
#[test]
fn sound_not_decoded_yet_is_silence() {
let mut f = feed(0.2, 1000);
let mut out = [1.0; 10];
fill(&mut f, &mut out, 1, RATE, 0.195);
assert_eq!(out[..5], [0.0; 5]);
assert_eq!(out[5], 0.0);
assert_eq!(out[6], 1.0);
}
#[test]
fn a_nudge_moves_the_clock_the_sound_read() {
let clock = Clock::default();
let anchor = Anchor { at: rune_core::time::now(), pos: 3.0, rate: 1.0 };
clock.set(Some(anchor));
clock.nudge(anchor, 0.01);
assert_eq!(clock.get().map(|a| a.pos), Some(3.01));
}
#[test]
fn a_nudge_leaves_a_clock_set_again_alone() {
let clock = Clock::default();
let anchor = Anchor { at: rune_core::time::now(), pos: 3.0, rate: 1.0 };
clock.set(Some(Anchor { pos: 9.0, ..anchor }));
clock.nudge(anchor, 0.01);
assert_eq!(clock.get().map(|a| a.pos), Some(9.0));
clock.set(None);
clock.nudge(anchor, 0.01);
assert_eq!(clock.get(), None);
}
@@ -0,0 +1,633 @@
//! One clip's decoder thread: opens the source with Media Foundation, decodes a few pictures
//! ahead into the player's GPU ring, hands audio to the sound output, loops without a gap by
//! seeking back while the last pictures still wait in the queue, and stops when told or when no
//! frame has drawn the clip for a while. The UI thread only takes pictures off the queue.
//!
//! The queue is the decoder's only clock: it decodes while there's room, so a clip nobody
//! draws fills it and sleeps, costing nothing until a frame takes a picture again.
#![allow(unsafe_code)]
use super::ahead::Read;
use super::audio::{self, Output};
use super::gpu::{self, Ring};
use super::layer::Layer;
use super::machine::Anchor;
use super::mf::{self, Decode, Picture, Sound};
use super::super::{Kind, MediaSource, Meta};
use crate::native_surface::ByteFrame;
use crate::native_surface::windows::DecodedPlanes;
use rune_core::time::Instant;
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::Duration;
use windows::Win32::Graphics::Direct3D11::{D3D11_BIND_DECODER, ID3D11Texture2D};
use windows::Win32::Media::MediaFoundation::*;
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
use windows::core::Interface;
/// Pictures decoded ahead of the one on screen.
const AHEAD: usize = 3;
/// A decoder no frame has taken a picture from for this long lets go of its source, decoder and
/// textures; the clip keeps its last picture and reopens when drawn again.
const PARK: Duration = Duration::from_secs(3);
/// How often a decoder with room but no free texture looks at the release fence again.
const RING_POLL: Duration = Duration::from_millis(2);
/// How long before a picture's time the decoder presents it on the clip's layer: the display
/// shows it at the first refresh after.
const LAYER_LEAD: Duration = Duration::from_millis(2);
/// How long a clip that opens before Rune has a GPU waits for it (`rune_device`).
const GPU_WAIT: Duration = Duration::from_secs(3);
/// What the UI asks of the decoder and what the decoder hands back, under one lock.
#[derive(Default)]
pub(super) struct Inbox {
/// A seek to land: clip seconds and the generation its pictures carry.
pub seek: Option<(f64, u32)>,
pub looping: bool,
/// Play sound, at this gain (unmuted, and the clip has some).
pub sound: Option<f32>,
pub stop: bool,
/// When a frame last drew the clip.
pub touched: Option<Instant>,
pub news: Vec<News>,
pub frames: VecDeque<Decoded>,
/// The generation whose last picture is in the queue: the clip ended there.
pub ended: Option<u32>,
/// The window shows the clip on its own layer at this size (device pixels): while the clock
/// runs, the decoder presents each picture there itself (`layer`). None: the UI draws them.
pub layer: Option<(u32, u32)>,
/// The layer's DirectComposition surface handle, once made, for the window's visual.
pub layer_handle: Option<usize>,
/// The size of the last picture presented on the layer, and the generation it belongs to.
pub layer_shown: Option<((u32, u32), u32)>,
/// The newest picture presented on the layer and kept in `frames`: its time and generation.
pub layer_presented: Option<(f64, u32)>,
/// The clip can't have a layer (a rotated clip, software pictures, no video processor): the
/// UI keeps drawing it.
pub layer_refused: bool,
}
pub(super) enum News {
Opened(Facts),
Failed(String),
/// Let go after `PARK` undrawn.
Parked,
}
/// `decode`'s answer when Rune's device was replaced under the ring: not a failure.
const DEVICE_CHANGED: &str = "Rune's GPU device changed";
/// What opening found.
#[derive(Clone, Copy, Debug)]
pub(super) struct Facts {
pub meta: Meta,
pub picture: Option<Picture>,
pub sound: Option<Sound>,
/// Pictures come out of a hardware decoder.
pub hardware: bool,
/// Pictures reach the screen on the GPU (false: through system memory).
pub gpu: bool,
}
pub(super) struct Decoded {
pub generation: u32,
/// Seconds from the clip's start, counting on through loops.
pub pts: f64,
pub picture: Pic,
}
pub(super) enum Pic {
Gpu(Arc<DecodedPlanes>, u64),
Cpu(ByteFrame),
}
pub(super) struct Pipe {
inbox: Mutex<Inbox>,
wake: Condvar,
}
impl Pipe {
pub(super) fn lock(&self) -> MutexGuard<'_, Inbox> {
self.inbox.lock().unwrap()
}
/// Tell the decoder something changed (a seek, a picture taken, a stop).
pub(super) fn poke(&self) {
self.wake.notify_all();
}
}
/// What a decoder starts with.
pub(super) struct Job {
pub source: MediaSource,
pub kind: Kind,
/// Clip seconds to start at, and that start's generation.
pub start: f64,
pub generation: u32,
pub looping: bool,
pub sound: Option<f32>,
/// Wakes the windows drawing the clip (news, or a picture after a wait).
pub notify: Box<dyn Fn() + Send>,
/// The clock audio follows.
pub clock: Arc<audio::Clock>,
/// When the UI asked for the clip.
pub started: Instant,
}
/// Starts a decoder thread; it runs until `stop` or parking.
pub(super) fn start(job: Job) -> Arc<Pipe> {
let pipe = Arc::new(Pipe {
inbox: Mutex::new(Inbox { looping: job.looping, sound: job.sound, touched: Some(rune_core::time::now()), ..Inbox::default() }),
wake: Condvar::new(),
});
let thread_pipe = pipe.clone();
let spawned = std::thread::Builder::new().name("rune-video-decode".into()).spawn(move || {
// SAFETY: COM for this thread, matched below.
let com = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.is_ok();
run(&thread_pipe, job);
if com {
// SAFETY: matches the initialisation above; every COM object of this thread is gone.
unsafe { CoUninitialize() };
}
});
if spawned.is_err() {
pipe.lock().news.push(News::Failed("couldn't start a video decoder thread".into()));
}
pipe
}
/// `RUNE_VIDEO_LOG=1` prints each open's steps in microseconds.
pub(super) fn logging() -> bool {
log_level() > 0
}
/// `RUNE_VIDEO_LOG=frames`: every picture shown and every pull's cost too.
pub(super) fn logging_frames() -> bool {
log_level() > 1
}
fn log_level() -> u8 {
static LEVEL: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*LEVEL.get_or_init(|| match std::env::var_os("RUNE_VIDEO_LOG") {
Some(v) if v == "frames" => 2,
Some(v) if v != "0" => 1,
_ => 0,
})
}
/// A `RUNE_VIDEO_LOG` line, stamped with microseconds since the first.
macro_rules! log {
($($arg:tt)*) => {
eprintln!("rune video {:>10} us: {}", $crate::video::windows::decoder::log_clock(), format!($($arg)*))
};
}
pub(super) use log;
/// Microseconds since the first `log!` line: one clock for every line, wherever it's written.
pub(super) fn log_clock() -> u128 {
static T0: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
T0.get_or_init(rune_core::time::now).elapsed().as_micros()
}
/// Microseconds from `t0` to now.
pub(super) fn us(t0: Instant) -> u128 {
t0.elapsed().as_micros()
}
/// The decoders' device on Rune's GPU. A window drawn on the CPU first (`window::cpu_frame`)
/// makes its GPU after its first frame, and a clip that opens before then would decode on the CPU
/// for good: it waits for the GPU as long as one takes to come, while the source resolves.
fn rune_device() -> Option<Arc<gpu::Device>> {
let deadline = rune_core::time::now() + GPU_WAIT;
loop {
match gpu::device() {
Ok(device) => return Some(device),
Err(_) if crate::native_surface::windows::presenting_device().is_none() && rune_core::time::now() < deadline => {
std::thread::sleep(Duration::from_millis(5));
}
Err(_) => return None,
}
}
}
fn run(pipe: &Pipe, job: Job) {
rune_core::marks::mark("video.open");
let generation = crate::native_surface::windows::device_generation();
let mut d = match Decoder::open(&job) {
Ok(d) => d,
// An open that failed as Rune lost its device opens again on the next one.
Err(_) if gpu::lost_since(generation) => {
if logging() {
log!("Rune's GPU device was lost while the clip opened: it opens again on the next one");
}
pipe.lock().news.push(News::Parked);
(job.notify)();
return;
}
Err(e) => {
pipe.lock().news.push(News::Failed(e));
(job.notify)();
return;
}
};
rune_core::marks::mark("video.opened");
pipe.lock().news.push(News::Opened(d.facts));
(job.notify)();
match d.decode(pipe, &job) {
Err(e) if e == DEVICE_CHANGED || gpu::lost_since(generation) => {
if logging() {
log!("Rune's GPU device changed: the clip opens again on the new one");
}
pipe.lock().news.push(News::Parked);
(job.notify)();
}
Err(e) => {
pipe.lock().news.push(News::Failed(e));
(job.notify)();
}
Ok(()) => {}
}
}
struct Decoder {
kind: Kind,
reader: IMFSourceReader,
facts: Facts,
ring: Option<Ring>,
output: Option<Output>,
video: Option<u32>,
audio: Option<u32>,
/// Selected streams not at their end yet.
video_open: bool,
audio_open: bool,
/// For `RUNE_VIDEO_LOG`: microseconds to open, and each step's.
opened_us: u128,
steps: String,
layer: Option<Layer>,
/// Decoding on the CPU only because Rune had no GPU yet when the clip opened: once it has one,
/// the clip opens again there (`decode`).
awaiting_gpu: bool,
}
impl Decoder {
fn open(job: &Job) -> Result<Self, String> {
let t0 = job.started;
let target = mf::Target::from_source(&job.source)?;
let lib = mf::library()?;
let t_mf = us(t0);
rune_core::marks::mark("video.mf");
let software = std::env::var_os("RUNE_VIDEO_DECODE").is_some_and(|v| v == "software");
// The decoders' D3D11 device (made once per process) comes up on a thread of its own
// while this one resolves the source: the two don't depend on each other.
let (device, source, t_device) = std::thread::scope(|s| {
let device = (job.kind == Kind::Video).then(|| s.spawn(|| (rune_device(), us(t0))));
let source = lib.resolve(&target);
let (device, t_device) = device.and_then(|d| d.join().ok()).unwrap_or((None, 0));
(device, source, t_device)
});
let source = source?;
let t_source = us(t0);
rune_core::marks::mark("video.device");
// Software decoding still uploads its pictures from this thread, not the UI's.
let manager = device.as_ref().filter(|_| !software).map(|d| d.manager(lib)).transpose()?;
let decode = manager.as_ref().map_or(Decode::Cpu, Decode::Gpu);
let opened = mf::open(lib, &source, job.kind, decode, true)?;
let t_reader = us(t0);
let duration = opened.duration;
let picture = opened.picture;
let awaiting_gpu = !software && device.is_none() && picture.is_some() && crate::native_surface::windows::presenting_device().is_none();
let ring = match (&device, &picture) {
(Some(device), Some(picture)) => Some(Ring::new(device.clone(), picture)?),
_ => None,
};
let hardware = false;
if job.start > 0.0 {
mf::seek(&opened.reader, job.start)?;
}
let meta = Meta { duration, size: picture.map(|p| p.natural), frame: picture.map_or(1.0 / 30.0, |p| p.frame), sound: opened.has_sound };
let facts = Facts { meta, picture, sound: opened.sound, hardware, gpu: ring.is_some() };
let opened_us = us(t0);
let steps = format!("Media Foundation at {t_mf}, D3D11 at {t_device}, source at {t_source}, reader at {t_reader}, ring at {opened_us}");
let mut d = Self { kind: job.kind, reader: opened.reader, facts, ring, output: None, video: opened.video, audio: opened.audio, video_open: picture.is_some(), audio_open: false, opened_us, steps, layer: None, awaiting_gpu };
d.select_sound(job.sound.is_some() || job.kind == Kind::Audio, job, job.start);
Ok(d)
}
/// Turns the sound on (opening the output, which reads a video's sound from `at` on with a
/// reader of its own) or off. Only an audio clip's sound comes from this reader.
fn select_sound(&mut self, on: bool, job: &Job, at: f64) {
let Some(sound) = self.facts.sound else { return };
if on && self.output.is_none() {
let read = (self.kind == Kind::Video).then(|| Read { source: job.source.clone(), at, duration: self.facts.meta.duration });
match Output::open(sound, job.clock.clone(), read) {
Ok(output) => self.output = Some(output),
Err(e) => eprintln!("rune: no sound for the clip: {e}"),
}
}
if !on {
self.output = None;
}
if let Some(index) = self.audio {
// SAFETY: stream selection on this thread's reader.
unsafe { self.reader.SetStreamSelection(index, self.reads_sound()) }.ok();
}
self.audio_open = self.reads_sound();
}
/// This reader decodes the sound: an audio clip's, while it plays any.
fn reads_sound(&self) -> bool {
self.kind == Kind::Audio && self.output.is_some()
}
fn decode(&mut self, pipe: &Pipe, job: &Job) -> Result<(), String> {
let mut generation = job.generation;
// Pictures before a seek's target are decoded only to reach it.
let mut skip_before = job.start;
// Added to stream times: the loops so far times the duration.
let mut epoch = 0.0;
let mut first = true;
let mut waiting_since = rune_core::time::now();
// Audio alone: the clip's end, until the clock passes it and the clip hears so.
let mut end_due: Option<f64> = None;
loop {
// Take the UI's asks, then wait for room in the queue and a free texture.
{
let mut s = pipe.lock();
loop {
if s.stop {
return Ok(());
}
if let Some((to, g)) = s.seek.take() {
end_due = None;
s.frames.clear();
s.ended = None;
generation = g;
skip_before = to;
epoch = 0.0;
mf::seek(&self.reader, to)?;
self.reopen_streams();
if let Some(o) = &self.output {
o.seek(to);
}
}
if self.output.is_some() != s.sound.is_some() {
let on = s.sound.is_some();
// Sound turned on mid-clip starts where the clip is.
let at = job.clock.get().map(|clock| clock.position(rune_core::time::now())).or(s.frames.front().map(|f| f.pts)).unwrap_or(epoch + skip_before);
drop(s);
self.select_sound(on, job, at);
s = pipe.lock();
}
if let (Some(o), Some(gain)) = (&self.output, s.sound) {
o.set_gain(gain);
o.set_looping(s.looping);
}
self.follow_layer(&mut s);
// Rune's GPU came after the clip opened on the CPU: it opens again on the GPU,
// at its picture, as for a replaced device.
if self.awaiting_gpu && crate::native_surface::windows::presenting_device().is_some() {
return Err(DEVICE_CHANGED.into());
}
let ended = s.ended == Some(generation);
let room = s.frames.len() < AHEAD || !self.video_open;
let texture = self.ring.as_ref().is_none_or(Ring::free);
let sound_full = self.output.as_ref().is_some_and(Output::full);
if !ended && room && texture && !(sound_full && !self.video_open) {
break;
}
let touched = s.touched.unwrap_or(waiting_since);
let playing_sound = self.output.as_ref().is_some_and(|o| !o.idle());
let heard_end = end_due.and_then(|end| job.clock.get().map(|clock| clock.when(end)));
if let Some(at) = heard_end.filter(|at| *at <= rune_core::time::now()) {
let _ = at;
end_due = None;
drop(s);
(job.notify)();
s = pipe.lock();
continue;
}
if job.kind == Kind::Video && !playing_sound && touched.elapsed() > PARK {
s.news.push(News::Parked);
drop(s);
(job.notify)();
return Ok(());
}
let patience = if (room && !texture) || sound_full { RING_POLL } else { PARK };
let patience = heard_end.map_or(patience, |at| patience.min(at.saturating_duration_since(rune_core::time::now()) + Duration::from_millis(1)));
s = pipe.wake.wait_timeout(s, patience).unwrap().0;
waiting_since = waiting_since.max(touched);
}
}
let mut read = mf::read(&self.reader, MF_SOURCE_READER_ANY_STREAM.0 as u32)?;
if read.flags & MF_SOURCE_READERF_ERROR.0 != 0 {
return Err("the decoder stopped with an error".into());
}
let video = self.video == Some(read.stream);
if read.flags & MF_SOURCE_READERF_ENDOFSTREAM.0 != 0 {
if video { self.video_open = false } else { self.audio_open = false }
}
if let Some(sample) = read.sample.take() {
if video {
if read.time + self.facts.meta.frame * 0.5 >= skip_before {
let (picture, texture) = self.picture(&sample)?;
let pts = epoch + read.time;
let blitted = self.blit_on_layer(pipe, job, texture);
// The decoder's surface goes back before the wait for the picture's time:
// held through it, Media Foundation's decoder ran out of surfaces and spun
// in the driver with the device's lock, and the next copy here never got it.
drop(sample);
let layered = blitted.is_some_and(|clock| self.present_when_due(pipe, job, clock, pts, generation));
let mut s = pipe.lock();
let was_empty = s.frames.is_empty();
s.frames.push_back(Decoded { generation, pts, picture });
let mut unread = Vec::new();
if layered {
// The window takes no pictures while its layer shows them: only the
// newest stays, for when it draws the clip itself again, and the
// others' textures are free at once (Rune never read them). Presenting
// counts as being drawn, so the decoder doesn't park.
while s.frames.len() > 1 {
if let Some(Decoded { picture: Pic::Gpu(planes, _), .. }) = s.frames.pop_front() {
unread.push(planes);
}
}
s.touched = Some(rune_core::time::now());
s.layer_presented = Some((pts, generation));
}
drop(s);
if let Some(ring) = &mut self.ring {
for planes in &unread {
ring.unread(planes);
}
}
drop(unread);
if first {
rune_core::marks::mark("video.first_frame");
rune_core::marks::note("video.decoder", if self.facts.hardware { "hardware" } else { "software" });
rune_core::marks::note("video.pictures", if self.facts.gpu { "gpu" } else { "cpu" });
if logging() {
let f = &self.facts;
log!(
"{:?} opened in {} us ({}), first picture decoded at {} us; {} decoder, {} pictures",
job.source, self.opened_us, self.steps, us(job.started), if f.hardware { "hardware" } else { "software" }, if f.gpu { "GPU" } else { "CPU" }
);
}
first = false;
}
if was_empty && !layered {
(job.notify)();
}
}
} else if let Some(o) = &self.output {
o.push(&sample, epoch + read.time, skip_before, generation);
}
}
if !self.video_open && !self.audio_open {
let looping = pipe.lock().looping;
if looping && self.facts.meta.duration > 0.0 {
epoch += self.facts.meta.duration;
skip_before = 0.0;
mf::seek(&self.reader, 0.0)?;
self.reopen_streams();
} else {
pipe.lock().ended = Some(generation);
if let Some(o) = &self.output {
o.end(generation);
}
if job.kind == Kind::Audio {
end_due = Some(epoch + self.facts.meta.duration);
}
(job.notify)();
}
}
}
}
/// After a seek or a loop, every selected stream reads again.
fn reopen_streams(&mut self) {
self.video_open = self.facts.picture.is_some();
self.audio_open = self.reads_sound();
}
/// Makes, resizes or lets go of the clip's layer as the window asks (`Inbox::layer`).
fn follow_layer(&mut self, s: &mut Inbox) {
let Some(size) = s.layer.filter(|_| !s.layer_refused) else {
if s.layer.is_none() && self.layer.take().is_some() {
s.layer_handle = None;
s.layer_shown = None;
}
return;
};
let made = match &mut self.layer {
Some(layer) => layer.resize(size),
None => self.make_layer(size).map(|layer| {
s.layer_handle = Some(layer.handle());
self.layer = Some(layer);
}),
};
if let Err(e) = made {
if logging() {
log!("no layer for the clip: {e}; the window draws its pictures");
}
s.layer_refused = true;
s.layer_handle = None;
s.layer_shown = None;
self.layer = None;
}
}
fn make_layer(&self, size: (u32, u32)) -> Result<Layer, String> {
let picture = self.facts.picture.ok_or("no video stream")?;
// The layer scales the decoder's own textures; software pictures have none.
let device = self.ring.as_ref().filter(|_| self.facts.hardware).map(Ring::device).ok_or("software pictures draw in the UI")?;
Layer::new(device, picture, size)
}
/// Scales a picture into the clip's layer when the window has the layer up and the clock
/// runs, and returns that clock; None leaves the picture to the window.
fn blit_on_layer(&mut self, pipe: &Pipe, job: &Job, texture: Option<(ID3D11Texture2D, u32)>) -> Option<Anchor> {
let (Some(layer), Some((texture, index)), Some(clock)) = (&mut self.layer, texture, job.clock.get()) else { return None };
if pipe.lock().layer.is_none() {
return None;
}
if let Err(e) = layer.blit(&texture, index) {
if logging() {
log!("the layer couldn't take a picture: {e}; the window draws them");
}
pipe.lock().layer_refused = true;
return None;
}
Some(clock)
}
/// Presents the picture `blit_on_layer` scaled at its time on the clock; false leaves it to
/// the window. The wait ends early for a seek, a stop or the window taking the pictures back,
/// and follows the clock where the sound moves it.
fn present_when_due(&mut self, pipe: &Pipe, job: &Job, clock: Anchor, pts: f64, generation: u32) -> bool {
let Some(layer) = &self.layer else { return false };
let mut s = pipe.lock();
loop {
if s.stop || s.seek.is_some() || s.layer.is_none() {
return false;
}
// Paused, or the rate changed, while it waited: the window decides again.
let Some(now_clock) = job.clock.get().filter(|c| c.rate == clock.rate) else { return false };
let due = now_clock.when(pts);
let at = due.checked_sub(LAYER_LEAD).unwrap_or(due);
let now = rune_core::time::now();
if now >= at {
break;
}
s = pipe.wake.wait_timeout(s, at - now).unwrap().0;
}
drop(s);
if let Err(e) = layer.present() {
if logging() {
log!("{e}; the window draws the pictures");
}
pipe.lock().layer_refused = true;
return false;
}
pipe.lock().layer_shown = Some((layer.size, generation));
true
}
fn picture(&mut self, sample: &IMFSample) -> Result<(Pic, Option<(ID3D11Texture2D, u32)>), String> {
let picture = self.facts.picture.ok_or("no video stream")?;
// SAFETY: COM reads on a sample this thread owns.
let texture = unsafe {
sample.GetBufferByIndex(0).ok().and_then(|b| b.cast::<IMFDXGIBuffer>().ok()).and_then(|b| {
let mut raw = std::ptr::null_mut();
b.GetResource(&ID3D11Texture2D::IID, &mut raw).ok()?;
Some((ID3D11Texture2D::from_raw(raw), b.GetSubresourceIndex().ok()?))
})
};
// Rune replaced its device (a lost one, a driver update): the ring's textures and fences
// were opened on the old one, and the decoders' D3D11 device went with it, so the decoder
// lets go and the clip opens again at its picture on the new one.
if self.ring.as_ref().is_some_and(Ring::stale) {
let device = gpu::device()?;
if !self.ring.as_mut().is_some_and(|r| r.adopt(&device)) {
return Err(DEVICE_CHANGED.into());
}
}
let Some(ring) = &mut self.ring else {
return mf::nv12_bytes(sample, &picture).map(|bytes| (Pic::Cpu(bytes), None));
};
let slot = ring.take()?.ok_or("no free video texture")?;
let (planes, value) = match &texture {
Some((texture, index)) => {
// DXVA decoders write into textures bound for decoding.
let mut desc = Default::default();
// SAFETY: a plain query on a live texture.
unsafe { texture.GetDesc(&mut desc) };
self.facts.hardware = desc.BindFlags & D3D11_BIND_DECODER.0 as u32 != 0;
ring.copy(slot, texture, *index)
}
None => ring.upload(slot, &mf::nv12_bytes(sample, &picture)?),
};
Ok((Pic::Gpu(planes, value), texture))
}
}
@@ -0,0 +1,291 @@
//! Where decoded pictures live on the GPU. Media Foundation decodes on a D3D11 device (its DXVA
//! decoders take a DXGI device manager), made once per process on the adapter Rune draws with.
//! Each player keeps a small ring of shared NV12 textures: the decoder's output is copied into a
//! free one on the GPU, the copy signals a fence, and Rune's D3D12 device samples the texture in
//! place (`native_surface::windows::DecodedPlanes`). Pictures never pass through the CPU.
#![allow(unsafe_code)]
use super::mf::{self, Picture};
use crate::native_surface::windows::{DecodedPlanes, VideoFences, device_generation, presenting_device};
use std::sync::{Arc, Mutex};
use windows::Win32::Foundation::{CloseHandle, GENERIC_ALL, HMODULE, LUID};
use windows::Win32::Graphics::Direct3D::{D3D_DRIVER_TYPE, D3D_DRIVER_TYPE_UNKNOWN, D3D_FEATURE_LEVEL, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_1};
use windows::Win32::Graphics::Direct3D11::*;
use windows::Win32::Graphics::Direct3D12::{D3D12_FENCE_FLAG_NONE, D3D12_FENCE_FLAG_SHARED, ID3D12Device, ID3D12Fence, ID3D12Resource};
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_NV12, DXGI_SAMPLE_DESC};
use windows::Win32::Graphics::Dxgi::{IDXGIAdapter, IDXGIFactory4, IDXGIResource1};
use windows::Win32::Media::MediaFoundation::IMFDXGIDeviceManager;
use windows::core::{GUID, HRESULT, Interface};
/// Pictures a player's ring holds: the few the decoder runs ahead, the one on screen, one the GPU
/// may still be reading and a spare.
pub(super) const RING: usize = 6;
type CreateDevice = unsafe extern "system" fn(
*mut core::ffi::c_void,
D3D_DRIVER_TYPE,
HMODULE,
u32,
*const D3D_FEATURE_LEVEL,
u32,
u32,
*mut *mut core::ffi::c_void,
*mut D3D_FEATURE_LEVEL,
*mut *mut core::ffi::c_void,
) -> HRESULT;
type CreateFactory = unsafe extern "system" fn(*const GUID, *mut *mut core::ffi::c_void) -> HRESULT;
/// The D3D11 device decoders share, on the adapter of Rune's D3D12 device.
pub(super) struct Device {
pub device: ID3D11Device,
pub context: ID3D11DeviceContext4,
device5: ID3D11Device5,
/// Rune's device, which opens the ring's textures and owns the fences.
pub d3d12: ID3D12Device,
luid: LUID,
/// `device_generation` when `d3d12` was Rune's device: a ring made on an older one is
/// checked against the current device (`Ring::stale`).
generation: u64,
}
static DEVICE: Mutex<Option<Arc<Device>>> = Mutex::new(None);
/// The decoders' D3D11 device, made on first use and kept; None when Rune draws without D3D12
/// or the adapter can't make one (decoding then runs on the CPU).
pub(super) fn device() -> Result<Arc<Device>, String> {
// The generation first: a device made after this read makes the result stale at once.
let generation = device_generation();
let d3d12 = presenting_device().ok_or("no D3D12 device draws a window")?;
// SAFETY: a plain query on a live device.
let luid = unsafe { d3d12.GetAdapterLuid() };
let mut slot = DEVICE.lock().unwrap();
if let Some(device) = slot.as_ref().filter(|d| d.luid.LowPart == luid.LowPart && d.luid.HighPart == luid.HighPart) {
if device.d3d12.as_raw() == d3d12.as_raw() && device.generation == generation {
return Ok(device.clone());
}
if device.d3d12.as_raw() == d3d12.as_raw() {
// Only the count moved (another window noted the same device).
let current = Arc::new(Device { device: device.device.clone(), context: device.context.clone(), device5: device.device5.clone(), d3d12, luid, generation });
*slot = Some(current.clone());
return Ok(current);
}
// Rune replaced a lost device. Whatever lost it (a removed device, a driver update, a
// TDR) leaves the decoders' D3D11 device unusable too, so everything is made again.
}
let device = Arc::new(make(d3d12, luid, generation)?);
*slot = Some(device.clone());
Ok(device)
}
/// Drops the kept decoder device once Rune's device under it is removed: it holds that device.
/// Decoders still holding their own reference let go as they see the loss (`lost_since`).
pub(crate) fn release_removed_device() {
let mut slot = DEVICE.lock().unwrap();
// SAFETY: a plain query on a device this slot holds.
if slot.as_ref().is_some_and(|d| unsafe { d.d3d12.GetDeviceRemovedReason() }.is_err()) {
*slot = None;
}
}
/// Rune's device was replaced since `generation`, or the one it presents with is removed.
pub(super) fn lost_since(generation: u64) -> bool {
// SAFETY: a plain query on a live device.
device_generation() != generation || presenting_device().is_some_and(|d| unsafe { d.GetDeviceRemovedReason() }.is_err())
}
fn make(d3d12: ID3D12Device, luid: LUID, generation: u64) -> Result<Device, String> {
let d3d11 = mf::system_library("d3d11.dll").ok_or("d3d11.dll is missing")?;
let dxgi = mf::system_library("dxgi.dll").ok_or("dxgi.dll is missing")?;
// SAFETY: documented entry points cast to their documented signatures; the out pointers are
// owned references on success.
unsafe {
let create: CreateDevice = mf::symbol(d3d11, c"D3D11CreateDevice").ok_or("no D3D11CreateDevice")?;
let factory: CreateFactory = mf::symbol(dxgi, c"CreateDXGIFactory1").ok_or("no CreateDXGIFactory1")?;
let mut raw = std::ptr::null_mut();
factory(&IDXGIFactory4::IID, &mut raw).ok().map_err(|e| format!("DXGI: {}", e.message()))?;
let factory = IDXGIFactory4::from_raw(raw);
let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(luid).map_err(|e| format!("Rune's GPU: {}", e.message()))?;
let levels = [D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0];
let (mut device, mut context) = (std::ptr::null_mut(), std::ptr::null_mut());
let flags = (D3D11_CREATE_DEVICE_VIDEO_SUPPORT.0 | D3D11_CREATE_DEVICE_BGRA_SUPPORT.0) as u32;
create(adapter.as_raw(), D3D_DRIVER_TYPE_UNKNOWN, HMODULE::default(), flags, levels.as_ptr(), levels.len() as u32, D3D11_SDK_VERSION, &mut device, std::ptr::null_mut(), &mut context)
.ok()
.map_err(|e| format!("no D3D11 video device: {}", e.message()))?;
let device = ID3D11Device::from_raw(device);
let context = ID3D11DeviceContext::from_raw(context);
// Decoders and players' threads share the device.
if let Ok(mt) = device.cast::<ID3D11Multithread>() {
let _prev = mt.SetMultithreadProtected(true);
}
let device5 = device.cast::<ID3D11Device5>().map_err(|_| "D3D11 fences need Windows 10 1703")?;
let context = context.cast::<ID3D11DeviceContext4>().map_err(|_| "D3D11 fences need Windows 10 1703")?;
Ok(Device { device, context, device5, d3d12, luid, generation })
}
}
impl Device {
/// A DXGI device manager over this device, for one reader.
pub(super) fn manager(&self, lib: &mf::Library) -> Result<IMFDXGIDeviceManager, String> {
let (manager, token) = lib.device_manager()?;
// SAFETY: hands the manager a reference to the live device.
unsafe { manager.ResetDevice(&self.device, token) }.map_err(|e| e.message())?;
Ok(manager)
}
}
/// One texture of the ring.
struct Slot {
texture: ID3D11Texture2D,
planes: Arc<DecodedPlanes>,
/// The fence value of the picture last written into it.
value: u64,
}
/// A player's shared NV12 textures, the size of its pictures.
pub(super) struct Ring {
device: Arc<Device>,
slots: Vec<Slot>,
fences: Arc<VideoFences>,
ready: ID3D11Fence,
value: u64,
crop: (u32, u32, u32, u32),
}
impl Ring {
/// The decoders' device this ring's textures are on.
pub(super) fn device(&self) -> Arc<Device> {
self.device.clone()
}
/// Rune made a new device since this ring opened its textures and fences on the old one.
pub(super) fn stale(&self) -> bool {
self.device.generation != device_generation()
}
/// Takes `device` when it's the device this ring opened its textures on (only the count
/// moved); false when the ring must be made again.
pub(super) fn adopt(&mut self, device: &Arc<Device>) -> bool {
let same = device.d3d12.as_raw() == self.device.d3d12.as_raw();
if same {
self.device = device.clone();
}
same
}
pub(super) fn new(device: Arc<Device>, picture: &Picture) -> Result<Self, String> {
// SAFETY: fences made on Rune's device and opened on the D3D11 one through a shared
// handle, closed once both hold the object.
let (fences, ready) = unsafe {
let ready12: ID3D12Fence = device.d3d12.CreateFence(0, D3D12_FENCE_FLAG_SHARED).map_err(|e| format!("fence: {}", e.message()))?;
let release: ID3D12Fence = device.d3d12.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| format!("fence: {}", e.message()))?;
let handle = device.d3d12.CreateSharedHandle(&ready12, None, GENERIC_ALL.0, None).map_err(|e| format!("share fence: {}", e.message()))?;
let mut ready: Option<ID3D11Fence> = None;
let opened = device.device5.OpenSharedFence(handle, &mut ready);
CloseHandle(handle).ok();
opened.map_err(|e| format!("open fence: {}", e.message()))?;
(Arc::new(VideoFences { ready: ready12, release }), ready.ok_or("open fence")?)
};
Ok(Self { device, slots: Vec::with_capacity(RING), fences, ready, value: 0, crop: picture.crop })
}
/// Whether a picture could be written now: a slot is free, or there's room for another.
pub(super) fn free(&self) -> bool {
self.slots.len() < RING || self.reusable().is_some()
}
/// A slot no picture on screen, in a queue or in flight on the GPU uses.
fn reusable(&self) -> Option<usize> {
// SAFETY: a plain read of the fence's value.
let released = unsafe { self.fences.release.GetCompletedValue() };
self.slots.iter().position(|s| Arc::strong_count(&s.planes) == 1 && (s.value == 0 || released >= s.value))
}
/// A free slot, made when every made one is busy and the ring isn't full: a clip that shows
/// one picture (a paused clip, a poster) makes one texture, not the whole ring.
pub(super) fn take(&mut self) -> Result<Option<usize>, String> {
if let Some(i) = self.reusable() {
return Ok(Some(i));
}
if self.slots.len() == RING {
return Ok(None);
}
let (_, _, w, h) = self.crop;
self.slots.push(slot(&self.device, &self.fences, w, h)?);
Ok(Some(self.slots.len() - 1))
}
/// A picture that never reached Rune (its layer showed it instead): its slot is free once the
/// last reference goes, with no read of Rune's to wait for.
pub(super) fn unread(&mut self, planes: &Arc<DecodedPlanes>) {
if let Some(slot) = self.slots.iter_mut().find(|s| Arc::ptr_eq(&s.planes, planes)) {
slot.value = 0;
}
}
/// Copies a decoder texture (array slice `index`) into slot `i` on the GPU.
pub(super) fn copy(&mut self, i: usize, source: &ID3D11Texture2D, index: u32) -> (Arc<DecodedPlanes>, u64) {
let (x, y, w, h) = self.crop;
let area = D3D11_BOX { left: x, top: y, front: 0, right: x + w, bottom: y + h, back: 1 };
// SAFETY: both textures are NV12 on this device; the box lies inside the source.
unsafe { self.device.context.CopySubresourceRegion(&self.slots[i].texture, 0, 0, 0, 0, source, index, Some(&area)) };
self.signal(i)
}
/// Uploads packed NV12 planes (a software decoder's picture) into slot `i`.
pub(super) fn upload(&mut self, i: usize, frame: &crate::native_surface::ByteFrame) -> (Arc<DecodedPlanes>, u64) {
let w = frame.width as usize;
// D3D11 takes an NV12 subresource as one block: the chroma rows follow the luma rows.
let mut packed = Vec::with_capacity(frame.planes[0].len() + frame.planes[1].len());
packed.extend_from_slice(&frame.planes[0]);
packed.extend_from_slice(&frame.planes[1]);
// SAFETY: `packed` holds `height * 1.5` rows of `w` bytes, the texture's layout.
unsafe { self.device.context.UpdateSubresource(&self.slots[i].texture, 0, None, packed.as_ptr().cast(), w as u32, 0) };
self.signal(i)
}
fn signal(&mut self, i: usize) -> (Arc<DecodedPlanes>, u64) {
self.value += 1;
self.slots[i].value = self.value;
// SAFETY: a signal after the copy on the immediate context; the flush sends both to the GPU.
unsafe {
self.device.context.Signal(&self.ready, self.value).ok();
self.device.context.Flush();
}
(self.slots[i].planes.clone(), self.value)
}
}
/// A shared NV12 texture made on D3D11 and opened on Rune's D3D12 device.
fn slot(device: &Device, fences: &Arc<VideoFences>, w: u32, h: u32) -> Result<Slot, String> {
let desc = D3D11_TEXTURE2D_DESC {
Width: w,
Height: h,
MipLevels: 1,
ArraySize: 1,
Format: DXGI_FORMAT_NV12,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Usage: D3D11_USAGE_DEFAULT,
BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
CPUAccessFlags: 0,
MiscFlags: (D3D11_RESOURCE_MISC_SHARED.0 | D3D11_RESOURCE_MISC_SHARED_NTHANDLE.0) as u32,
};
// SAFETY: a texture of `desc` shared through an NT handle that's closed once D3D12 opened it.
unsafe {
let mut texture = None;
device.device.CreateTexture2D(&desc, None, Some(&mut texture)).map_err(|e| format!("video texture: {}", e.message()))?;
let texture = texture.ok_or("video texture")?;
let handle = texture.cast::<IDXGIResource1>().and_then(|r| r.CreateSharedHandle(None, GENERIC_ALL.0, None)).map_err(|e| format!("share video texture: {}", e.message()))?;
let mut resource: Option<ID3D12Resource> = None;
let opened = device.d3d12.OpenSharedHandle(handle, &mut resource);
CloseHandle(handle).ok();
opened.map_err(|e| format!("open video texture: {}", e.message()))?;
let planes = Arc::new(DecodedPlanes {
resource: resource.ok_or("open video texture")?,
size: [w, h],
fences: fences.clone(),
device: device.d3d12.as_raw() as usize,
});
Ok(Slot { texture, planes, value: 0 })
}
}
@@ -0,0 +1,225 @@
//! A playing clip's own layer: an NV12 swap chain on the decoders' D3D11 device, which the window
//! shows on a DirectComposition visual under its UI while the video's place is still. The decoder
//! thread scales each picture into it with the GPU's video processor and presents it at the
//! picture's time, so playing draws no UI frame per picture.
//!
//! Made as Chromium makes its video swap chains: on a DirectComposition surface handle through
//! `IDXGIFactoryMedia`, which is also the only way to an NV12 swap chain (one the display can scan
//! out as an overlay plane); `CreateSwapChainForComposition` refuses NV12. The window wraps the
//! handle in a surface of its own DirectComposition device (`handle`).
#![allow(unsafe_code)]
use super::gpu::Device;
use super::mf::{self, Picture};
use crate::native_surface::{Format, Matrix, Orient};
use std::mem::ManuallyDrop;
use std::sync::Arc;
use windows::Win32::Foundation::{CloseHandle, HANDLE, RECT};
use windows::Win32::Graphics::Direct3D11::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::Graphics::Dxgi::*;
use windows::core::{HRESULT, Interface};
type CreateSurfaceHandle = unsafe extern "system" fn(u32, *const core::ffi::c_void, *mut HANDLE) -> HRESULT;
/// `COMPOSITIONOBJECT_READ | COMPOSITIONOBJECT_WRITE`.
const ALL_ACCESS: u32 = 0x3;
pub(super) struct Layer {
swap: IDXGISwapChain3,
/// The DirectComposition surface handle the swap chain presents to; closed on drop.
handle: HANDLE,
/// The video's place on screen, in device pixels, as the window asked.
pub size: (u32, u32),
/// The swap chain's buffers: `size` with even sides.
buffer: (u32, u32),
video: ID3D11VideoDevice,
context: ID3D11VideoContext1,
processor: Option<(ID3D11VideoProcessorEnumerator, ID3D11VideoProcessor, ID3D11VideoProcessorOutputView)>,
/// Input views of the decoder's textures, by texture and array slice.
inputs: Vec<(usize, u32, ID3D11VideoProcessorInputView)>,
picture: Picture,
}
// SAFETY: the decoder thread makes, uses and drops a layer; the device is multithread-protected.
unsafe impl Send for Layer {}
impl Drop for Layer {
fn drop(&mut self) {
// SAFETY: the handle this layer made and nobody else closes.
unsafe {
CloseHandle(self.handle).ok();
}
}
}
impl Layer {
/// A layer `size` device pixels for `picture`'s clip. Rotated clips stay in the UI.
pub(super) fn new(device: Arc<Device>, picture: Picture, size: (u32, u32)) -> Result<Layer, String> {
if picture.orient != Orient::default() {
return Err("a rotated clip draws in the UI".into());
}
let buffer = even(size);
let dcomp = mf::system_library("dcomp.dll").ok_or("dcomp.dll is missing")?;
// SAFETY: the documented entry point at its documented signature; the handle it writes is
// owned by this layer. The swap chain is made on the decoders' live device.
unsafe {
let create: CreateSurfaceHandle = mf::symbol(dcomp, c"DCompositionCreateSurfaceHandle").ok_or("no DCompositionCreateSurfaceHandle")?;
let mut handle = HANDLE::default();
create(ALL_ACCESS, std::ptr::null(), &mut handle).ok().map_err(|e| format!("composition surface: {}", e.message()))?;
let swap = match swap_chain(&device, handle, buffer) {
Ok(swap) => swap,
Err(e) => {
CloseHandle(handle).ok();
return Err(e);
}
};
let video: ID3D11VideoDevice = device.device.cast().map_err(|_| "no video processor")?;
let context: ID3D11VideoContext1 = device.context.cast().map_err(|_| "no video processor")?;
Ok(Layer { swap, handle, size, buffer, video, context, processor: None, inputs: Vec::new(), picture })
}
}
/// The DirectComposition surface handle, for the window's `CreateSurfaceFromHandle`.
pub(super) fn handle(&self) -> usize {
self.handle.0 as usize
}
/// The video's place changed size: the swap chain follows; the next picture fills it.
pub(super) fn resize(&mut self, size: (u32, u32)) -> Result<(), String> {
if size == self.size {
return Ok(());
}
let buffer = even(size);
// The output view holds the old buffer: it goes before the buffers are made again.
self.processor = None;
// SAFETY: no view of the swap chain's buffers is alive.
unsafe { self.swap.ResizeBuffers(0, buffer.0, buffer.1, DXGI_FORMAT_UNKNOWN, SWAP_FLAGS) }.map_err(|e| format!("resize video layer: {}", e.message()))?;
self.size = size;
self.buffer = buffer;
Ok(())
}
/// Scales array slice `index` of the decoder's `texture` into the swap chain's next buffer.
pub(super) fn blit(&mut self, texture: &ID3D11Texture2D, index: u32) -> Result<(), String> {
if self.processor.is_none() {
self.processor = Some(self.processor()?);
}
let Some((enumerator, processor, output)) = &self.processor else { return Ok(()) };
let key = texture.as_raw() as usize;
let input = match self.inputs.iter().find(|(t, i, _)| *t == key && *i == index) {
Some((_, _, view)) => view.clone(),
None => {
let mut desc = D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC { FourCC: 0, ViewDimension: D3D11_VPIV_DIMENSION_TEXTURE2D, ..Default::default() };
desc.Anonymous.Texture2D = D3D11_TEX2D_VPIV { MipSlice: 0, ArraySlice: index };
let mut view = None;
// SAFETY: a view of a live decoder texture on this device.
unsafe { self.video.CreateVideoProcessorInputView(texture, enumerator, &desc, Some(&mut view)) }.map_err(|e| format!("video input: {}", e.message()))?;
let view = view.ok_or("video input")?;
// A decoder cycles a handful of textures; a new decoder's are new keys.
if self.inputs.len() >= 32 {
self.inputs.remove(0);
}
self.inputs.push((key, index, view.clone()));
view
}
};
let mut stream = D3D11_VIDEO_PROCESSOR_STREAM { Enable: true.into(), pInputSurface: ManuallyDrop::new(Some(input)), ..Default::default() };
// SAFETY: one enabled stream whose input view and output view are live on this device.
let done = unsafe { self.context.VideoProcessorBlt(processor, output, 0, std::slice::from_ref(&stream)) };
// SAFETY: drops the reference the stream took above, once.
unsafe { ManuallyDrop::drop(&mut stream.pInputSurface) };
done.map_err(|e| format!("scale picture: {}", e.message()))
}
/// Shows the last blitted picture at the display's next refresh.
pub(super) fn present(&self) -> Result<(), String> {
// SAFETY: a present on this layer's swap chain.
let presented = unsafe { self.swap.Present(1, DXGI_PRESENT(0)) };
presented.ok().map_err(|e| format!("present video layer: {}", e.message()))
}
/// The video processor for this clip and this size, writing into buffer 0 (which D3D11 moves
/// to each present's next buffer).
fn processor(&self) -> Result<(ID3D11VideoProcessorEnumerator, ID3D11VideoProcessor, ID3D11VideoProcessorOutputView), String> {
let (x, y, w, h) = self.picture.crop;
let rate = DXGI_RATIONAL { Numerator: (1.0 / self.picture.frame.max(1e-3)).round() as u32, Denominator: 1 };
let desc = D3D11_VIDEO_PROCESSOR_CONTENT_DESC {
InputFrameFormat: D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE,
InputFrameRate: rate,
InputWidth: self.picture.coded.0,
InputHeight: self.picture.coded.1,
OutputFrameRate: rate,
OutputWidth: self.buffer.0,
OutputHeight: self.buffer.1,
Usage: D3D11_VIDEO_USAGE_PLAYBACK_NORMAL,
};
// SAFETY: video processor setup on this device; the buffer is the swap chain's own.
unsafe {
let enumerator = self.video.CreateVideoProcessorEnumerator(&desc).map_err(|e| format!("video processor: {}", e.message()))?;
let processor = self.video.CreateVideoProcessor(&enumerator, 0).map_err(|e| format!("video processor: {}", e.message()))?;
let buffer: ID3D11Texture2D = self.swap.GetBuffer(0).map_err(|e| format!("video layer buffer: {}", e.message()))?;
let out = D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC { ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2D, ..Default::default() };
let mut output = None;
self.video.CreateVideoProcessorOutputView(&buffer, &enumerator, &out, Some(&mut output)).map_err(|e| format!("video output: {}", e.message()))?;
let c = &self.context;
c.VideoProcessorSetStreamFrameFormat(&processor, 0, D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE);
// No denoising, edge enhancement or other "improvements": the picture as decoded.
c.VideoProcessorSetStreamAutoProcessingMode(&processor, 0, false);
c.VideoProcessorSetStreamColorSpace1(&processor, 0, input_space(&self.picture));
c.VideoProcessorSetOutputColorSpace1(&processor, DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709);
let source = RECT { left: x as i32, top: y as i32, right: (x + w) as i32, bottom: (y + h) as i32 };
let target = RECT { left: 0, top: 0, right: self.buffer.0 as i32, bottom: self.buffer.1 as i32 };
c.VideoProcessorSetStreamSourceRect(&processor, 0, true, Some(&source));
c.VideoProcessorSetStreamDestRect(&processor, 0, true, Some(&target));
c.VideoProcessorSetOutputTargetRect(&processor, true, Some(&target));
Ok((enumerator, processor, output.ok_or("video output")?))
}
}
}
/// `DXGI_SWAP_CHAIN_FLAG_YUV_VIDEO | DXGI_SWAP_CHAIN_FLAG_FULLSCREEN_VIDEO`, as Chromium's.
const SWAP_FLAGS: DXGI_SWAP_CHAIN_FLAG = DXGI_SWAP_CHAIN_FLAG(DXGI_SWAP_CHAIN_FLAG_YUV_VIDEO.0 | DXGI_SWAP_CHAIN_FLAG_FULLSCREEN_VIDEO.0);
/// An NV12 swap chain presenting to the composition surface `handle`.
unsafe fn swap_chain(device: &Device, handle: HANDLE, size: (u32, u32)) -> Result<IDXGISwapChain3, String> {
let desc = DXGI_SWAP_CHAIN_DESC1 {
Width: size.0,
Height: size.1,
Format: DXGI_FORMAT_NV12,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
BufferCount: 2,
Scaling: DXGI_SCALING_STRETCH,
SwapEffect: DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL,
AlphaMode: DXGI_ALPHA_MODE_IGNORE,
Flags: SWAP_FLAGS.0 as u32,
..Default::default()
};
// SAFETY: the decoders' live device and a composition surface handle this layer owns.
unsafe {
let factory: IDXGIFactoryMedia = device.device.cast::<IDXGIDevice>().and_then(|d| d.GetAdapter()).and_then(|a| a.GetParent()).map_err(|e| format!("DXGI media factory: {}", e.message()))?;
let swap: IDXGISwapChain3 = factory
.CreateSwapChainForCompositionSurfaceHandle(&device.device, Some(handle), &desc, None)
.and_then(|s| s.cast())
.map_err(|e| format!("video layer: {}", e.message()))?;
swap.SetColorSpace1(DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709).map_err(|e| format!("video layer colours: {}", e.message()))?;
Ok(swap)
}
}
/// The decoder's YCbCr encoding as DXGI names it.
fn input_space(picture: &Picture) -> DXGI_COLOR_SPACE_TYPE {
match (picture.color.matrix, picture.format) {
(Matrix::Bt709, Format::Nv12Full) => DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P709,
(Matrix::Bt709, _) => DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709,
(Matrix::Bt601, Format::Nv12Full) => DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P601,
(Matrix::Bt601, _) => DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P601,
}
}
/// NV12 needs even sides.
fn even((w, h): (u32, u32)) -> (u32, u32) {
((w.max(2) + 1) & !1, (h.max(2) + 1) & !1)
}
@@ -0,0 +1,205 @@
//! The Windows player's phases as plain data: what its decoder is doing and which picture time
//! the screen holds. [`step`] takes one event and returns what to do; the backend (`mod.rs`)
//! carries the effects out on the UI thread, in the frame that draws the clip.
//!
//! Times are unwrapped seconds: a loop keeps counting past the duration, so a clip's pictures
//! always move forward and the clock never jumps back at the loop point.
use rune_core::machine::Effects;
use rune_core::time::Instant;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Phase {
/// No decoder: never asked for, or let go while undrawn. The surface keeps the picture at
/// `at`, and opening starts there.
Idle { at: f64 },
/// The decoder is opening the source.
Opening { at: f64, play: bool },
/// Waiting for the picture at `at`: after opening, a seek, or a stall while playing, when
/// the clock holds. `play`: playback goes on once it lands.
Buffering { at: f64, play: bool },
/// Pictures follow the clock.
Playing { clock: Anchor },
/// The picture at `at` holds.
Paused { at: f64 },
/// The last picture showed and the clip doesn't loop.
Ended { at: f64 },
Failed,
}
impl Default for Phase {
fn default() -> Self {
Phase::Idle { at: 0.0 }
}
}
/// The playback clock: `pos` media seconds at `at`, moving `rate` media seconds per second.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Anchor {
pub at: Instant,
pub pos: f64,
pub rate: f64,
}
impl Anchor {
pub(crate) fn position(&self, t: Instant) -> f64 {
match t.checked_duration_since(self.at) {
Some(d) => self.pos + d.as_secs_f64() * self.rate,
None => self.pos - self.at.duration_since(t).as_secs_f64() * self.rate,
}
}
/// When the clock reaches `pos`.
pub(crate) fn when(&self, pos: f64) -> Instant {
let d = (pos - self.pos) / self.rate;
if d >= 0.0 { self.at + std::time::Duration::from_secs_f64(d) } else { self.at - std::time::Duration::from_secs_f64(-d) }
}
}
pub(super) enum Event {
/// A frame wants the clip's pictures and no decoder runs.
Open { play: bool },
Opened,
Failed,
/// The first picture at or after the phase's time reached the surface, at presentation `target`.
Shown { pts: f64, target: Instant, lead: f64, rate: f64 },
Play { target: Instant, lead: f64, rate: f64 },
/// Hold the picture on screen, at `at`.
Pause { at: f64 },
Seek { to: f64 },
Rate { target: Instant, rate: f64 },
/// Playing, with no picture due and the decoder behind: hold the clock at `at`.
Stalled { at: f64 },
/// The last picture showed, at `at`.
Ended { at: f64 },
/// Drawn again after a gap with nothing heard: the clock picks up at the picture on screen.
Resumed { target: Instant, at: f64, lead: f64 },
/// The decoder let go of the clip.
Released { at: f64 },
/// The sound moved the running clock to where it plays.
Synced { clock: Anchor },
}
#[derive(Debug, PartialEq)]
pub(super) enum Effect {
/// Start a decoder at `at`.
Open { at: f64 },
/// Move the decoder to `to`.
Seek { to: f64 },
/// The clock changed: sound follows it (`None`: silent).
Clock(Option<Anchor>),
}
/// The clock that shows `pts` at `target`: `lead` ahead of it, so later presentations land
/// mid-way between picture boundaries and a little jitter never shows a picture twice.
fn anchor(target: Instant, pts: f64, lead: f64, rate: f64) -> Anchor {
Anchor { at: target, pos: pts + lead, rate }
}
pub(super) fn step(phase: &mut Phase, event: Event) -> Effects<Effect> {
use Phase as P;
match (*phase, event) {
(P::Failed, _) => Effects::none(),
(_, Event::Failed) => {
*phase = P::Failed;
Effects::one(Effect::Clock(None))
}
(P::Idle { at }, Event::Open { play }) => {
*phase = P::Opening { at, play };
Effects::one(Effect::Open { at })
}
(P::Opening { at, play }, Event::Opened) => {
*phase = P::Buffering { at, play };
Effects::none()
}
(P::Buffering { play, .. }, Event::Shown { pts, target, lead, rate }) => {
if play {
let clock = anchor(target, pts, lead, rate);
*phase = P::Playing { clock };
Effects::one(Effect::Clock(Some(clock)))
} else {
*phase = P::Paused { at: pts };
Effects::none()
}
}
(P::Opening { at, .. }, Event::Play { .. }) => {
*phase = P::Opening { at, play: true };
Effects::none()
}
(P::Buffering { at, .. }, Event::Play { .. }) => {
*phase = P::Buffering { at, play: true };
Effects::none()
}
(P::Paused { at }, Event::Play { target, lead, rate }) => {
let clock = anchor(target, at, lead, rate);
*phase = P::Playing { clock };
Effects::one(Effect::Clock(Some(clock)))
}
(P::Opening { at, .. }, Event::Pause { .. }) => {
*phase = P::Opening { at, play: false };
Effects::none()
}
(P::Buffering { at, .. }, Event::Pause { .. }) => {
*phase = P::Buffering { at, play: false };
Effects::none()
}
(P::Playing { .. }, Event::Pause { at }) => {
*phase = P::Paused { at };
Effects::one(Effect::Clock(None))
}
(P::Paused { .. }, Event::Pause { at }) => {
*phase = P::Paused { at };
Effects::none()
}
(P::Idle { .. }, Event::Seek { to }) => {
*phase = P::Idle { at: to };
Effects::none()
}
(P::Opening { play, .. }, Event::Seek { to }) => {
*phase = P::Opening { at: to, play };
Effects::one(Effect::Seek { to })
}
(P::Buffering { play, .. }, Event::Seek { to }) => {
*phase = P::Buffering { at: to, play };
Effects::one(Effect::Seek { to })
}
(P::Playing { .. }, Event::Seek { to }) => {
*phase = P::Buffering { at: to, play: true };
Effects::two(Effect::Clock(None), Effect::Seek { to })
}
(P::Paused { .. } | P::Ended { .. }, Event::Seek { to }) => {
*phase = P::Buffering { at: to, play: false };
Effects::one(Effect::Seek { to })
}
(P::Playing { clock }, Event::Rate { target, rate }) => {
let clock = Anchor { at: target, pos: clock.position(target), rate };
*phase = P::Playing { clock };
Effects::one(Effect::Clock(Some(clock)))
}
(P::Playing { .. }, Event::Stalled { at }) => {
*phase = P::Buffering { at, play: true };
Effects::one(Effect::Clock(None))
}
(P::Playing { .. }, Event::Ended { at }) => {
*phase = P::Ended { at };
Effects::one(Effect::Clock(None))
}
(P::Playing { clock }, Event::Synced { clock: heard }) if heard.rate == clock.rate => {
*phase = P::Playing { clock: heard };
Effects::none()
}
(P::Playing { clock }, Event::Resumed { target, at, lead }) => {
let clock = anchor(target, at, lead, clock.rate);
*phase = P::Playing { clock };
Effects::one(Effect::Clock(Some(clock)))
}
(P::Opening { .. } | P::Buffering { .. } | P::Playing { .. } | P::Paused { .. } | P::Ended { .. }, Event::Released { at }) => {
*phase = P::Idle { at };
Effects::one(Effect::Clock(None))
}
_ => Effects::none(),
}
}
@@ -0,0 +1,34 @@
//! Tests for the player's phases.
use super::{Anchor, Effect, Event, Phase, step};
fn effects(phase: &mut Phase, event: Event) -> Vec<Effect> {
step(phase, event).into_iter().collect()
}
#[test]
fn a_seek_while_parked_keeps_the_phase_idle_at_the_target() {
let mut phase = Phase::Idle { at: 0.0 };
assert_eq!(effects(&mut phase, Event::Seek { to: 7.5 }), vec![]);
assert_eq!(phase, Phase::Idle { at: 7.5 });
assert_eq!(effects(&mut phase, Event::Open { play: false }), vec![Effect::Open { at: 7.5 }]);
}
#[test]
fn a_paused_clip_moves_its_hold_to_the_picture_it_shows() {
let mut phase = Phase::Paused { at: 4.0 };
assert_eq!(effects(&mut phase, Event::Pause { at: 4.016 }), vec![]);
assert_eq!(phase, Phase::Paused { at: 4.016 });
}
#[test]
fn the_sound_moves_a_running_clock_at_its_rate_only() {
let at = rune_core::time::now();
let mut phase = Phase::Playing { clock: Anchor { at, pos: 1.0, rate: 1.0 } };
let heard = Anchor { at, pos: 1.004, rate: 1.0 };
assert_eq!(effects(&mut phase, Event::Synced { clock: heard }), vec![]);
assert_eq!(phase, Phase::Playing { clock: heard });
let other = Anchor { at, pos: 1.0, rate: 2.0 };
assert_eq!(effects(&mut phase, Event::Synced { clock: other }), vec![]);
assert_eq!(phase, Phase::Playing { clock: heard });
}
@@ -0,0 +1,606 @@
//! Media Foundation: the source reader that opens and decodes a clip, and its library, loaded
//! with `LoadLibraryExW` the first time a clip opens so no MF DLL is in the import table.
//! Windows N editions without the Media Feature Pack have no `mfplat.dll`: every clip then
//! fails with a message saying so, and nothing else changes.
#![allow(unsafe_code)]
use super::super::{Kind, MediaSource};
use crate::native_surface::{ByteFrame, ColorInfo, Format, Matrix, Orient, Transfer};
use std::path::{Component, Path, PathBuf, Prefix};
use std::sync::OnceLock;
use windows::Win32::Foundation::HMODULE;
use windows::Win32::Media::MediaFoundation::*;
use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW};
use windows::Win32::System::Variant::VT_I8;
use windows::core::{GUID, HRESULT, HSTRING, Interface, PCSTR, PCWSTR};
/// `MF_VERSION`: `MF_SDK_VERSION << 16 | MF_API_VERSION`.
const MF_VERSION: u32 = 0x0002_0070;
/// 100 ns units per second, Media Foundation's clock.
pub(super) const TICKS: f64 = 10_000_000.0;
type Startup = unsafe extern "system" fn(u32, u32) -> HRESULT;
type CreateAttributes = unsafe extern "system" fn(*mut *mut core::ffi::c_void, u32) -> HRESULT;
type CreateMediaType = unsafe extern "system" fn(*mut *mut core::ffi::c_void) -> HRESULT;
type CreateDeviceManager = unsafe extern "system" fn(*mut u32, *mut *mut core::ffi::c_void) -> HRESULT;
type CreateFile = unsafe extern "system" fn(MF_FILE_ACCESSMODE, MF_FILE_OPENMODE, MF_FILE_FLAGS, PCWSTR, *mut *mut core::ffi::c_void) -> HRESULT;
type CreateResolver = unsafe extern "system" fn(*mut *mut core::ffi::c_void) -> HRESULT;
type CreateReaderFromSource = unsafe extern "system" fn(*mut core::ffi::c_void, *mut core::ffi::c_void, *mut *mut core::ffi::c_void) -> HRESULT;
/// The few flat Media Foundation entry points; everything else is COM.
pub(super) struct Library {
create_attributes: CreateAttributes,
create_media_type: CreateMediaType,
create_device_manager: CreateDeviceManager,
create_file: CreateFile,
create_resolver: CreateResolver,
create_reader: CreateReaderFromSource,
}
static LIBRARY: OnceLock<Result<Library, String>> = OnceLock::new();
/// Loads Media Foundation and starts it, once per process.
pub(super) fn library() -> Result<&'static Library, String> {
LIBRARY.get_or_init(load).as_ref().map_err(Clone::clone)
}
fn load() -> Result<Library, String> {
let missing = || "Media Foundation isn't installed (a Windows N edition without the Media Feature Pack)".to_string();
let plat = system_library("mfplat.dll").ok_or_else(missing)?;
let rw = system_library("mfreadwrite.dll").ok_or_else(missing)?;
// SAFETY: each symbol is looked up by its documented name and cast to its documented signature.
unsafe {
let startup: Startup = symbol(plat, c"MFStartup").ok_or_else(missing)?;
let library = Library {
create_attributes: symbol(plat, c"MFCreateAttributes").ok_or_else(missing)?,
create_media_type: symbol(plat, c"MFCreateMediaType").ok_or_else(missing)?,
create_device_manager: symbol(plat, c"MFCreateDXGIDeviceManager").ok_or_else(missing)?,
create_file: symbol(plat, c"MFCreateFile").ok_or_else(missing)?,
create_resolver: symbol(plat, c"MFCreateSourceResolver").ok_or_else(missing)?,
create_reader: symbol(rw, c"MFCreateSourceReaderFromMediaSource").ok_or_else(missing)?,
};
// MFSTARTUP_FULL: the network source needs sockets.
startup(MF_VERSION, 0).ok().map_err(|e| format!("Media Foundation didn't start: {}", e.message()))?;
Ok(library)
}
}
/// A DLL from System32 only, never the app's folder or the current directory.
pub(super) fn system_library(name: &str) -> Option<HMODULE> {
// SAFETY: loads a system DLL by name; the handle is kept for the process's life.
unsafe { LoadLibraryExW(&HSTRING::from(name), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()
}
/// `name` from `module` as a function of type `F`.
///
/// # Safety
/// `F` must be the symbol's true signature.
pub(super) unsafe fn symbol<F: Copy>(module: HMODULE, name: &std::ffi::CStr) -> Option<F> {
// SAFETY: a lookup by name on a loaded module.
let f = unsafe { GetProcAddress(module, PCSTR(name.as_ptr().cast())) }?;
debug_assert_eq!(size_of::<F>(), size_of_val(&f));
// SAFETY: the caller vouches for `F`.
Some(unsafe { std::mem::transmute_copy(&f) })
}
impl Library {
pub(super) fn attributes(&self, count: u32) -> Result<IMFAttributes, String> {
let mut raw = std::ptr::null_mut();
// SAFETY: MFCreateAttributes fills `raw` with an owned reference on success.
unsafe { (self.create_attributes)(&mut raw, count).ok().map_err(|e| e.message())?; Ok(IMFAttributes::from_raw(raw)) }
}
fn media_type(&self) -> Result<IMFMediaType, String> {
let mut raw = std::ptr::null_mut();
// SAFETY: as `attributes`.
unsafe { (self.create_media_type)(&mut raw).ok().map_err(|e| e.message())?; Ok(IMFMediaType::from_raw(raw)) }
}
pub(super) fn device_manager(&self) -> Result<(IMFDXGIDeviceManager, u32), String> {
let (mut token, mut raw) = (0, std::ptr::null_mut());
// SAFETY: as `attributes`.
unsafe { (self.create_device_manager)(&mut token, &mut raw).ok().map_err(|e| e.message())?; Ok((IMFDXGIDeviceManager::from_raw(raw), token)) }
}
/// Opens `target` as a media source: a strict local byte stream (bypassing scheme handlers
/// and wildcard handler sniffing), or a remote URL whose first bytes say what it holds.
/// It needs no GPU, so it runs while the decoders' device comes up.
pub(super) fn resolve(&self, target: &Target) -> Result<IMFMediaSource, String> {
let mut raw = std::ptr::null_mut();
// SAFETY: as `attributes`; then a blocking resolve into an owned `IMFMediaSource`.
unsafe {
(self.create_resolver)(&mut raw).ok().map_err(|e| e.message())?;
let resolver = IMFSourceResolver::from_raw(raw);
let (mut kind, mut object) = (MF_OBJECT_INVALID, None);
match target {
Target::Local { path, ext } => {
let mut stream_raw = std::ptr::null_mut();
(self.create_file)(MF_ACCESSMODE_READ, MF_OPENMODE_FAIL_IF_NOT_EXIST, MF_FILEFLAGS_NONE, PCWSTR(path.as_ptr()), &mut stream_raw)
.ok()
.map_err(open_error)?;
let stream = IMFByteStream::from_raw(stream_raw);
// Extension-matched byte-stream handler only: no wildcard handler enumeration
// and no process-local plugins; `CreateObjectFromByteStream` skips scheme handlers.
let flags = (MF_RESOLUTION_MEDIASOURCE | MF_RESOLUTION_READ | MF_RESOLUTION_DISABLE_LOCAL_PLUGINS).0 as u32;
let hint = HSTRING::from(format!("local.{ext}"));
resolver.CreateObjectFromByteStream(&stream, &hint, flags, None, &mut kind, &mut object).map_err(open_error)?;
}
Target::Remote(url) => {
let flags = (MF_RESOLUTION_MEDIASOURCE | MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE).0 as u32;
resolver.CreateObjectFromURL(url, flags, None, &mut kind, &mut object).map_err(open_error)?;
}
}
object.ok_or("no media source")?.cast::<IMFMediaSource>().map_err(|e| e.message())
}
}
fn reader(&self, source: &IMFMediaSource, attributes: &IMFAttributes) -> Result<IMFSourceReader, String> {
let mut raw = std::ptr::null_mut();
// SAFETY: as `attributes`; the reader takes its own references to the source and the
// attributes, and shuts the source down when it goes.
unsafe { (self.create_reader)(source.as_raw(), attributes.as_raw(), &mut raw).ok().map_err(open_error)?; Ok(IMFSourceReader::from_raw(raw)) }
}
}
/// What a failed open means to someone looking at a clip that won't play.
fn open_error(e: windows::core::Error) -> String {
match e.code().0 as u32 {
0xC00D_36C4 => "Media Foundation can't read this format".into(),
0x8007_0002 | 0x8007_0003 | 0xC00D_001A => "the clip wasn't found".into(),
0x8007_0005 => "access to the clip was denied".into(),
// NS_E_SERVER_NOT_FOUND is what the network source answers for a refused connection.
0x8007_2EE7 | 0x8007_2EFD | 0x8007_2EFE | 0xC00D_2EE7 | 0xC00D_0035 => "the clip's server couldn't be reached".into(),
// MF_E_INVALIDREQUEST from the byte stream: an mp4 cut short, its index never reached.
0xC00D_36E5 => "the clip is incomplete or damaged".into(),
_ => format!("Media Foundation couldn't open the clip: {} ({:#010x})", e.message(), e.code().0),
}
}
/// The first video stream's picture, as it comes out of the reader.
#[derive(Clone, Copy, Debug)]
pub(super) struct Picture {
/// The decoder's surface, which may be taller than the picture (1920 x 1088 for 1080p).
pub coded: (u32, u32),
/// The picture inside it: x, y, width, height, all even.
pub crop: (u32, u32, u32, u32),
/// Display size in pixels (pixel aspect and rotation applied).
pub natural: (u32, u32),
pub format: Format,
pub color: ColorInfo,
pub orient: Orient,
/// Seconds per frame, from the stream's nominal rate.
pub frame: f64,
}
/// The first audio stream's samples: 32-bit float, interleaved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Sound {
pub channels: u16,
pub rate: u32,
}
pub(super) struct Opened {
pub reader: IMFSourceReader,
/// The video stream's index, which reads from any stream report.
pub video: Option<u32>,
pub picture: Option<Picture>,
/// The audio stream's index; the stream is selected only while sound plays.
pub audio: Option<u32>,
pub sound: Option<Sound>,
/// The clip has an audio stream, decodable when it was set up (`audio`).
pub has_sound: bool,
pub duration: f64,
}
/// How the reader decodes.
pub(super) enum Decode<'a> {
/// Into D3D11 textures on the manager's device, with hardware decoders where the GPU has one.
Gpu(&'a IMFDXGIDeviceManager),
/// Into system memory with software decoders.
Cpu,
}
/// Reads `source` and sets up the streams `kind` plays: for video the first video stream as
/// NV12 and, when `audio`, the first audio stream as float; for audio only the audio stream.
pub(super) fn open(lib: &Library, source: &IMFMediaSource, kind: Kind, decode: Decode<'_>, audio: bool) -> Result<Opened, String> {
let attributes = lib.attributes(4)?;
// SAFETY: plain attribute writes on an object this thread owns.
unsafe {
if let Decode::Gpu(manager) = decode {
attributes.SetUnknown(&MF_SOURCE_READER_D3D_MANAGER, manager).map_err(|e| e.message())?;
attributes.SetUINT32(&MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, 1).map_err(|e| e.message())?;
}
// Converts a decoder's other output (P010, YUY2, interlaced) to progressive NV12.
attributes.SetUINT32(&MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, 1).map_err(|e| e.message())?;
}
let reader = lib.reader(source, &attributes)?;
// SAFETY: stream selection and type negotiation on the reader this thread made.
unsafe {
reader.SetStreamSelection(MF_SOURCE_READER_ALL_STREAMS.0 as u32, false).ok();
let (video, audio_index) = streams(&reader);
let (video, picture) = match video.filter(|_| kind == Kind::Video) {
Some(index) => {
reader.SetStreamSelection(index, true).map_err(|e| e.message())?;
let wanted = lib.media_type()?;
wanted.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video).map_err(|e| e.message())?;
wanted.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_NV12).map_err(|e| e.message())?;
reader.SetCurrentMediaType(index, None, &wanted).map_err(|e| no_decoder(e, "video"))?;
(Some(index), Some(picture(&reader.GetCurrentMediaType(index).map_err(|e| e.message())?)?))
}
None if kind == Kind::Video => return Err("no playable video track".into()),
None => (None, None),
};
let mut has_sound = audio_index.is_some();
let (audio, sound) = match audio_index.filter(|_| audio || kind == Kind::Audio) {
Some(index) => match sound(lib, &reader, index) {
Ok(sound) => (Some(index), Some(sound)),
Err(e) if kind == Kind::Audio => return Err(e),
Err(_) => {
has_sound = false;
(None, None)
}
},
None if kind == Kind::Audio => return Err("no playable audio track".into()),
None => (None, None),
};
let duration = duration(&reader);
Ok(Opened { reader, video, picture, audio, sound, has_sound, duration })
}
}
/// The indexes of the first video and the first audio stream.
unsafe fn streams(reader: &IMFSourceReader) -> (Option<u32>, Option<u32>) {
let (mut video, mut audio) = (None, None);
// SAFETY: native type reads on a live reader; an index past the last stream fails.
unsafe {
for index in 0..64 {
let Ok(t) = reader.GetNativeMediaType(index, 0) else { break };
match t.GetMajorType() {
Ok(major) if major == MFMediaType_Video => video = video.or(Some(index)),
Ok(major) if major == MFMediaType_Audio => audio = audio.or(Some(index)),
_ => {}
}
}
}
(video, audio)
}
/// Stream `index` set up as float audio. It stays selected; the decoder deselects it while muted.
unsafe fn sound(lib: &Library, reader: &IMFSourceReader, index: u32) -> Result<Sound, String> {
// SAFETY: as in `open`.
unsafe {
reader.SetStreamSelection(index, true).map_err(|e| e.message())?;
let wanted = lib.media_type()?;
wanted.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Audio).map_err(|e| e.message())?;
wanted.SetGUID(&MF_MT_SUBTYPE, &MFAudioFormat_Float).map_err(|e| e.message())?;
if let Err(e) = reader.SetCurrentMediaType(index, None, &wanted) {
reader.SetStreamSelection(index, false).ok();
return Err(no_decoder(e, "audio"));
}
let current = reader.GetCurrentMediaType(index).map_err(|e| e.message())?;
let channels = current.GetUINT32(&MF_MT_AUDIO_NUM_CHANNELS).unwrap_or(2).clamp(1, 8) as u16;
let rate = current.GetUINT32(&MF_MT_AUDIO_SAMPLES_PER_SECOND).unwrap_or(48_000);
Ok(Sound { channels, rate })
}
}
fn no_decoder(e: windows::core::Error, what: &str) -> String {
match e.code().0 as u32 {
// MF_E_TOPO_CODEC_NOT_FOUND, MF_E_INVALIDMEDIATYPE
0xC00D_5212 | 0xC00D_36B4 => format!("no {what} decoder for this codec (Media Foundation has none installed)"),
_ => format!("can't decode the {what}: {}", e.message()),
}
}
/// Facts about the decoded picture from the reader's NV12 type.
unsafe fn picture(t: &IMFMediaType) -> Result<Picture, String> {
// SAFETY: attribute reads on a live media type.
unsafe {
let size = t.GetUINT64(&MF_MT_FRAME_SIZE).map_err(|_| "video track has no size".to_string())?;
let coded = ((size >> 32) as u32, size as u32);
if coded.0 < 2 || coded.1 < 2 {
return Err("video track has no size".into());
}
let mut area = MFVideoArea::default();
let bytes = std::slice::from_raw_parts_mut((&raw mut area).cast::<u8>(), size_of::<MFVideoArea>());
let crop = match t.GetBlob(&MF_MT_MINIMUM_DISPLAY_APERTURE, bytes, None) {
Ok(()) if area.Area.cx > 0 && area.Area.cy > 0 => {
let (x, y) = (area.OffsetX.value.max(0) as u32 & !1, area.OffsetY.value.max(0) as u32 & !1);
let w = (area.Area.cx as u32).min(coded.0 - x) & !1;
let h = (area.Area.cy as u32).min(coded.1 - y) & !1;
(x, y, w.max(2), h.max(2))
}
_ => (0, 0, coded.0 & !1, coded.1 & !1),
};
let full = t.GetUINT32(&MF_MT_VIDEO_NOMINAL_RANGE).is_ok_and(|r| r == MFNominalRange_0_255.0 as u32);
// Unknown matrices follow the picture's size, as browsers do: SD is BT.601.
let matrix = match t.GetUINT32(&MF_MT_YUV_MATRIX).map(|m| m as i32) {
Ok(m) if m == MFVideoTransferMatrix_BT601.0 => Matrix::Bt601,
Ok(m) if m == MFVideoTransferMatrix_BT709.0 => Matrix::Bt709,
_ if crop.3 < 720 => Matrix::Bt601,
_ => Matrix::Bt709,
};
let par = t.GetUINT64(&MF_MT_PIXEL_ASPECT_RATIO).ok().map(|p| ((p >> 32) as f64, (p as u32) as f64)).filter(|(n, d)| *n > 0.0 && *d > 0.0);
let width = par.map_or(crop.2 as f64, |(n, d)| crop.2 as f64 * n / d).round() as u32;
let orient = rotation(t.GetUINT32(&MF_MT_VIDEO_ROTATION).unwrap_or(0));
let natural = orient.upright([width, crop.3]);
let rate = t.GetUINT64(&MF_MT_FRAME_RATE).ok().map(|r| ((r >> 32) as f64, (r as u32) as f64)).filter(|(n, d)| *n > 0.0 && *d > 0.0);
Ok(Picture {
coded,
crop,
natural: (natural[0], natural[1]),
format: if full { Format::Nv12Full } else { Format::Nv12Video },
color: ColorInfo { matrix, transfer: Transfer::Bt709 },
orient,
frame: rate.map_or(1.0 / 30.0, |(n, d)| d / n),
})
}
}
/// `MF_MT_VIDEO_ROTATION`: the picture must turn this many degrees counter-clockwise to stand
/// upright. As `Orient`, which maps upright coordinates (y down) to buffer coordinates.
fn rotation(degrees: u32) -> Orient {
match degrees {
90 => Orient([0, 1, -1, 0]),
180 => Orient([-1, 0, 0, -1]),
270 => Orient([0, -1, 1, 0]),
_ => Orient::UP,
}
}
/// The clip's length in seconds, 0 when it doesn't say (a live stream).
unsafe fn duration(reader: &IMFSourceReader) -> f64 {
// SAFETY: a presentation attribute read; the PROPVARIANT holds a plain integer.
unsafe {
match reader.GetPresentationAttribute(MF_SOURCE_READER_MEDIASOURCE.0 as u32, &MF_PD_DURATION) {
Ok(v) => v.Anonymous.Anonymous.Anonymous.uhVal as f64 / TICKS,
Err(_) => 0.0,
}
}
}
/// Moves the reader to `seconds`; it lands on the key frame at or before it.
pub(super) fn seek(reader: &IMFSourceReader, seconds: f64) -> Result<(), String> {
let mut at = PROPVARIANT::default();
// SAFETY: a VT_I8 PROPVARIANT owns nothing, so it needs no clearing.
unsafe {
(*at.Anonymous.Anonymous).vt = VT_I8;
(*at.Anonymous.Anonymous).Anonymous.hVal = (seconds.max(0.0) * TICKS) as i64;
reader.SetCurrentPosition(&GUID::zeroed(), &at).map_err(|e| format!("seek: {}", e.message()))
}
}
/// Validated media target before Media Foundation loads or touches the network/filesystem.
pub(super) enum Target {
Local { path: HSTRING, ext: String },
Remote(HSTRING),
}
impl Target {
pub(super) fn from_source(source: &MediaSource) -> Result<Self, String> {
match source {
MediaSource::File(path) => {
let (path, ext) = validate_local_file(path)?;
Ok(Self::Local { path, ext })
}
MediaSource::Url(url) if url.get(..5).is_some_and(|p| p.eq_ignore_ascii_case("file:")) => {
let path = parse_file_url(url)?;
let (path, ext) = validate_local_file(&path)?;
Ok(Self::Local { path, ext })
}
MediaSource::Url(url) if url.starts_with("http://") || url.starts_with("https://") => Ok(Self::Remote(HSTRING::from(url.as_str()))),
MediaSource::Url(url) => Err(format!("unsupported URL: {url}")),
}
}
}
/// Validates that `path` is a plain local disk file with a direct media container extension
/// before touching disk or Media Foundation. Refuses UNC shares, Win32/NT device namespaces,
/// embedded URL schemes, NTFS alternate data streams, reserved DOS device names, trailing
/// dots/spaces, and shortcut/playlist redirectors (`.url`, `.lnk`, `.asx`, `.m3u8`, etc.).
fn validate_local_file(path: &Path) -> Result<(HSTRING, String), String> {
let raw = path.to_str().ok_or_else(|| format!("unsupported local path: {}", path.display()))?;
if raw.is_empty() || raw.chars().any(char::is_control) || raw.contains(['?', '*']) {
return Err(format!("unsupported local path: {}", path.display()));
}
if has_unc_or_device_prefix(raw) || has_unc_or_device_prefix(raw.trim_start()) {
return Err(format!("local media must be a plain local file path: {}", path.display()));
}
if !has_valid_local_colons(raw) {
return Err(format!("local media must be a plain local file path: {}", path.display()));
}
for component in Path::new(raw).components() {
match component {
Component::Prefix(prefix) if matches!(prefix.kind(), Prefix::Disk(_)) => {}
Component::Prefix(_) => return Err(format!("local media must be a plain local file path: {}", path.display())),
Component::Normal(seg) => {
let Some(seg) = seg.to_str() else {
return Err(format!("unsupported local path: {}", path.display()));
};
if seg.ends_with(['.', ' ']) || is_dos_device_name(seg) {
return Err(format!("unsupported local path: {}", path.display()));
}
}
Component::RootDir | Component::CurDir | Component::ParentDir => {}
}
}
let ext = local_media_extension(Path::new(raw))
.ok_or_else(|| format!("unsupported local media file type: {}", path.display()))?;
let abs = std::path::absolute(path).map_err(|e| format!("invalid local path: {e}"))?;
let abs_str = abs.to_str().ok_or_else(|| format!("unsupported local path: {}", path.display()))?;
let mut abs_components = abs.components();
let is_plain_disk = matches!(abs_components.next(), Some(Component::Prefix(p)) if matches!(p.kind(), Prefix::Disk(_)))
&& matches!(abs_components.next(), Some(Component::RootDir));
if !is_plain_disk || has_unc_or_device_prefix(abs_str) || !has_valid_local_colons(abs_str) {
return Err(format!("local media must be a plain local file path: {}", path.display()));
}
let meta = std::fs::metadata(&abs).map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound => format!("no such file: {}", path.display()),
_ => format!("can't open {}: {e}", path.display()),
})?;
if !meta.is_file() {
return Err(format!("not a file: {}", path.display()));
}
Ok((HSTRING::from(abs.as_os_str()), ext))
}
fn has_unc_or_device_prefix(s: &str) -> bool {
let bytes = s.as_bytes();
let two_seps = bytes.len() >= 2 && matches!(bytes[0], b'\\' | b'/') && matches!(bytes[1], b'\\' | b'/');
let nt_prefix = bytes.len() >= 3
&& matches!(bytes[0], b'\\' | b'/')
&& bytes[1] == b'?'
&& bytes[2] == b'?'
&& (bytes.len() == 3 || matches!(bytes[3], b'\\' | b'/'));
two_seps || nt_prefix
}
/// Only a single leading drive letter (`X:\` or `X:/`) may contain `:`; any other `:` indicates
/// a URL scheme (`http:`, `file:`, `mms:`, `rtsp:`), a drive-relative path, or an NTFS ADS.
fn has_valid_local_colons(s: &str) -> bool {
let bytes = s.as_bytes();
let mut colons = bytes.iter().enumerate().filter_map(|(i, &b)| (b == b':').then_some(i));
let Some(first) = colons.next() else { return true };
if colons.next().is_some() {
return false;
}
first == 1 && bytes[0].is_ascii_alphabetic() && matches!(bytes.get(2), Some(b'\\' | b'/'))
}
fn is_dos_device_name(segment: &str) -> bool {
let stem = segment.split('.').next().unwrap_or(segment).trim_end_matches(' ');
matches!(
stem.to_ascii_uppercase().as_str(),
"CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" | "CLOCK$"
| "COM1" | "COM2" | "COM3" | "COM4" | "COM5" | "COM6" | "COM7" | "COM8" | "COM9"
| "LPT1" | "LPT2" | "LPT3" | "LPT4" | "LPT5" | "LPT6" | "LPT7" | "LPT8" | "LPT9"
) || matches!(
stem,
"COM¹" | "COM²" | "COM³" | "LPT¹" | "LPT²" | "LPT³"
| "com¹" | "com²" | "com³" | "lpt¹" | "lpt²" | "lpt³"
)
}
/// Direct self-contained media container extensions accepted for local files on Windows.
/// Redirectors, shortcuts, and playlists (`.url`, `.lnk`, `.asx`, `.wax`, `.wvx`, `.wmx`, `.wpl`,
/// `.m3u`, `.m3u8`, `.pls`, `.qtl`, `.ram`, `.smil`, `.smi`, `.sami`, `.nsc`, `.xspf`, `.mpd`,
/// `.ism`, `.isml`, `.f4m`, `.sdp`) are refused before touching Media Foundation.
fn local_media_extension(path: &Path) -> Option<String> {
let name = path.file_name()?.to_str()?;
let ext = name.rsplit_once('.')?.1.to_ascii_lowercase();
matches!(
ext.as_str(),
"mp4" | "m4v" | "mp4v" | "mov" | "webm" | "mkv" | "mk3d" | "avi" | "wmv"
| "mpg" | "mpeg" | "mp2v" | "m2t" | "m2ts" | "mts" | "ts" | "tts" | "vob" | "mod" | "tod"
| "3gp" | "3g2" | "3gp2" | "3gpp" | "uvu" | "ogv"
| "mp3" | "mpa" | "m4a" | "aac" | "adt" | "adts" | "ac3" | "ec3" | "amr"
| "wav" | "aif" | "aiff" | "flac" | "ogg" | "oga" | "opus" | "mka" | "weba" | "wma"
)
.then_some(ext)
}
/// Converts a local `file:///X:/...` or `file://localhost/X:/...` URL to a local Windows path,
/// refusing remote hosts, UNC escapes, queries, fragments, and malformed percent escapes.
fn parse_file_url(url: &str) -> Result<PathBuf, String> {
let rest = url
.get(..7)
.filter(|p| p.eq_ignore_ascii_case("file://"))
.map(|_| &url[7..])
.ok_or_else(|| format!("unsupported file URL: {url}"))?;
let after_host = if let Some(s) = rest.strip_prefix('/') {
s
} else if rest.get(..10).is_some_and(|p| p.eq_ignore_ascii_case("localhost/")) {
&rest[10..]
} else {
return Err(format!("remote file URL isn't supported: {url}"));
};
if after_host.starts_with(['/', '\\']) || after_host.contains(['?', '#']) {
return Err(format!("unsupported file URL: {url}"));
}
let decoded = percent_decode(after_host).ok_or_else(|| format!("invalid file URL encoding: {url}"))?;
if decoded.starts_with(['/', '\\']) {
return Err(format!("remote file URL isn't supported: {url}"));
}
Ok(PathBuf::from(decoded.replace('/', "\\")))
}
fn percent_decode(input: &str) -> Option<String> {
let bytes = input.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
let hi = (*bytes.get(i + 1)? as char).to_digit(16)? as u8;
let lo = (*bytes.get(i + 2)? as char).to_digit(16)? as u8;
out.push((hi << 4) | lo);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
/// One read: the stream it came from, its flags, its time in seconds and the sample, if any.
pub(super) struct Read {
pub stream: u32,
pub flags: i32,
pub time: f64,
pub sample: Option<IMFSample>,
}
pub(super) fn read(reader: &IMFSourceReader, stream: u32) -> Result<Read, String> {
let (mut index, mut flags, mut time, mut sample) = (0u32, 0u32, 0i64, None);
// SAFETY: a blocking read into locals.
unsafe { reader.ReadSample(stream, 0, Some(&mut index), Some(&mut flags), Some(&mut time), Some(&mut sample)) }
.map_err(|e| format!("decode: {}", e.message()))?;
Ok(Read { stream: index, flags: flags as i32, time: time as f64 / TICKS, sample })
}
/// A system-memory NV12 sample as packed planes of `picture.crop`'s size.
pub(super) fn nv12_bytes(sample: &IMFSample, picture: &Picture) -> Result<ByteFrame, String> {
// SAFETY: the buffer is locked for the copy and unlocked after it.
unsafe {
let buffer = sample.ConvertToContiguousBuffer().map_err(|e| e.message())?;
let (mut base, mut pitch, mut len) = (std::ptr::null_mut(), 0i32, 0u32);
let two_d = buffer.cast::<IMF2DBuffer2>().ok();
let locked = match &two_d {
Some(b) => {
let mut start = std::ptr::null_mut();
b.Lock2DSize(MF2DBuffer_LockFlags_Read, &mut base, &mut pitch, &mut start, &mut len).is_ok()
}
None => false,
};
if !locked {
buffer.Lock(&mut base, None, Some(&mut len)).map_err(|e| e.message())?;
pitch = picture.coded.0 as i32;
}
let pitch = pitch.unsigned_abs() as usize;
let (x, y, w, h) = picture.crop;
let (w, h, x, y) = (w as usize, h as usize, x as usize, y as usize);
// The luma plane's height from the buffer itself (NV12 is 1.5 planes of luma): the media
// type's coded height can differ from what the decoder wrote (1088 against 1080 rows), and
// reading chroma from there leaves the top rows without colour, a green band.
let rows = match len as usize * 2 / (3 * pitch.max(1)) {
0 => picture.coded.1 as usize,
rows => rows.max(y + h),
};
let mut luma = Vec::with_capacity(w * h);
let mut chroma = Vec::with_capacity(w * h / 2);
for row in y..y + h {
luma.extend_from_slice(std::slice::from_raw_parts(base.add(row * pitch + x), w));
}
let uv = base.add(rows * pitch);
for row in y / 2..(y + h) / 2 {
chroma.extend_from_slice(std::slice::from_raw_parts(uv.add(row * pitch + x), w));
}
match &two_d {
Some(b) if locked => { b.Unlock2D().ok(); }
_ => { buffer.Unlock().ok(); }
}
Ok(ByteFrame { width: w as u32, height: h as u32, format: picture.format, color: picture.color, planes: [luma, chroma] })
}
}
@@ -0,0 +1,601 @@
//! Windows: Media Foundation. Each clip that plays gets a decoder thread (`decoder`) that opens
//! it with the source reader, decodes on the GPU where the adapter has a hardware decoder (else
//! on the CPU) and copies each picture into a shared NV12 texture Rune samples in place
//! (`gpu`). Sound goes to the default output through WASAPI (`audio`), following the clock.
//!
//! The UI thread's part, in each frame that draws the clip: fold the handle's intent and the
//! decoder's news into the player's phase (`machine`), and swap in the picture for the refresh
//! the frame presents at (`vsync`). It then asks for its next frame when the next picture is
//! due, not every refresh. A clip nobody draws isn't pulled, so its decoder fills its queue and
//! sleeps; a muted one picks up where it left off when drawn again, and after a few seconds
//! undrawn the decoder lets go of everything but the picture on screen.
//!
//! Nothing here runs until a clip opens: Media Foundation, D3D11 and the audio stack load then.
mod ahead;
mod audio;
mod decoder;
mod gpu;
mod layer;
mod machine;
mod mf;
mod still;
mod vsync;
use super::*;
use decoder::{Decoded, Facts, Job, News, Pic, Pipe};
use machine::{Effect, Event, Phase};
use std::time::Duration;
/// A muted clip undrawn this long picks up at its picture when drawn again, rather than
/// skipping what played while nobody watched.
const RESUME_GAP: Duration = Duration::from_millis(250);
#[derive(Default)]
pub(crate) struct Native {
phase: Phase,
pipe: Option<Arc<Pipe>>,
/// Seeks issued; the decoder's pictures carry the one they belong to.
seeks: rune_core::machine::Seq,
clock: Arc<audio::Clock>,
facts: Option<Facts>,
/// The picture on the surface: its unwrapped time.
shown: Option<f64>,
/// When a frame last drew the clip.
pulled: Option<Instant>,
/// The intent last folded into the phase.
playing: bool,
rate: f32,
/// When the frame that draws the clip next should come.
due: Option<Instant>,
/// Headless pictures.
still: Option<still::Still>,
/// When the decoder was last started, until its first picture reached the surface
/// (`RUNE_VIDEO_LOG`).
opened: Option<Instant>,
/// The clip's layer shows its pictures (`layer`): frames don't pull them one by one.
layered: bool,
/// The layer presented pictures since the surface last got one: the surface is behind.
behind: bool,
}
/// The window's side of a clip's layer (`layer`): what the decoder has made of its ask.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LayerStatus {
/// The layer's DirectComposition surface handle, once made.
pub handle: Option<usize>,
/// A picture of the current seek is on the layer at the asked size, and the clock runs.
pub showing: bool,
/// The clock runs: only then does the layer take the pictures.
pub running: bool,
/// The clip can't have a layer; the window draws it.
pub refused: bool,
}
/// The window asks for the clip's layer at `ask` device pixels (None: it draws the pictures),
/// and hears what the decoder has done.
pub(crate) use gpu::release_removed_device;
pub(crate) fn layer(shared: &Arc<Shared>, ask: Option<(u32, u32)>) -> LayerStatus {
let mut native = shared.native.lock().unwrap();
let running = matches!(native.phase, Phase::Playing { .. });
let generation = native.seeks.current().0;
let Some(pipe) = native.pipe.clone() else {
native.layered = false;
return LayerStatus { running, ..LayerStatus::default() };
};
let mut s = pipe.lock();
let changed = s.layer != ask;
s.layer = ask;
let showing = running && ask.is_some_and(|size| s.layer_shown == Some((size, generation)));
let status = LayerStatus { handle: s.layer_handle, showing, running, refused: s.layer_refused };
drop(s);
if changed {
pipe.poke();
}
native.layered = showing;
native.behind |= showing;
status
}
// SAFETY: the reader in `still` stays on the headless thread that made it, under the Shared mutex.
#[allow(unsafe_code)]
unsafe impl Send for Native {}
impl Drop for Native {
/// The clip's last handle and element went: its decoder stops now, not when it would park.
fn drop(&mut self) {
self.clock.set(None);
if let Some(pipe) = self.pipe.take() {
pipe.lock().stop = true;
pipe.poke();
}
}
}
pub(super) fn created(shared: &Arc<Shared>) {
// Media Foundation's network source sends no headers of ours.
if !shared.headers.is_empty() {
shared.ctl.lock().unwrap().fail("request headers aren't supported for clips on Windows yet".into());
}
}
pub(super) fn enable() {}
pub(super) fn probe(native: &mut Native, source: &MediaSource, _: &[(String, String)], kind: Kind) -> Result<Meta, String> {
let (still, meta) = still::open(source, kind)?;
native.still = still;
Ok(meta)
}
pub(super) fn decode(native: &mut Native, source: &MediaSource, headers: &[(String, String)], at: f64) -> Result<ByteFrame, String> {
if native.still.is_none() {
probe(native, source, headers, Kind::Video)?;
}
native.still.as_mut().ok_or("no video track")?.frame(at)
}
/// A handle edit: fold it in now, so pausing or muting a clip nobody draws goes quiet at once.
pub(super) fn apply(shared: &Arc<Shared>) {
if !playback_enabled() {
return;
}
if shared.kind == Kind::Audio {
return drive(shared);
}
// Being pulled further up this stack: that pull folds it in.
let Ok(mut native) = shared.native.try_lock() else { return };
let mut c = shared.ctl.lock().unwrap();
let target = vsync::snap(rune_core::time::now());
// Video opens when a frame draws it.
native.reconcile(shared, &mut c, target, false);
drop(c);
drop(native);
shared.settle(false);
}
/// Audio, from any thread (an edit, or its decoder's news): fold everything in. Sound has no
/// pictures to land, so a clip that opened plays from where it was asked to, and one whose
/// clock passed its end ends.
pub(super) fn drive(shared: &Arc<Shared>) {
let Ok(mut native) = shared.native.try_lock() else { return };
let mut c = shared.ctl.lock().unwrap();
let now = rune_core::time::now();
native.reconcile(shared, &mut c, now, true);
match native.phase {
Phase::Buffering { at, .. } => {
native.shown = Some(at);
native.event(shared, &c, Event::Shown { pts: at, target: now, lead: 0.0, rate: f64::from(c.rate) });
}
Phase::Playing { clock } => {
let generation = native.seeks.current().0;
let ended = native.pipe.as_ref().is_some_and(|p| p.lock().ended == Some(generation));
let duration = c.duration.unwrap_or(0.0);
let pos = clock.position(now);
if ended && duration > 0.0 && pos >= (clock.pos / duration).floor() * duration + duration {
native.end(shared, &mut c, duration, duration);
}
}
_ => {}
}
drop(c);
drop(native);
shared.settle(false);
}
pub(super) fn preload(shared: &Arc<Shared>) {
let mut native = shared.native.lock().unwrap();
let c = shared.ctl.lock().unwrap();
if !c.failed() && native.pipe.is_none() {
let play = c.playing();
native.event(shared, &c, Event::Open { play });
}
}
/// The window takes the pictures back from the clip's layer: the picture for now goes on the
/// surface at once, so the frame that draws it isn't one from before the layer showed.
pub(crate) fn unlayer(shared: &Arc<Shared>, surface: &NativeSurface) {
let mut native = shared.native.lock().unwrap();
let mut c = shared.ctl.lock().unwrap();
native.layered = false;
let lead = vsync::period().as_secs_f64() / 2.0;
native.show(shared, &mut c, surface, vsync::snap(rune_core::time::now()), lead);
}
/// Audio, and video on its layer: where the clock has it now. The clock runs only while the sound
/// does (or the layer shows the pictures), so it's always the one to read.
pub(super) fn live_time(shared: &Shared, _: bool) -> Option<f64> {
let native = shared.native.try_lock().ok()?;
if shared.kind != Kind::Audio && !native.layered {
return None;
}
let clock = native.clock.get()?;
let duration = native.facts.map(|f| f.meta.duration).filter(|d| *d > 0.0)?;
Some(clock.position(rune_core::time::now()).rem_euclid(duration))
}
/// When the frame that draws the clip next should come; None while nothing is due.
pub(super) fn due(shared: &Shared) -> Option<Instant> {
shared.native.try_lock().ok()?.due
}
pub(super) fn pull(shared: &Arc<Shared>, surface: &NativeSurface, target: Instant) -> bool {
let now = rune_core::time::now();
let target = vsync::snap(target.max(now));
let mut native = shared.native.lock().unwrap();
let mut c = shared.ctl.lock().unwrap();
let gap = native.pulled.map(|p| now.saturating_duration_since(p));
native.pulled = Some(now);
if let Some(pipe) = &native.pipe {
pipe.lock().touched = Some(now);
}
native.reconcile(shared, &mut c, target, true);
if c.failed() {
native.due = None;
return false;
}
let lead = vsync::period().as_secs_f64() / 2.0;
// A clip on its layer played on between pulls, as the window saw it.
if let (Phase::Playing { .. }, Some(gap), Some(at)) = (native.phase, gap, native.shown)
&& gap > RESUME_GAP
&& !native.sounding(&c)
&& !native.layered
{
native.event(shared, &c, Event::Resumed { target, at, lead });
}
let shown = native.shown;
native.show(shared, &mut c, surface, target, lead);
let (active, due) = native.next(&c, now);
native.due = due;
let cost = now.elapsed().as_nanos();
if decoder::logging_frames() {
let new = native.shown.filter(|s| shown != Some(*s)).map_or(String::new(), |s| format!(" picture {s:.4}"));
let at = |t: Instant| t.saturating_duration_since(now).as_micros();
decoder::log!("pull {cost} ns, target +{} us{new}, due +{:?} us", at(target), due.map(at));
}
active
}
impl Native {
/// Steps the phase and carries out what it asks.
fn event(&mut self, shared: &Arc<Shared>, c: &Control, event: Event) {
let before = self.phase;
let effects = machine::step(&mut self.phase, event);
if decoder::logging() && std::mem::discriminant(&before) != std::mem::discriminant(&self.phase) {
decoder::log!("{:?} -> {:?}", before, self.phase);
}
for effect in effects {
match effect {
Effect::Open { at } => self.open(shared, c, at),
Effect::Seek { to } => {
let generation = self.seeks.next().0;
if let Some(pipe) = &self.pipe {
pipe.lock().seek = Some((to, generation));
pipe.poke();
}
self.shown = None;
}
Effect::Clock(anchor) => self.clock.set(anchor),
}
}
}
fn open(&mut self, shared: &Arc<Shared>, c: &Control, at: f64) {
let weak = Arc::downgrade(shared);
let job = Job {
source: shared.source.clone(),
kind: shared.kind,
// Picture times count on through loops; the clip starts at its own time.
start: c.duration.filter(|d| *d > 0.0).map_or(at, |d| at.rem_euclid(d)),
generation: self.seeks.current().0,
looping: c.looping,
sound: (!c.muted).then_some(c.volume),
notify: Box::new(move || {
let Some(shared) = weak.upgrade() else { return };
match shared.kind {
Kind::Video => shared.wake_windows(),
Kind::Audio => drive(&shared),
}
}),
clock: self.clock.clone(),
started: rune_core::time::now(),
};
self.opened = Some(job.started);
self.pipe = Some(decoder::start(job));
}
/// Sound is playing: the clip's clock runs on whether or not it's drawn.
fn sounding(&self, c: &Control) -> bool {
!c.muted && self.facts.is_some_and(|f| f.sound.is_some())
}
/// Folds the decoder's news and the handle's intent into the phase.
fn reconcile(&mut self, shared: &Arc<Shared>, c: &mut Control, target: Instant, may_open: bool) {
let news = self.pipe.as_ref().map(|p| std::mem::take(&mut p.lock().news)).unwrap_or_default();
for news in news {
match news {
News::Opened(facts) => {
self.facts = Some(facts);
if !c.opened() {
c.open(Ok(facts.meta));
}
self.event(shared, c, Event::Opened);
}
News::Failed(e) => {
if decoder::logging() {
decoder::log!("failed: {e}");
}
c.fail(e);
self.pipe = None;
self.event(shared, c, Event::Failed);
}
News::Parked => {
self.pipe = None;
let at = self.shown.unwrap_or(0.0);
self.event(shared, c, Event::Released { at });
}
}
}
if c.failed() {
self.pipe = None;
self.event(shared, c, Event::Failed);
return;
}
if let (Phase::Playing { clock }, Some(heard)) = (self.phase, self.clock.get())
&& heard != clock
{
self.event(shared, c, Event::Synced { clock: heard });
}
let lead = vsync::period().as_secs_f64() / 2.0;
if let Some(to) = c.seek.take() {
self.event(shared, c, Event::Seek { to });
}
if c.playing() != self.playing {
self.playing = c.playing();
let held = self.held_at();
let event = if self.playing {
Event::Play { target, lead, rate: f64::from(c.rate) }
} else {
Event::Pause { at: held.or(self.shown).unwrap_or_else(|| self.at()) }
};
self.event(shared, c, event);
// Paused while the surface is behind: the time is where the pause holds, and the
// surface gets that picture when the window draws the clip again (`hold`).
if let (false, Some(at)) = (self.playing, held) {
c.time = clip_time(c, at);
}
}
if c.rate != self.rate {
self.rate = c.rate;
self.event(shared, c, Event::Rate { target, rate: f64::from(c.rate) });
}
// Until the clip opens, whether it has sound is unknown: the decoder keeps its ask.
let sound = self.sounding(c).then_some(c.volume);
if let Some(pipe) = self.pipe.as_ref().filter(|_| self.facts.is_some()) {
let mut inbox = pipe.lock();
if inbox.looping != c.looping || inbox.sound != sound {
inbox.looping = c.looping;
inbox.sound = sound;
drop(inbox);
pipe.poke();
}
}
// A clip with no picture yet, or one that plays, opens; a paused one keeps its picture.
if let Phase::Idle { .. } = self.phase
&& may_open
&& (c.playing() || (self.shown.is_none() && shared.kind == Kind::Video))
{
self.event(shared, c, Event::Open { play: c.playing() });
}
}
/// The picture the clip's layer shows, while it shows the pictures.
fn on_layer(&self) -> Option<f64> {
let pipe = self.pipe.as_ref().filter(|_| self.layered)?;
let generation = self.seeks.current().0;
pipe.lock().layer_presented.filter(|(_, g)| *g == generation).map(|(pts, _)| pts)
}
/// Where a pause holds while the surface is behind: the picture the layer shows, or the
/// clock when the window let go of the layer without drawing the clip again.
fn held_at(&self) -> Option<f64> {
self.on_layer().or(match self.phase {
Phase::Playing { clock } if self.behind => Some(clock.position(rune_core::time::now())),
_ => None,
})
}
/// The phase's time, for a pause before any picture showed.
fn at(&self) -> f64 {
match self.phase {
Phase::Idle { at } | Phase::Opening { at, .. } | Phase::Buffering { at, .. } | Phase::Paused { at } | Phase::Ended { at } => at,
Phase::Playing { clock } => clock.pos,
Phase::Failed => 0.0,
}
}
/// Puts the picture for `target` on the surface and notes where playback stands.
fn show(&mut self, shared: &Arc<Shared>, c: &mut Control, surface: &NativeSurface, target: Instant, lead: f64) {
let Some(pipe) = self.pipe.clone() else { return };
let generation = self.seeks.current().0;
// The layer shows the pictures: the surface keeps the one it has, so the window has
// nothing to draw, and playback stands at the newest picture presented.
if self.layered {
let (newest, ended) = {
let inbox = pipe.lock();
(inbox.frames.back().filter(|f| f.generation == generation).map(|f| f.pts), inbox.ended == Some(generation))
};
if let Some(pts) = newest {
self.shown = Some(pts);
}
if let (true, Phase::Playing { clock }, Some(shown)) = (ended, self.phase, self.shown) {
let frame = self.facts.map_or(1.0 / 30.0, |f| f.meta.frame);
let duration = c.duration.unwrap_or(0.0);
let end = if duration > 0.0 { (shown / duration).floor() * duration + duration } else { shown + frame };
if clock.position(target) >= end.max(shown + frame) {
self.end(shared, c, shown, duration);
}
}
return;
}
if let (true, Phase::Paused { at } | Phase::Ended { at }) = (self.behind, self.phase) {
return self.hold(shared, c, surface, &pipe, generation, at);
}
let picked = {
let mut inbox = pipe.lock();
while inbox.frames.front().is_some_and(|f| f.generation != generation) {
inbox.frames.pop_front();
}
match self.phase {
Phase::Buffering { .. } => inbox.frames.pop_front(),
Phase::Paused { .. } if self.shown.is_none() => inbox.frames.pop_front(),
Phase::Playing { clock } => {
let pos = clock.position(target);
let mut newest = None;
while inbox.frames.front().is_some_and(|f| f.pts <= pos) {
newest = inbox.frames.pop_front();
}
newest
}
_ => None,
}
};
let Some(frame) = picked else {
self.check_end(shared, c, &pipe, generation, target);
return;
};
pipe.poke();
let pts = frame.pts;
self.put(c, surface, frame);
if let Phase::Buffering { .. } = self.phase {
self.event(shared, c, Event::Shown { pts, target, lead, rate: f64::from(c.rate) });
}
}
/// Playing with nothing due: the end, or a decoder that fell behind.
/// Puts the held picture on a surface the layer got ahead of: the newest at or before `at`,
/// or the next one when the pause came while the decoder presented it. Gone from the queue,
/// a paused clip seeks to it.
fn hold(&mut self, shared: &Arc<Shared>, c: &mut Control, surface: &NativeSurface, pipe: &Pipe, generation: u32, at: f64) {
self.behind = false;
let frame = self.facts.map_or(1.0 / 30.0, |f| f.meta.frame);
let held = {
let mut inbox = pipe.lock();
while inbox.frames.front().is_some_and(|f| f.generation != generation) {
inbox.frames.pop_front();
}
let mut held = None;
while inbox.frames.front().is_some_and(|f| f.pts <= at) {
held = inbox.frames.pop_front();
}
if held.is_none() && inbox.frames.front().is_some_and(|f| f.pts <= at + frame * 1.5) {
held = inbox.frames.pop_front();
}
held.filter(|f| f.pts >= at - frame * 1.5)
};
pipe.poke();
match (held, self.phase) {
(Some(held), _) => {
let pts = held.pts;
self.put(c, surface, held);
if let Phase::Paused { at } = self.phase
&& at != pts
{
self.event(shared, c, Event::Pause { at: pts });
}
}
(None, Phase::Paused { at }) => self.event(shared, c, Event::Seek { to: clip_time(c, at) }),
_ => {}
}
}
fn check_end(&mut self, shared: &Arc<Shared>, c: &mut Control, pipe: &Pipe, generation: u32, target: Instant) {
let Phase::Playing { clock } = self.phase else { return };
let (empty, ended) = {
let inbox = pipe.lock();
(inbox.frames.is_empty(), inbox.ended == Some(generation))
};
if !empty {
return;
}
let pos = clock.position(target);
let frame = self.facts.map_or(1.0 / 30.0, |f| f.meta.frame);
let duration = c.duration.unwrap_or(0.0);
let shown = self.shown.unwrap_or(clock.pos);
if ended {
let end = if duration > 0.0 { (shown / duration).floor() * duration + duration } else { shown + frame };
if pos >= end.max(shown + frame) {
self.end(shared, c, shown, duration);
}
} else if pos > shown + frame * 2.0 + 0.1 {
self.event(shared, c, Event::Stalled { at: shown + frame });
}
}
/// The last picture showed (or the last sound played) and the decoder didn't loop. Looping
/// turned on since starts the clip again from zero.
fn end(&mut self, shared: &Arc<Shared>, c: &mut Control, at: f64, duration: f64) {
if c.observe(duration, true) {
c.seek = Some(0.0);
return;
}
self.event(shared, c, Event::Ended { at });
self.playing = c.playing();
}
/// Puts `frame` on the surface.
fn put(&mut self, c: &mut Control, surface: &NativeSurface, frame: Decoded) {
let Some(facts) = self.facts else { return };
let Some(picture) = facts.picture else { return };
let id = c.next_frame_id();
match frame.picture {
Pic::Gpu(planes, value) => surface.push_decoded(planes, value, id, picture.format, picture.color, picture.orient),
Pic::Cpu(bytes) => {
if let Err(e) = surface.push_bytes_oriented(bytes, id, picture.orient) {
c.fail(e);
return;
}
}
}
let duration = facts.meta.duration;
if duration > 0.0 && self.shown.is_some_and(|s| (s / duration).floor() < (frame.pts / duration).floor()) {
// A loop is news for anything showing progress from zero.
c.generation += 1;
}
self.shown = Some(frame.pts);
self.behind = false;
c.time = clip_time(c, frame.pts);
if let Some(opened) = self.opened.take() {
rune_core::marks::mark("video.first_frame.shown");
if decoder::logging() {
decoder::log!("first picture on the surface at {} us", decoder::us(opened));
}
}
}
/// Whether frames should keep coming, and when the next is due.
fn next(&self, c: &Control, now: Instant) -> (bool, Option<Instant>) {
let Phase::Playing { clock } = self.phase else { return (false, None) };
let frame = self.facts.map_or(1.0 / 30.0, |f| f.meta.frame);
let shown = self.shown.unwrap_or(clock.pos);
// The layer shows the pictures: a frame is due only to hear that the clip ended.
if self.layered {
let generation = self.seeks.current().0;
let ended = self.pipe.as_ref().is_some_and(|p| p.lock().ended == Some(generation));
return if ended { (true, Some(clock.when(shown + frame).max(now))) } else { (false, None) };
}
let next = self.pipe.as_ref().and_then(|p| p.lock().frames.front().map(|f| f.pts));
let pos = next.unwrap_or(shown + frame);
let _ = c;
(true, Some(clock.when(pos).max(now)))
}
}
/// Unwrapped seconds as the clip's own time.
fn clip_time(c: &Control, pts: f64) -> f64 {
match c.duration.filter(|d| *d > 0.0) {
Some(duration) => pts.rem_euclid(duration).min(duration),
None => pts,
}
}
@@ -0,0 +1,71 @@
//! Headless runs: a clip's facts and its picture at a virtual time, decoded synchronously on
//! the CPU, so `--snap` and `--frames` are the same every run. No player, no sound.
use super::super::{Kind, MediaSource, Meta};
use super::mf::{self, Decode, Picture};
use crate::native_surface::ByteFrame;
use windows::Win32::Media::MediaFoundation::{IMFSourceReader, MF_SOURCE_READERF_ENDOFSTREAM};
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx};
pub(crate) struct Still {
reader: IMFSourceReader,
video: u32,
picture: Picture,
/// The last picture read at or before the time asked, and the one read after it: a later
/// time reads on from them rather than seeking.
current: Option<(f64, ByteFrame)>,
next: Option<(f64, ByteFrame)>,
}
/// Opens `source` and reads its facts; for video, a reader for its pictures too.
#[allow(unsafe_code)]
pub(super) fn open(source: &MediaSource, kind: Kind) -> Result<(Option<Still>, Meta), String> {
let target = mf::Target::from_source(source)?;
// SAFETY: COM on this thread for the reader; left initialised, as the thread may open more.
unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.ok().ok();
let lib = mf::library()?;
let opened = mf::open(lib, &lib.resolve(&target)?, kind, Decode::Cpu, false)?;
let meta = Meta { duration: opened.duration, size: opened.picture.map(|p| p.natural), frame: opened.picture.map_or(1.0 / 30.0, |p| p.frame), sound: opened.has_sound };
let still = match (opened.video, opened.picture) {
(Some(video), Some(picture)) => Some(Still { reader: opened.reader, video, picture, current: None, next: None }),
_ => None,
};
Ok((still, meta))
}
impl Still {
/// The picture showing at clip second `at`.
pub(super) fn frame(&mut self, at: f64) -> Result<ByteFrame, String> {
let shows = |t: f64| t <= at + self.picture.frame * 0.5;
let reads_on = self.current.as_ref().is_some_and(|(t, _)| shows(*t) && at - t < 1.0);
if !reads_on {
mf::seek(&self.reader, at)?;
(self.current, self.next) = (None, None);
}
if let Some((t, _)) = &self.next {
if !shows(*t) {
return self.current.as_ref().map(|(_, f)| copy(f)).ok_or_else(|| "no picture at that time".into());
}
self.current = self.next.take();
}
loop {
let read = mf::read(&self.reader, self.video)?;
if let Some(sample) = &read.sample {
let frame = mf::nv12_bytes(sample, &self.picture)?;
if !shows(read.time) && self.current.is_some() {
self.next = Some((read.time, frame));
break;
}
self.current = Some((read.time, frame));
}
if read.flags & MF_SOURCE_READERF_ENDOFSTREAM.0 != 0 {
break;
}
}
self.current.as_ref().map(|(_, f)| copy(f)).ok_or_else(|| "no picture at that time".into())
}
}
fn copy(f: &ByteFrame) -> ByteFrame {
ByteFrame { width: f.width, height: f.height, format: f.format, color: f.color, planes: f.planes.clone() }
}
@@ -0,0 +1,82 @@
//! The display's refresh grid, from DWM: when presentations happen. A video picks its picture
//! for the refresh a frame will show at, rather than the moment the frame was built, so the
//! wobble in when frames are built never shows a picture twice or skips one.
#![allow(unsafe_code)]
use rune_core::time::Instant;
use std::sync::Mutex;
use std::time::Duration;
use windows_sys::Win32::Graphics::Dwm::DWM_TIMING_INFO;
use windows_sys::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency};
/// How long a reading of the grid is trusted before it's read again.
const FRESH: Duration = Duration::from_secs(1);
/// A frame built now presents at the first refresh at least this far ahead.
const BUILD: Duration = Duration::from_millis(2);
const DEFAULT_PERIOD: Duration = Duration::from_nanos(16_666_667);
type GetTiming = unsafe extern "system" fn(isize, *mut DWM_TIMING_INFO) -> i32;
#[derive(Clone, Copy)]
struct Grid {
read: Instant,
vblank: Instant,
period: Duration,
}
static GRID: Mutex<Option<Grid>> = Mutex::new(None);
fn grid() -> Option<Grid> {
let now = rune_core::time::now();
let mut slot = GRID.lock().unwrap();
if let Some(g) = *slot
&& now.saturating_duration_since(g.read) < FRESH
{
return Some(g);
}
let fresh = read(now);
*slot = fresh.or(*slot);
*slot
}
fn read(now: Instant) -> Option<Grid> {
static TIMING: std::sync::OnceLock<Option<GetTiming>> = std::sync::OnceLock::new();
// SAFETY: dwmapi's documented entry point at its documented signature.
let get = (*TIMING.get_or_init(|| unsafe { super::mf::symbol(super::mf::system_library("dwmapi.dll")?, c"DwmGetCompositionTimingInfo") }))?;
// SAFETY: `DWM_TIMING_INFO` is a plain Win32 C struct where all-zero bytes are valid.
let mut info: DWM_TIMING_INFO = unsafe { std::mem::zeroed() };
info.cbSize = size_of::<DWM_TIMING_INFO>() as u32;
let (mut qpc, mut frequency) = (0i64, 0i64);
// SAFETY: plain reads into locals.
unsafe {
if get(0, &mut info) < 0 {
return None;
}
QueryPerformanceCounter(&mut qpc);
QueryPerformanceFrequency(&mut frequency);
}
if frequency <= 0 || info.qpcRefreshPeriod == 0 {
return None;
}
let ticks = |t: i64| Duration::from_nanos((t as i128 * 1_000_000_000 / frequency as i128) as u64);
let period = ticks(info.qpcRefreshPeriod as i64);
let ago = qpc - info.qpcVBlank as i64;
let vblank = if ago >= 0 { now - ticks(ago) } else { now + ticks(-ago) };
(Duration::from_micros(2_000)..Duration::from_millis(100)).contains(&period).then_some(Grid { read: now, vblank, period })
}
/// The display's refresh period.
pub(super) fn period() -> Duration {
grid().map_or(DEFAULT_PERIOD, |g| g.period)
}
/// The refresh a frame built at `t` presents at: the first at least `BUILD` after it.
pub(super) fn snap(t: Instant) -> Instant {
let Some(g) = grid() else { return t };
let t = t + BUILD;
let since = t.saturating_duration_since(g.vblank).as_nanos();
let period = g.period.as_nanos().max(1);
let k = since.div_ceil(period);
g.vblank + Duration::from_nanos((k * period) as u64)
}