feat(render,app): footage decode lands (M12 P0) + UI density pass

engine:
- oakrender eval footage hook decodes via oakcodec (JobSpec::Footage
  carries filename/stream); ticket/ffi/manager wiring, real-media
  decode test with programmatically generated MPEG-2
- oakrender bridge/codec.rs + node.rs: direct oakcodec/oaknode calls;
  the crate's dlsym module is gone (project_deep_copy/sync_copy remain
  documented always-fail stubs — never implemented in oaknode)
- oakaudio waveform/decoder path adjustments for the decode hook

app (gpui + gpui_widgets):
- menu bar scrubbing: hovering another top-level title while a menu is
  open switches to it; popup width is content-aware (CJK-aware) instead
  of fixed 160px
- density pass: window rem 16 -> 14px, menu rows 26 -> 22px, dock tabs
  32 -> 26px, viewer transport tightened
- open/import/save-as use the native platform file dialogs
  (prompt_for_paths / prompt_for_new_path; multi-select import);
  MockEngine records imported footage for tests
- project explorer Tree/Icons toggle is localized (explorer.tree /
  explorer.icons widget keys)
This commit is contained in:
2026-08-13 18:16:10 +08:00
parent 3625e37081
commit 5afa95c80e
227 changed files with 5851 additions and 65946 deletions
+5 -1
View File
@@ -150,6 +150,8 @@ impl PreviewAutoCacher {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
},
Box::new(|_| {}),
);
@@ -185,6 +187,8 @@ impl PreviewAutoCacher {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
},
done,
);
@@ -303,7 +307,7 @@ mod tests {
p.height = 4;
f.set_video_params(p);
f.allocate();
Ok(Texture::wrap_frame(f))
Ok(crate::ticket::TicketPayload::Video(Texture::wrap_frame(f)))
})
}
+317
View File
@@ -0,0 +1,317 @@
// Oak Video Editor - Non-Linear Video Editor
// Copyright (C) 2026 Oak Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! oakcodec C ABI bridge: direct Rust calls into the `oakcodec` crate
//! (M12 P0: the footage decode path).
//!
//! Single-lib unification (see `docs/zh/plans/riir/single-lib.md`): every
//! call below is a compile-time Rust call into `oakcodec`'s `ffi` — the
//! `#[no_mangle]` exports stay in the dylib for the external C ABI;
//! internal callers bypass them. Handles cross as the shared
//! [`crate::handle::CHandle`] (`oakcore_rs::handle::CHandle`). There is no
//! runtime ABI probe: the crate is a path dependency, so the functions are
//! always present; failure semantics are oakcodec's own (empty handle /
//! negative error code).
use std::ffi::{c_char, c_int};
use crate::error::{Error, Result};
use crate::handle::CHandle;
/// `oakcodec_video_stream_info` — POD probe output (one video stream).
///
/// Layout-identical to `oakcodec::decoder::OakCodecVideoStreamInfo` (both
/// `#[repr(C)]`); kept as a local mirror so the bridge API is self-contained.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct VideoStreamInfo {
/// Stream index.
pub stream_index: c_int,
/// Width in pixels.
pub width: c_int,
/// Height in pixels.
pub height: c_int,
/// Frame-rate numerator.
pub frame_rate_num: c_int,
/// Frame-rate denominator.
pub frame_rate_den: c_int,
/// Stream length in time-base units.
pub duration_ts: i64,
/// Time-base numerator (seconds per time-base unit).
pub time_base_num: c_int,
/// Time-base denominator.
pub time_base_den: c_int,
/// Native delivery `OakPixelFormat`.
pub format: c_int,
/// Plane channel count.
pub channel_count: c_int,
/// ISO/IEC 23001-8 color-primaries code point (0 = unknown).
pub color_primaries: c_int,
/// ISO/IEC 23001-8 color-transfer code point (0 = unknown).
pub color_trc: c_int,
/// 1 when the stream is interlaced.
pub interlaced: c_int,
}
/// Decoder handle (owned session).
pub type DecoderHandle = CHandle;
/// Probe handle (owned).
pub type ProbeHandle = CHandle;
/// Decoded frame handle (owned).
pub type CodecFrameHandle = CHandle;
/// `oakcodec_decoder_probe(filename)` — owned probe handle; null on
/// failure.
pub fn decoder_probe(filename: &str) -> ProbeHandle {
let c = std::ffi::CString::new(filename).unwrap_or_default();
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::decoder::oakcodec_decoder_probe(c.as_ptr()) }
}
/// `oakcodec_decoder_probe_video_stream_count(probe)`; 0 on an empty
/// probe.
pub fn probe_video_stream_count(probe: ProbeHandle) -> c_int {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::decoder::oakcodec_decoder_probe_video_stream_count(probe) }
}
/// `oakcodec_decoder_probe_get_video_stream(probe, index, out)`.
pub fn probe_get_video_stream(probe: ProbeHandle, index: c_int, out: &mut VideoStreamInfo) -> Result<()> {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI). `VideoStreamInfo`
// is layout-identical to oakcodec's `OakCodecVideoStreamInfo`, so the
// pointer crosses via a cast.
let rc = unsafe {
oakcodec::ffi::decoder::oakcodec_decoder_probe_get_video_stream(
probe,
index,
out as *mut VideoStreamInfo as *mut oakcodec::decoder::OakCodecVideoStreamInfo,
)
};
if rc == 0 {
Ok(())
} else {
Err(Error::Failed(format!("probe_get_video_stream rc={rc}")))
}
}
/// `oakcodec_decoder_init()` — owned decoder session; null on failure.
pub fn decoder_init() -> DecoderHandle {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::decoder::oakcodec_decoder_init() }
}
/// `oakcodec_decoder_free(decoder: *mut CHandle)` — NULL no-op.
pub fn decoder_free(decoder: &mut DecoderHandle) {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::decoder::oakcodec_decoder_free(decoder) }
}
/// `oakcodec_decoder_open(decoder, filename, stream_index)`.
pub fn decoder_open(decoder: DecoderHandle, filename: &str, stream_index: c_int) -> Result<()> {
let c = std::ffi::CString::new(filename).unwrap_or_default();
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
let rc = unsafe { oakcodec::ffi::decoder::oakcodec_decoder_open(decoder, c.as_ptr(), stream_index) };
if rc == 0 {
Ok(())
} else {
Err(Error::Failed(format!("decoder_open rc={rc}")))
}
}
/// `oakcodec_decoder_close(decoder)`.
pub fn decoder_close(decoder: DecoderHandle) -> Result<()> {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
let rc = unsafe { oakcodec::ffi::decoder::oakcodec_decoder_close(decoder) };
if rc == 0 {
Ok(())
} else {
Err(Error::Failed(format!("decoder_close rc={rc}")))
}
}
/// `oakcodec_decoder_decode_video(decoder, num, den)` — owned frame
/// handle; null when not decodable at `time`.
pub fn decoder_decode_video(decoder: DecoderHandle, num: i64, den: i64) -> CodecFrameHandle {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::decoder::oakcodec_decoder_decode_video(decoder, num as c_int, den as c_int) }
}
/// `oakcodec_decoder_decode_audio` — decode interleaved f32 covering
/// `[in, out)` into `buf` (at least `buf_frames` frames, interleaved by
/// `channel_layout`). Returns the number of frames written or a negative
/// error.
pub fn decoder_decode_audio(
decoder: DecoderHandle,
in_num: i64,
in_den: i64,
out_num: i64,
out_den: i64,
sample_rate: c_int,
channel_layout: u64,
buf: *mut f32,
buf_frames: c_int,
) -> Result<c_int> {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
let rc = unsafe {
oakcodec::ffi::decoder::oakcodec_decoder_decode_audio(
decoder,
in_num as c_int,
in_den as c_int,
out_num as c_int,
out_den as c_int,
sample_rate,
channel_layout,
buf,
buf_frames,
)
};
if rc < 0 {
return Err(Error::Failed(format!("decode_audio rc={rc}")));
}
Ok(rc)
}
/// `oakcodec_decoder_last_error(decoder, buf, size)` — error detail.
pub fn decoder_last_error(decoder: DecoderHandle) -> String {
let mut buf = [0 as c_char; 512];
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
let n = unsafe {
oakcodec::ffi::decoder::oakcodec_decoder_last_error(decoder, buf.as_mut_ptr(), buf.len() as c_int)
};
if n <= 0 {
return String::new();
}
let len = (n as usize).min(buf.len());
let bytes: Vec<u8> = buf[..len]
.iter()
.take_while(|&&b| b != 0)
.map(|&b| b as u8)
.collect();
String::from_utf8_lossy(&bytes).into_owned()
}
// ---------------------------------------------------------------------------
// Decoded frame accessors (`oakcodec_frame_*`)
// ---------------------------------------------------------------------------
/// `oakcodec_frame_width(frame)`; 0 on an empty frame.
pub fn frame_width(frame: CodecFrameHandle) -> c_int {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::frame::oakcodec_frame_width(frame) }
}
/// `oakcodec_frame_height(frame)`; 0 on an empty frame.
pub fn frame_height(frame: CodecFrameHandle) -> c_int {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::frame::oakcodec_frame_height(frame) }
}
/// `oakcodec_frame_format(frame)`; `OAKCOMMON_PIXEL_FORMAT_INVALID` on an
/// empty frame.
pub fn frame_format(frame: CodecFrameHandle) -> c_int {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::frame::oakcodec_frame_format(frame) }
}
/// `oakcodec_frame_linesize_bytes(frame)`; 0 on an empty frame.
pub fn frame_linesize_bytes(frame: CodecFrameHandle) -> c_int {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::frame::oakcodec_frame_linesize_bytes(frame) }
}
/// `oakcodec_frame_is_allocated(frame)`; 0 on an empty frame.
pub fn frame_is_allocated(frame: CodecFrameHandle) -> c_int {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::frame::oakcodec_frame_is_allocated(frame) }
}
/// `oakcodec_frame_const_data(frame)` — read-only pixel buffer pointer.
///
/// # Safety
/// The returned pointer is valid while `frame` is alive and allocated.
pub unsafe fn frame_const_data(frame: CodecFrameHandle) -> *const u8 {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::frame::oakcodec_frame_const_data(frame) as *const u8 }
}
/// `oakcodec_frame_get_timestamp(frame, num, den)`.
pub fn frame_timestamp(frame: CodecFrameHandle) -> Option<(i64, i64)> {
let mut num: c_int = 0;
let mut den: c_int = 0;
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
let rc = unsafe { oakcodec::ffi::frame::oakcodec_frame_get_timestamp(frame, &mut num, &mut den) };
if rc == 0 && den != 0 {
Some((num as i64, den as i64))
} else {
None
}
}
/// `oakcodec_frame_free(frame: *mut CHandle)` — NULL no-op.
pub fn frame_free(frame: &mut CodecFrameHandle) {
// Direct call into the `oakcodec` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
unsafe { oakcodec::ffi::frame::oakcodec_frame_free(frame) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bad_inputs_fail_explainably() {
// Wrapper contract with bad input: every call returns the
// documented fallback rather than panicking (the real oakcodec
// guards each export against empty handles / missing files).
assert!(decoder_probe("/nonexistent_oak_test.mp4").is_null());
// decoder_init always succeeds (a closed session handle) and must
// be released.
let mut d = decoder_init();
assert!(!d.is_null());
assert!(decoder_open(d, "f", 0).is_err());
// Closing a session that is not open is a successful no-op.
assert!(decoder_close(d).is_ok());
assert!(decoder_decode_video(d, 0, 1).is_null());
decoder_free(&mut d);
assert!(d.is_null());
// Frame accessors on an empty handle hit the documented fallbacks.
let empty = CHandle::null();
assert_eq!(frame_width(empty), 0);
assert_eq!(frame_height(empty), 0);
assert_eq!(frame_linesize_bytes(empty), 0);
assert_eq!(frame_format(empty), -1);
assert!(frame_timestamp(empty).is_none());
}
}
+26 -1
View File
@@ -19,9 +19,34 @@
//! `docs/zh/plans/riir/single-lib.md`). The configuration-location and
//! disk-cache helpers delegate to oakcommon's own implementation.
use std::ffi::{c_char, c_int};
use std::ffi::{c_char, c_int, c_void};
use std::sync::Mutex;
/// `oakcore_audioparams_sample_rate` (host-provided; M12 P1 — the audio
/// ticket reads the output format from the params handle).
pub fn audioparams_sample_rate(params: *const c_void) -> c_int {
unsafe extern "C" {
fn oakcore_audioparams_sample_rate(params: *const c_void) -> c_int;
}
unsafe { oakcore_audioparams_sample_rate(params) }
}
/// `oakcore_audioparams_channel_layout` (host-provided).
pub fn audioparams_channel_layout(params: *const c_void) -> u64 {
unsafe extern "C" {
fn oakcore_audioparams_channel_layout(params: *const c_void) -> u64;
}
unsafe { oakcore_audioparams_channel_layout(params) }
}
/// `oakcore_audioparams_channel_count` (host-provided).
pub fn audioparams_channel_count(params: *const c_void) -> c_int {
unsafe extern "C" {
fn oakcore_audioparams_channel_count(params: *const c_void) -> c_int;
}
unsafe { oakcore_audioparams_channel_count(params) }
}
/// Read a config string via the two-stage C ABI
/// (`oakcommon_config_get(group, key, buf, n)`, C++ `Config::current()
/// [key].toString()`).
+9 -47
View File
@@ -14,54 +14,16 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! C ABI imports from other oak modules.
//! C ABI bridges to sibling oak modules.
//!
//! Every submodule follows the same dual-mode pattern as `src/plugin/rust`
//! (bridge/mod.rs): the default path resolves symbols at runtime through
//! [`dlsym`] (`RTLD_DEFAULT`; the module is force-loaded into the app
//! process, so oaknode/oakcommon symbols are in the global scope); when a
//! symbol is missing — e.g. `cargo test` without the C++ modules linked —
//! the wrapper returns a documented fallback (empty handle / negative
//! error code) instead of a link error.
//! Single-lib unification (see `docs/zh/plans/riir/single-lib.md`): every
//! submodule is a compile-time Rust call into the target crate's `ffi`
//! (the `#[no_mangle]` exports stay in the dylib for the external C ABI;
//! internal callers bypass them). Handles cross as the shared
//! `oakcore_rs::handle::CHandle`. The only exception is the copier
//! direction in [`node`], which targets symbols oaknode never implemented
//! and is documented there.
pub mod codec;
pub mod common;
pub mod node;
/// Shared `dlsym(RTLD_DEFAULT)` runtime resolution.
pub(crate) mod dlsym {
use std::ffi::{c_char, c_void};
/// RTLD_DEFAULT (macOS: -2; Linux: 0).
#[cfg(target_os = "macos")]
pub(crate) const RTLD_DEFAULT: *mut c_void = -2isize as *mut c_void;
#[cfg(target_os = "linux")]
pub(crate) const RTLD_DEFAULT: *mut c_void = 0isize as *mut c_void;
extern "C" {
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}
/// Resolve a global-scope symbol; `None` when missing.
pub(crate) fn resolve(name: &str) -> Option<*mut c_void> {
let c = std::ffi::CString::new(name).ok()?;
let p = unsafe { dlsym(RTLD_DEFAULT, c.as_ptr()) };
if p.is_null() {
None
} else {
Some(p)
}
}
/// Resolve and call by signature; `None` when the symbol is missing.
///
/// # Safety
/// The caller guarantees `T` matches the symbol's real function type.
pub(crate) fn call<T, R>(name: &str, f: impl FnOnce(T) -> R) -> Option<R>
where
T: Copy,
{
let p = resolve(name)?;
let f_ptr: T = unsafe { std::mem::transmute_copy(&p) };
Some(f(f_ptr))
}
}
+49 -44
View File
@@ -14,13 +14,20 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! oaknode C ABI imports (project copies, node queries).
//! oaknode C ABI bridge: direct Rust calls into the `oaknode` crate
//! (project copies, node queries).
//!
//! The functions here are declared against the frozen `include/node/*.h`
//! contract and resolved through [`crate::bridge::dlsym`]. When the
//! symbols are missing (cargo test without liboaknode) the wrappers fail
//! with the documented fallbacks; the copier tests that require a live
//! node module are `#[ignore = "needs oaknode C ABI"]`.
//! Single-lib unification (see `docs/zh/plans/riir/single-lib.md`): the
//! live node query below is a compile-time Rust call into `oaknode`'s
//! `ffi`; handles cross as the shared [`crate::handle::CHandle`]
//! (`oakcore_rs::handle::CHandle`).
//!
//! The copier direction (`project_deep_copy` / `project_sync_copy`) has
//! **no oaknode implementation**: the `oaknode_project_*` symbols were
//! declared by the old render bridge but never existed in any crate
//! (single-lib plan §4.1 — dead direction). They stay as documented
//! always-fail stubs with the exact previous fallback semantics (empty
//! handle / explainable error / `node_abi_available() == false`).
use std::ffi::c_int;
@@ -63,49 +70,44 @@ pub mod change_kind {
pub const FOOTAGE_PROXY: u32 = 7;
}
/// `oaknode_project_deep_copy(project)` — new in the Rust-era node C ABI.
/// Returns an owned copied-project handle; empty when the symbol is
/// missing or the copy failed.
pub fn project_deep_copy(project: ProjectHandle) -> CHandle {
type F = unsafe extern "C" fn(ProjectHandle) -> CHandle;
crate::bridge::dlsym::call::<F, CHandle>("oaknode_project_deep_copy", |f| unsafe { f(project) })
.unwrap_or_else(CHandle::null)
/// `oaknode_project_deep_copy(project)` — would return an owned
/// copied-project handle.
///
/// Never implemented: oaknode has no such C ABI export (single-lib plan
/// §4.1 — dead direction), so this always yields the empty handle, exactly
/// as the previous runtime-symbol lookup did when the symbol was absent.
pub fn project_deep_copy(_project: ProjectHandle) -> CHandle {
CHandle::null()
}
/// `oaknode_project_sync_copy(source, copy, changes, count)` — pushes a
/// recorded change set into the copy. `OAKNODE_OK` (0) on success; a
/// negative error otherwise (missing symbol → `Error::Failed`).
/// `oaknode_project_sync_copy(source, copy, changes, count)` — would push
/// a recorded change set into the copy.
///
/// Never implemented: oaknode has no such C ABI export (single-lib plan
/// §4.1 — dead direction), so this always fails explainably, exactly as
/// the previous runtime-symbol lookup did when the symbol was absent.
pub fn project_sync_copy(
source: ProjectHandle,
copy: ProjectHandle,
changes: &[ChangeRecord],
_source: ProjectHandle,
_copy: ProjectHandle,
_changes: &[ChangeRecord],
) -> Result<()> {
type F =
unsafe extern "C" fn(ProjectHandle, ProjectHandle, *const ChangeRecord, c_int) -> c_int;
let rc = crate::bridge::dlsym::call::<F, c_int>("oaknode_project_sync_copy", |f| unsafe {
f(source, copy, changes.as_ptr(), changes.len() as c_int)
})
.ok_or_else(|| Error::Failed("oaknode_project_sync_copy missing".into()))?;
if rc == 0 {
Ok(())
} else {
Err(Error::Failed(format!("oaknode_project_sync_copy rc={rc}")))
}
Err(Error::Failed(
"oaknode_project_sync_copy missing (not implemented in oaknode)".into(),
))
}
/// `oaknode_node_get_video_frame_cache(node, out)` — borrowed cache
/// handle of a node. `OAKNODE_OK` (0) on success with `*out` set;
/// otherwise a negative error (missing symbol → `Error::Failed`).
/// otherwise a negative error.
///
/// # Safety
/// `node` must be a valid handle; `out` a valid pointer.
pub unsafe fn node_get_video_frame_cache(node: NodeHandle, out: *mut CHandle) -> Result<()> {
type F = unsafe extern "C" fn(NodeHandle, *mut CHandle) -> c_int;
let rc =
crate::bridge::dlsym::call::<F, c_int>("oaknode_node_get_video_frame_cache", |f| unsafe {
f(node, out)
})
.ok_or_else(|| Error::Failed("oaknode_node_get_video_frame_cache missing".into()))?;
// Direct call into the `oaknode` crate (single-lib unification; the
// `#[no_mangle]` export stays for the external C ABI).
let rc = unsafe {
oaknode::ffi::node::oaknode_node_get_video_frame_cache(node, out as *mut std::ffi::c_void)
};
if rc == 0 {
Ok(())
} else {
@@ -115,10 +117,13 @@ pub unsafe fn node_get_video_frame_cache(node: NodeHandle, out: *mut CHandle) ->
}
}
/// Whether the oaknode C ABI is present in the process (tests use this to
/// gate success-path copier tests).
/// Whether the oaknode deep-copy C ABI is available.
///
/// Constant `false`: `oaknode_project_deep_copy` was never implemented
/// (single-lib plan §4.1), so the copier success-path tests stay gated
/// exactly as before.
pub fn node_abi_available() -> bool {
crate::bridge::dlsym::resolve("oaknode_project_deep_copy").is_some()
false
}
/// Node identity of a handle (the box pointer; matches the copier's
@@ -132,20 +137,20 @@ mod tests {
use super::*;
#[test]
fn deep_copy_missing_symbol_yields_empty_handle() {
// Without liboaknode the deep copy cannot exist.
fn deep_copy_unavailable_yields_empty_handle() {
// oaknode never implemented the deep-copy ABI (dead direction).
let h = project_deep_copy(CHandle::null());
assert!(h.is_null());
}
#[test]
fn sync_copy_missing_symbol_fails_explainably() {
fn sync_copy_unavailable_fails_explainably() {
let changes = [ChangeRecord {
kind: change_kind::NODE_ADD,
payload: [0u8; 48],
}];
let rc = project_sync_copy(CHandle::null(), CHandle::null(), &changes);
assert!(rc.is_err(), "missing symbol → explainable failure");
assert!(rc.is_err(), "not implemented → explainable failure");
}
#[test]
+4 -3
View File
@@ -19,9 +19,10 @@
//! (`oaknode_project_deep_copy` / `sync_copy`); this module only tracks
//! which copy belongs to which viewer and when to re-sync.
//!
//! The oaknode C ABI functions are resolved through [`crate::bridge::node`]
//! (dlsym); without liboaknode linked (cargo test) the copy operations
//! fail explainably and the success-path tests are `#[ignore]`d.
//! The oaknode C ABI functions go through [`crate::bridge::node`]; oaknode
//! never implemented the deep-copy symbols (single-lib plan §4.1 — dead
//! direction), so the copy operations fail explainably and the
//! success-path tests are `#[ignore]`d.
use crate::bridge::node::{ChangeRecord, ProjectHandle};
use crate::error::{Error, Result};
+357 -6
View File
@@ -25,6 +25,8 @@
//! depend on the oakcodec / oaknode / oakplugin C ABIs and fail with
//! explainable errors (their success-path tests are `#[ignore]`d).
use std::ffi::c_int;
use oakcore_rs::{PixelFormat, Rational};
use crate::error::{Error, Result};
@@ -59,6 +61,10 @@ pub enum JobSpec {
Footage {
/// Decoder/stream id.
decoder_id: String,
/// Footage filename (M12 P0: the decode path).
filename: String,
/// Media stream index.
stream_index: i32,
},
/// Sample generation (C++ SampleJob).
Sample,
@@ -89,13 +95,33 @@ impl RenderEvalHooks {
/// C++ process_video_footage: decode + upload into `destination`.
fn process_video_footage(&mut self, destination: &mut Texture, spec: &JobSpec) -> Result<()> {
let JobSpec::Footage { decoder_id } = spec else {
let JobSpec::Footage {
decoder_id,
filename,
stream_index,
} = spec
else {
return Err(Error::Invalid);
};
let _ = (destination, decoder_id);
Err(Error::Failed(
"footage decode deferred: oakcodec decoder bridge pending".into(),
))
let _ = decoder_id;
let Texture::Cpu(frame) = destination else {
return Err(Error::Failed(
"footage decode on GPU deferred: CPU path only this pass".into(),
));
};
let mut decoded = render_footage_frame(
filename,
*stream_index,
frame.timestamp,
(frame.width, frame.height),
frame.format,
)?;
let src_data = match &mut decoded {
Texture::Cpu(frame) => std::mem::take(&mut frame.data),
_ => return Err(Error::Failed("decode produced a GPU texture".into())),
};
frame.data = src_data;
Ok(())
}
/// C++ process_audio_footage.
@@ -205,16 +231,337 @@ pub fn generate_frame(time: Rational, size: (i32, i32), format: PixelFormat) ->
/// The manager-installed ticket producer: render the frame the ticket
/// asks for (F32 pipeline frame). This is the CPU-backend render path.
///
/// M12 P0 routing: a sequence montage (list of clips) is composited
/// topmost-last; a single-footage ticket decodes one stream; otherwise
/// the pipeline frame is generated.
pub fn render_produced_frame(
time: Rational,
params: &crate::ticket::VideoTicketParams,
) -> Result<Texture> {
let (w, h) = params.render_size();
let format = params.force_format.unwrap_or(PixelFormat::F32);
if !params.montage.is_empty() {
let r = render_montage_frame(time, params, (w, h), format);
return r;
}
if let Some((filename, stream_index)) = &params.footage {
return render_footage_frame(filename, *stream_index, time, (w, h), format);
}
let frame = generate_frame(time, (w, h), format)?;
Ok(Texture::wrap_frame(frame))
}
// ---------------------------------------------------------------------------
// Footage decode (M12 P0): the oakcodec bridge
// ---------------------------------------------------------------------------
/// Process-wide open decoder sessions, keyed by (filename, stream).
/// Sessions are mutex-serialized inside the oakcodec box, so sharing
/// one handle across worker threads is safe.
static DECODERS: std::sync::OnceLock<std::sync::Mutex<
std::collections::HashMap<(String, i32), crate::handle::CHandle>,
>> = std::sync::OnceLock::new();
fn decoders() -> std::sync::MutexGuard<'static, std::collections::HashMap<(String, i32), crate::handle::CHandle>> {
DECODERS
.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
.lock()
.unwrap_or_else(|e| e.into_inner())
}
/// Open (or reuse) the decoder session for `(filename, stream_index)`.
fn open_decoder(filename: &str, stream_index: i32) -> Result<crate::handle::CHandle> {
{
let cache = decoders();
if let Some(h) = cache.get(&(filename.to_string(), stream_index)) {
if !h.is_null() {
return Ok(*h);
}
}
}
let decoder = crate::bridge::codec::decoder_init();
if decoder.is_null() {
return Err(Error::Failed("footage decode: decoder_init failed".into()));
}
crate::bridge::codec::decoder_open(decoder, filename, stream_index)
.map_err(|e| Error::Failed(format!("footage decode open: {e:?}")))?;
let mut cache = decoders();
cache.insert((filename.to_string(), stream_index), decoder);
Ok(decoder)
}
/// Decode the footage frame at `time` and copy/scale it into an
/// oakrender F32 frame of `(w, h)`.
pub fn render_footage_frame(
filename: &str,
stream_index: i32,
time: Rational,
size: (i32, i32),
format: PixelFormat,
) -> Result<Texture> {
let decoder = open_decoder(filename, stream_index)?;
let frame_handle = crate::bridge::codec::decoder_decode_video(
decoder,
time.numerator(),
time.denominator(),
);
if frame_handle.is_null() {
let detail = crate::bridge::codec::decoder_last_error(decoder);
return Err(Error::Failed(format!(
"footage decode at {time:?}: {detail}"
)));
}
let src_w = crate::bridge::codec::frame_width(frame_handle);
let src_h = crate::bridge::codec::frame_height(frame_handle);
let src_linesize = crate::bridge::codec::frame_linesize_bytes(frame_handle);
let _alloc = crate::bridge::codec::frame_is_allocated(frame_handle);
let (w, h) = size;
if src_w <= 0
|| src_h <= 0
|| src_linesize <= 0
|| crate::bridge::codec::frame_is_allocated(frame_handle) == 0
{
frame_free(frame_handle);
return Err(Error::Failed("footage decode: bad decoded frame".into()));
}
let mut dst = generate_frame(time, (w, h), format)?;
let dst_linesize = dst.linesize_bytes() as i32;
let src_data = unsafe { crate::bridge::codec::frame_const_data(frame_handle) };
if src_data.is_null() {
frame_free(frame_handle);
return Err(Error::Failed("footage decode: no frame data".into()));
}
if src_w == w && src_h == h && src_linesize == dst_linesize {
let bytes = (src_h as usize)
.checked_mul(src_linesize as usize)
.ok_or(Error::NoMem)?;
let src_slice = unsafe { std::slice::from_raw_parts(src_data, bytes) };
dst.data[..bytes].copy_from_slice(src_slice);
} else {
scale_rgba_f32(
src_data,
src_linesize,
src_w,
src_h,
&mut dst.data,
dst_linesize,
w,
h,
);
}
frame_free(frame_handle);
Ok(Texture::wrap_frame(dst))
}
/// Render the audio montage over `params.range` (M12 P1): every clip
/// overlapping the range is decoded (interleaved f32 at the output rate
/// and layout) and mixed with its gain; uncovered parts stay silent.
pub fn render_audio_samples(
params: &crate::ticket::AudioTicketParams,
) -> Result<crate::ticket::TicketPayload> {
let rate = params.sample_rate.max(1);
let channels = params.channel_layout.count_ones().max(1) as i32;
let duration = params.range.out() - params.range.in_();
let seconds = if duration.denominator() == 0 {
0.0
} else {
duration.numerator() as f64 / duration.denominator() as f64
};
if seconds <= 0.0 || seconds > 3600.0 {
return Err(Error::Invalid);
}
let total_frames = (seconds * rate as f64).round() as usize;
let mut acc = vec![0.0f32; total_frames.saturating_mul(channels as usize)];
for clip in &params.montage {
// Overlap of the clip with the requested range.
let in_time = params.range.in_().max(clip.in_time);
let out_time = params.range.out().min(clip.out_time);
if out_time <= in_time {
continue;
}
let start_frame = ((in_time - params.range.in_()).to_f64() * rate as f64) as usize;
let end_frame = ((out_time - params.range.in_()).to_f64() * rate as f64) as usize;
if start_frame >= total_frames {
continue;
}
let frames = (end_frame - start_frame).min(total_frames - start_frame);
if frames == 0 {
continue;
}
// Media time of the overlap start; the media-out is
// media_start + (overlap duration).
let media_start = clip.media_in + (in_time - clip.in_time);
let media_end = media_start + (out_time - in_time);
let mut buf = vec![0.0f32; frames * channels as usize];
let decoder = open_decoder(&clip.filename, clip.stream_index)?;
let rc = crate::bridge::codec::decoder_decode_audio(
decoder,
media_start.numerator(),
media_start.denominator(),
media_end.numerator(),
media_end.denominator(),
rate,
params.channel_layout,
buf.as_mut_ptr(),
frames as c_int,
);
let written = rc.unwrap_or(0).max(0) as usize;
let written = written.min(frames);
// Mix into the accumulator (per-channel gain).
for i in 0..written * channels as usize {
acc[start_frame * channels as usize + i] += buf[i] * clip.gain;
}
}
Ok(crate::ticket::TicketPayload::Audio(crate::ticket::AudioSamples {
samples: acc,
sample_rate: rate,
channel_layout: params.channel_layout,
channel_count: channels,
}))
}
/// Free a codec frame handle (Copy-handle dance).
fn frame_free(mut h: crate::handle::CHandle) {
crate::bridge::codec::frame_free(&mut h);
}
/// Bilinear scale an F32-RGBA image (row-major with per-row strides).
fn scale_rgba_f32(
src: *const u8,
src_stride: i32,
src_w: i32,
src_h: i32,
dst: &mut [u8],
dst_stride: i32,
dst_w: i32,
dst_h: i32,
) {
if src_w <= 0 || src_h <= 0 || dst_w <= 0 || dst_h <= 0 {
return;
}
// 1:1 copy (no scaling): the caller already handled stride equality;
// here we handle the general case with a fast path for integer 1:1.
let sample = |x: f64, y: f64| -> [f32; 4] {
let x0 = x.floor() as i32;
let y0 = y.floor() as i32;
let fx = (x - x0 as f64) as f32;
let fy = (y - y0 as f64) as f32;
let x1 = (x0 + 1).clamp(0, src_w - 1);
let y1 = (y0 + 1).clamp(0, src_h - 1);
let x0 = x0.clamp(0, src_w - 1);
let y0 = y0.clamp(0, src_h - 1);
let px = |xx: i32, yy: i32| -> [f32; 4] {
let off = (yy as usize) * (src_stride as usize) + (xx as usize) * 16;
// SAFETY: coordinates are clamped to the source size.
let b = unsafe { std::slice::from_raw_parts(src.add(off), 16) };
let f = |i: usize| f32::from_le_bytes(b[i * 4..i * 4 + 4].try_into().unwrap());
[f(0), f(1), f(2), f(3)]
};
let c00 = px(x0, y0);
let c10 = px(x1, y0);
let c01 = px(x0, y1);
let c11 = px(x1, y1);
let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t;
let mut out = [0f32; 4];
for i in 0..4 {
let top = lerp(c00[i], c10[i], fx);
let bottom = lerp(c01[i], c11[i], fx);
out[i] = lerp(top, bottom, fy);
}
out
};
for y in 0..dst_h {
let sy = (y as f64 + 0.5) * src_h as f64 / dst_h as f64 - 0.5;
let sy = sy.max(0.0);
for x in 0..dst_w {
let sx = (x as f64 + 0.5) * src_w as f64 / dst_w as f64 - 0.5;
let sx = sx.max(0.0);
let px = sample(sx, sy);
let off = (y as usize) * (dst_stride as usize) + (x as usize) * 16;
for i in 0..4 {
dst[off + i * 4..off + i * 4 + 4]
.copy_from_slice(&px[i].clamp(0.0, 1.0).to_le_bytes());
}
}
}
}
/// Composite the montage at `time`: decode each covering clip and
/// alpha-composite topmost-last (C++ track order: track 0 is topmost).
fn render_montage_frame(
time: Rational,
params: &crate::ticket::VideoTicketParams,
size: (i32, i32),
format: PixelFormat,
) -> Result<Texture> {
let mut acc = generate_frame(time, size, format)?;
let stride = acc.linesize_bytes();
let (w, h) = size;
let mut acc32 = acc.data; // decode from bottom clip first
for clip in &params.montage {
if time < clip.in_time || time >= clip.out_time {
continue;
}
let media_time = clip.media_in + (time - clip.in_time);
let decoded = render_footage_frame(&clip.filename, clip.stream_index, media_time, (w, h), format)?;
let (src_data, src_stride) = match &decoded {
Texture::Cpu(src) => (&src.data, src.linesize_bytes() as i32),
_ => continue,
};
composite_over(&mut acc32, stride as i32, w, h, src_data, src_stride, clip.gain);
}
acc.data = acc32;
Ok(Texture::wrap_frame(acc))
}
/// `src` over `dst` (premultiplied-ish alpha compositing; F32 RGBA).
/// `gain` scales the source RGB (audio-style volume applied to video
/// transparency is ignored here; gain scales color).
fn composite_over(
dst: &mut [u8],
dst_stride: i32,
w: i32,
h: i32,
src: &[u8],
src_stride: i32,
gain: f32,
) {
let read = |buf: &[u8], stride: i32, x: i32, y: i32| -> [f32; 4] {
let off = (y as usize) * (stride as usize) + (x as usize) * 16;
let mut out = [0f32; 4];
for i in 0..4 {
out[i] = f32::from_le_bytes(buf[off + i * 4..off + i * 4 + 4].try_into().unwrap());
}
out
};
for y in 0..h {
for x in 0..w {
let s = read(src, src_stride, x, y);
let d = read(dst, dst_stride, x, y);
let a = (s[3] * gain).clamp(0.0, 1.0);
let out = [
(s[0] * gain) * a + d[0] * (1.0 - a),
(s[1] * gain) * a + d[1] * (1.0 - a),
(s[2] * gain) * a + d[2] * (1.0 - a),
a + d[3] * (1.0 - a),
];
let off = (y as usize) * (dst_stride as usize) + (x as usize) * 16;
for i in 0..4 {
dst[off + i * 4..off + i * 4 + 4].copy_from_slice(&out[i].clamp(0.0, 1.0).to_le_bytes());
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -247,6 +594,8 @@ mod tests {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
};
let tex = render_produced_frame(params.time, &params).unwrap();
assert_eq!(tex.size(), (16, 9));
@@ -261,7 +610,9 @@ mod tests {
.process_video_footage(
&mut dest,
&JobSpec::Footage {
decoder_id: "d".into()
decoder_id: "d".into(),
filename: "definitely-missing-file.mp4".into(),
stream_index: 0,
}
)
.is_err());
+179 -13
View File
@@ -128,6 +128,56 @@ pub struct OakVideoTicketParams {
pub force_color_transform: OakColorTransform,
/// Borrowed frame cache; empty ctx = none.
pub cache: OakRenderCache,
/// Single-footage decode filename (null = off; M12 P0).
pub footage_filename: *const c_char,
/// Media stream index for `footage_filename`.
pub footage_stream: c_int,
/// Sequence montage clip array (null = off; M12 P0). Clips are
/// ordered bottom-to-top; the last element is the topmost.
pub montage: *const OakMontageClip,
/// `montage` element count.
pub montage_count: c_int,
}
/// One sequence-montage clip (M12 P0): the facade resolves the timeline
/// into this POD list; the render producer decodes and composites.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct OakMontageClip {
/// Footage filename (borrowed; alive for the render call).
pub filename: *const c_char,
/// Media stream index.
pub stream_index: c_int,
/// Clip in point (sequence time), rational.
pub in_num: i64,
/// Clip in point denominator.
pub in_den: i64,
/// Clip out point (sequence time), rational.
pub out_num: i64,
/// Clip out point denominator.
pub out_den: i64,
/// Media in point, rational.
pub media_in_num: i64,
/// Media in point denominator.
pub media_in_den: i64,
/// Playback gain (1.0 = unity).
pub gain: f32,
}
/// The samples block handed out by `oakrender_ticket_get_samples`
/// (caller-owned; release with `oakrender_audio_samples_free`). Read by
/// the facade through the Rust type.
pub struct OakAudioSamplesOut {
/// Interleaved f32 samples.
pub data: Box<[f32]>,
/// Frame count.
pub frame_count: c_int,
/// Sample rate (Hz).
pub sample_rate: c_int,
/// Channel layout mask.
pub channel_layout: u64,
/// Channel count.
pub channel_count: c_int,
}
/// `oakrender_color_transform_job` (render/renderer.h).
@@ -353,11 +403,11 @@ pub mod manager {
let _arena = arena.clone();
Box::new(move |result| {
let handle = match result {
Ok(tex) => match tex.to_frame() {
Ok(crate::ticket::TicketPayload::Video(tex)) => match tex.to_frame() {
Ok(frame) => frame_handle(frame),
Err(_) => CHandle::null(),
},
Err(_) => CHandle::null(),
_ => CHandle::null(),
};
lock().remove(&rid);
unsafe { cb(handle, ts, userdata.ptr()) };
@@ -1107,6 +1157,36 @@ pub mod ticket {
});
let userdata = RawSend(userdata);
// The completion needs the final handle to pass to `cb`.
let footage = if !params.footage_filename.is_null() {
let filename = unsafe { cstr(params.footage_filename) };
filename.filter(|s| !s.is_empty()).map(|s| (s, params.footage_stream))
} else {
None
};
let montage = if !params.montage.is_null() && params.montage_count > 0 {
let count = params.montage_count.min(1024);
let mut out = Vec::with_capacity(count as usize);
for i in 0..count {
let c = unsafe { &*params.montage.add(i as usize) };
let Some(filename) = (unsafe { cstr(c.filename) }) else {
continue;
};
if filename.is_empty() {
continue;
}
out.push(crate::ticket::MontageClip {
filename,
stream_index: c.stream_index,
in_time: oakcore_rs::Rational::new(c.in_num, c.in_den),
out_time: oakcore_rs::Rational::new(c.out_num, c.out_den),
media_in: oakcore_rs::Rational::new(c.media_in_num, c.media_in_den),
gain: c.gain,
});
}
out
} else {
Vec::new()
};
arena.submit_video_with_id(
id,
crate::ticket::VideoTicketParams {
@@ -1122,6 +1202,8 @@ pub mod ticket {
cache_dir,
cache_id,
cache_timebase,
footage,
montage,
},
match cb {
Some(cb) => Box::new(move |_result| {
@@ -1134,7 +1216,9 @@ pub mod ticket {
})
}
/// `oakrender_ticket_render_audio`.
/// `oakrender_ticket_render_audio` — range audio render (M12 P1).
/// `montage`/`montage_count` carry the clips to mix (same POD as the
/// video path; additive trailing fields).
#[no_mangle]
pub unsafe extern "C" fn oakrender_ticket_render_audio(
output_node: OakNodeNode,
@@ -1146,6 +1230,8 @@ pub mod ticket {
mode: c_int,
cb: Option<unsafe extern "C" fn(OakRenderTicket, *mut c_void)>,
userdata: *mut c_void,
montage: *const OakMontageClip,
montage_count: c_int,
) -> OakRenderTicket {
crate::handle::guard_handle(|| {
if output_node.is_null() || params.is_null() {
@@ -1159,6 +1245,35 @@ pub mod ticket {
oakcore_rs::Rational::new(in_num, in_den),
oakcore_rs::Rational::new(out_num, out_den),
);
let sample_rate =
crate::bridge::common::audioparams_sample_rate(params as *const c_void).max(1);
let channel_layout = crate::bridge::common::audioparams_channel_layout(
params as *const c_void,
);
let montage = if !montage.is_null() && montage_count > 0 {
let count = montage_count.min(1024);
let mut out = Vec::with_capacity(count as usize);
for i in 0..count {
let c = unsafe { &*montage.add(i as usize) };
let Some(filename) = (unsafe { cstr(c.filename) }) else {
continue;
};
if filename.is_empty() {
continue;
}
out.push(crate::ticket::MontageClip {
filename,
stream_index: c.stream_index,
in_time: oakcore_rs::Rational::new(c.in_num, c.in_den),
out_time: oakcore_rs::Rational::new(c.out_num, c.out_den),
media_in: oakcore_rs::Rational::new(c.media_in_num, c.media_in_den),
gain: c.gain,
});
}
out
} else {
Vec::new()
};
let arena = manager.tickets.clone();
let id = arena.next_id();
let handle = crate::handle::make_owned(TicketBox {
@@ -1168,8 +1283,13 @@ pub mod ticket {
let userdata = RawSend(userdata);
arena.submit_audio_with_id(
id,
output_node.ctx as u64,
range,
crate::ticket::AudioTicketParams {
viewer: output_node.ctx as u64,
range,
sample_rate,
channel_layout,
montage,
},
match cb {
Some(cb) => Box::new(move |_result| {
unsafe { cb(handle, userdata.ptr()) };
@@ -1296,8 +1416,16 @@ pub mod ticket {
.arena
.result(b.id)
.ok_or_else(|| crate::error::Error::Failed("ticket has no result".into()))?;
let texture =
result.map_err(|_| crate::error::Error::Failed("ticket failed".into()))?;
let texture = match result.map_err(|_| {
crate::error::Error::Failed("ticket failed".into())
})? {
crate::ticket::TicketPayload::Video(t) => t,
_ => {
return Err(crate::error::Error::Failed(
"ticket produced audio, not video".into(),
));
}
};
let frame = texture.to_frame()?;
unsafe { *out = frame_handle(frame) };
if unsafe { (*out).is_null() } {
@@ -1307,8 +1435,9 @@ pub mod ticket {
})
}
/// `oakrender_ticket_get_samples` — audio rendering is not implemented
/// in this pass; always fails explainably.
/// `oakrender_ticket_get_samples` — the audio ticket's interleaved
/// f32 samples (M12 P1). `*out` receives a heap `OakAudioSamples`
/// owned by the caller (release with `oakrender_audio_samples_free`).
#[no_mangle]
pub unsafe extern "C" fn oakrender_ticket_get_samples(
ticket: OakRenderTicket,
@@ -1319,14 +1448,51 @@ pub mod ticket {
return Err(crate::error::Error::Invalid);
}
unsafe { *out = std::ptr::null_mut() };
let _ = unsafe { crate::handle::get::<TicketBox>(&ticket) }
let b = unsafe { crate::handle::get::<TicketBox>(&ticket) }
.ok_or(crate::error::Error::Invalid)?;
Err(crate::error::Error::Failed(
"audio samples deferred: audio rendering not implemented".into(),
))
if !b.arena.is_finished(b.id) {
return Err(crate::error::Error::State);
}
let result = b
.arena
.result(b.id)
.ok_or_else(|| crate::error::Error::Failed("ticket has no result".into()))?;
let samples = match result.map_err(|_| {
crate::error::Error::Failed("audio ticket failed".into())
})? {
crate::ticket::TicketPayload::Audio(a) => a,
_ => {
return Err(crate::error::Error::Failed(
"ticket produced video, not audio".into(),
));
}
};
let boxed = Box::new(OakAudioSamplesOut {
data: samples.samples.clone().into_boxed_slice(),
frame_count: samples
.samples
.len()
.checked_div(samples.channel_count.max(1) as usize)
.unwrap_or(0) as c_int,
sample_rate: samples.sample_rate,
channel_layout: samples.channel_layout,
channel_count: samples.channel_count,
});
unsafe { *out = Box::into_raw(boxed) as *mut c_void };
Ok(())
})
}
/// `oakrender_audio_samples_free` — release the samples block returned
/// by `oakrender_ticket_get_samples` (NULL no-op).
#[no_mangle]
pub unsafe extern "C" fn oakrender_audio_samples_free(samples: *mut c_void) {
if samples.is_null() {
return;
}
unsafe { drop(Box::from_raw(samples as *mut OakAudioSamplesOut)) };
}
/// `oakrender_ticket_free`.
#[no_mangle]
pub unsafe extern "C" fn oakrender_ticket_free(ticket: *mut OakRenderTicket) {
+1 -1
View File
@@ -32,7 +32,7 @@
//! - `backend` — wgpu GPU context + display renderer
//! - `copier` — render-side project-copy client (oaknode C ABI)
//! - `cancelatom` — the cancellation primitive
//! - `bridge` — C ABI imports (oakcommon/oaknode/oakcodec, dlsym-resolved)
//! - `bridge` — direct-call C ABI bridges (oakcommon/oaknode/oakcodec)
//! - `ffi` — the `include/render/*.h` export layer
#![deny(unsafe_op_in_unsafe_fn)]
+4 -2
View File
@@ -69,8 +69,10 @@ impl RenderManager {
let backend = BackendKind::from_user_config();
let mut pool = WorkerPool::new(0);
pool.start();
let producer: crate::ticket::Producer =
Arc::new(|time, params| eval::render_produced_frame(time, params));
let producer: crate::ticket::Producer = Arc::new(|time, params| {
eval::render_produced_frame(time, params)
.map(crate::ticket::TicketPayload::Video)
});
let tickets = Arc::new(TicketArena::new(pool.clone(), producer));
*guard = Some(Arc::new(RenderManager {
pool,
+114 -23
View File
@@ -31,9 +31,46 @@ use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use oakcore_rs::{Rational, TimeRange};
use crate::error::{Error, Result};
use crate::eval;
use crate::texture::Texture;
use crate::worker::WorkerPool;
/// One clip of a sequence montage (M12 P0): the facade resolves the
/// timeline into an ordered list of clips; the producer decodes each and
/// composites them topmost-last.
#[derive(Clone, Debug)]
pub struct MontageClip {
/// Footage filename.
pub filename: String,
/// Media stream index.
pub stream_index: i32,
/// Clip in point (sequence time).
pub in_time: Rational,
/// Clip out point (sequence time).
pub out_time: Rational,
/// Media in point.
pub media_in: Rational,
/// Playback gain (1.0 = unity).
pub gain: f32,
}
/// Audio ticket parameters (M12 P1): the output format plus the audio
/// montage to mix over the requested range.
#[derive(Clone, Debug)]
pub struct AudioTicketParams {
/// Node graph context (copied project identity).
pub viewer: u64,
/// The range to render (sequence time).
pub range: TimeRange,
/// Output sample rate (Hz).
pub sample_rate: i32,
/// Output channel layout mask.
pub channel_layout: u64,
/// Clips to mix (ordered arbitrarily; gains applied, silence
/// elsewhere).
pub montage: Vec<MontageClip>,
}
/// Ticket parameters (Rust view of `oakrender_video_ticket_params`).
#[derive(Clone, Debug)]
pub struct VideoTicketParams {
@@ -54,6 +91,11 @@ pub struct VideoTicketParams {
pub cache_id: Option<String>,
/// Cache timebase.
pub cache_timebase: Option<oakcore_rs::Rational>,
/// Single-footage decode (footage node render; M12 P0).
pub footage: Option<(String, i32)>,
/// Sequence montage (ordered topmost-last; M12 P0). When set, the
/// footage field is ignored.
pub montage: Vec<MontageClip>,
}
impl VideoTicketParams {
@@ -66,8 +108,31 @@ impl VideoTicketParams {
}
}
/// Completion payload: the rendered texture or the failure reason.
pub type TicketResult = Result<Texture>;
/// Audio samples produced by an audio ticket (M12 P1).
#[derive(Clone, Debug)]
pub struct AudioSamples {
/// Interleaved f32 samples.
pub samples: Vec<f32>,
/// Sample rate (Hz).
pub sample_rate: i32,
/// Channel layout mask.
pub channel_layout: u64,
/// Channel count.
pub channel_count: i32,
}
/// The ticket completion payload: video frames or audio samples.
#[derive(Clone, Debug)]
pub enum TicketPayload {
/// A rendered video texture.
Video(Texture),
/// Rendered interleaved audio.
Audio(AudioSamples),
}
/// Completion payload: the rendered texture/samples or the failure
/// reason.
pub type TicketResult = Result<TicketPayload>;
/// Completion callback (exactly-once delivery).
pub type Completion = Box<dyn FnOnce(TicketResult) + Send>;
@@ -192,9 +257,9 @@ impl TicketArena {
}
}
/// A producer that always fails (audio rendering is not implemented in
/// this pass; used for audio tickets).
fn audio_producer() -> Producer {
/// A producer that always fails (kept for tests that need a failing
/// producer).
pub fn audio_producer() -> Producer {
Arc::new(|_, _| Err(Error::Failed("audio rendering not implemented".into())))
}
@@ -268,16 +333,15 @@ impl TicketArena {
}
/// Submit an audio ticket (range pull; C++ render_audio) with a
/// caller-reserved id (allocated by [`TicketArena::next_id`]). Audio
/// rendering is not implemented in this pass; the completion still
/// fires exactly once with `Error::Failed`.
/// caller-reserved id (allocated by [`TicketArena::next_id`]). The
/// completion fires exactly once.
pub fn submit_audio_with_id(
&self,
id: TicketId,
viewer: u64,
range: TimeRange,
params: AudioTicketParams,
done: Completion,
) -> TicketId {
let range = params.range;
let meta = TicketMeta {
kind: Some(ticket_kind::AUDIO),
time: Some(range.in_()),
@@ -298,7 +362,12 @@ impl TicketArena {
});
self.allocate(slot.clone());
let producer = Self::audio_producer();
// The audio producer captures the montage + output params; the
// video-params field of the job is a dummy (unused by the audio
// path).
let ap = Arc::new(params);
let viewer = ap.viewer;
let producer: Producer = Arc::new(move |_, _| eval::render_audio_samples(&ap));
let slot_done = slot.clone();
let job = crate::worker::Job {
node_identity: viewer,
@@ -312,6 +381,8 @@ impl TicketArena {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
}),
produce: producer,
done: Box::new(move |result| slot_done.finish(result)),
@@ -322,12 +393,11 @@ impl TicketArena {
id
}
/// Submit an audio ticket (range pull; C++ render_audio). Audio
/// rendering is not implemented in this pass; the completion still
/// fires exactly once with `Error::Failed`.
pub fn submit_audio(&self, viewer: u64, range: TimeRange, done: Completion) -> TicketId {
/// Submit an audio ticket (range pull; C++ render_audio). The
/// completion fires exactly once.
pub fn submit_audio(&self, params: AudioTicketParams, done: Completion) -> TicketId {
let id = self.next_id();
self.submit_audio_with_id(id, viewer, range, done)
self.submit_audio_with_id(id, params, done)
}
/// True when the ticket has finished.
@@ -419,7 +489,7 @@ mod tests {
}
fn ok_producer() -> Producer {
Arc::new(|_, _| Ok(Texture::wrap_frame(small_frame())))
Arc::new(|_, _| Ok(TicketPayload::Video(Texture::wrap_frame(small_frame()))))
}
#[test]
@@ -440,6 +510,8 @@ mod tests {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
},
Box::new(move |r| {
let _ = tx.send(r.is_ok());
@@ -455,7 +527,13 @@ mod tests {
);
let res = arena.result(id).unwrap().unwrap();
assert_eq!(res.size(), (4, 4));
assert_eq!(
match res {
TicketPayload::Video(t) => t.size(),
_ => panic!("video ticket"),
},
(4, 4)
);
assert!(arena.is_finished(id));
pool.shutdown();
}
@@ -472,7 +550,7 @@ mod tests {
while !release2.load(Ordering::Acquire) {
std::thread::sleep(Duration::from_millis(1));
}
Ok(Texture::wrap_frame(small_frame()))
Ok(TicketPayload::Video(Texture::wrap_frame(small_frame())))
});
let arena = TicketArena::new(pool.clone(), producer);
@@ -487,6 +565,8 @@ mod tests {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
},
Box::new(move |r| {
let _ = tx.send(r);
@@ -541,9 +621,14 @@ mod tests {
let (tx, rx) = mpsc::channel();
let range = TimeRange::new(Rational::new(0, 1), Rational::new(10, 1));
let id = arena.submit_audio(
7,
range,
Box::new(move |r| {
AudioTicketParams {
viewer: 7,
range,
sample_rate: 48000,
channel_layout: 0x3,
montage: Vec::new(),
},
Box::new(move |r: TicketResult| {
let _ = tx.send(r.is_err());
}),
);
@@ -551,7 +636,9 @@ mod tests {
assert_eq!(arena.meta(id).unwrap().kind, Some(ticket_kind::AUDIO));
assert_eq!(arena.range(id), Some(range));
arena.wait(id).unwrap();
assert!(rx.recv_timeout(Duration::from_secs(5)).unwrap());
// M12 P1: an empty-montage audio ticket succeeds with silence
// (the completion must NOT report an error).
assert!(!rx.recv_timeout(Duration::from_secs(5)).unwrap());
// get_time equivalent: audio tickets report range.in.
assert_eq!(arena.time(id), Some(range.in_()));
pool.shutdown();
@@ -573,6 +660,8 @@ mod tests {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
},
Box::new(|_| {}),
);
@@ -586,6 +675,8 @@ mod tests {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
},
Box::new(|_| {}),
);
+9 -3
View File
@@ -344,7 +344,7 @@ mod tests {
if let Some(g) = &gate {
g.fetch_add(1, Ordering::SeqCst);
}
Ok(Texture::dummy())
Ok(crate::ticket::TicketPayload::Video(Texture::dummy()))
});
Job {
node_identity: tag,
@@ -358,6 +358,8 @@ mod tests {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
}),
produce,
done: Box::new(move |r| {
@@ -409,7 +411,7 @@ mod tests {
std::thread::sleep(Duration::from_millis(1));
}
}
Ok(Texture::dummy())
Ok(crate::ticket::TicketPayload::Video(Texture::dummy()))
});
let job = Job {
node_identity: i,
@@ -423,6 +425,8 @@ mod tests {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
}),
produce,
done: Box::new(move |r| {
@@ -463,7 +467,7 @@ mod tests {
let tx1 = tx.clone();
let tx2 = tx.clone();
let boom: Producer = Arc::new(|_, _| panic!("boom"));
let ok: Producer = Arc::new(|_, _| Ok(Texture::dummy()));
let ok: Producer = Arc::new(|_, _| Ok(crate::ticket::TicketPayload::Video(Texture::dummy())));
let params = Arc::new(VideoTicketParams {
viewer: 0,
time: Rational::new(0, 1),
@@ -473,6 +477,8 @@ mod tests {
cache_dir: None,
cache_id: None,
cache_timebase: None,
footage: None,
montage: Vec::new(),
});
pool.post(Job {
node_identity: 0,