workspace: kebab-case crates, app under crates/oak-app, shared versions
CI / Build & test (Windows) (push) Failing after 7s

All crates take the oak-* kebab-case naming (oak-audio, oak-codec,
oak-common, oak-core, oak-ffmpeg-link, oak-node, oak-otio, oak-plugin,
oak-render, oak-storage, oak-task, oak-timeline, oak-undo), with the
lib identifiers rewritten (oakrender:: -> oak_render::, oakcore_rs:: ->
oak_core::, ...) across all 226 referencing files.

The GUI application moves from the workspace root into
crates/oak-app/: src/, build.rs (paths fixed for the new location) and
tests/ travel with it, the root Cargo.toml becomes workspace-only
([workspace] + workspace.package + profiles), and the app package
inherits the workspace version. The screenshots example becomes a
standalone crate examples/simple_player/ with its own Cargo.toml.

Every crate now inherits the single workspace version
(version.workspace = true), and the workflows' crate paths and the
build docs follow the renames.

Validated with a clean cargo check --workspace.
This commit is contained in:
2026-08-22 16:58:37 +08:00
parent 7e2b3cb4b8
commit 244d5e860f
438 changed files with 2375 additions and 2309 deletions
+416
View File
@@ -0,0 +1,416 @@
// 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/>.
//! clip 实例:clip ↔ oakrender 纹理桥。
//!
//! 对应 C++ 的 `OliveClipInstance`。纹理数据经
//! [`crate::render`](oakrender 值类型:`Texture`/`Frame`)流动;
//! OFX 侧只看到 [`crate::image::Image`](CPU 路径)。
//!
//! `#[repr(C)]` + props 在偏移 0(句柄约定,见 [`crate::suites::tag`];
//! clip handle 即 `&props`)。
//!
//! 单库化后 oakrender 的 ffi 已删除:帧访问走
//! [`oak_render::texture::Texture::to_frame`] 值路径(GPU 纹理经后端
//! 下载、CPU 纹理克隆),帧释放随值 drop 自动发生(原
//! `texture_get_frame`/`frame_free` 句柄调用面随桩删除)。
use crate::instance::{OfxRangeD, OfxRectD, RenderScale};
use crate::property::PropertySet;
/// clip 实例。
#[repr(C)]
pub struct ClipInstance {
/// 实例级 clip 属性(当前分量/位深/像素比,协商结果写入;
/// 偏移 0,句柄约定)。
pub props: PropertySet,
/// clip 名。
pub name: String,
/// 当前输入纹理(oakrender 值;输出 clip 为 None)。
input_texture: std::sync::Mutex<Option<crate::render::Texture>>,
/// 当前输出纹理(C++ `output_textures_` 的 phase 1 单槽;
/// [`store_output_image`](Self::store_output_image) 的回写目标;
/// 输入 clip 为 None)。
output_texture: std::sync::Mutex<Option<crate::render::Texture>>,
}
/// 从 clip 属性读协商分量(getClipPreferences 写入)。
fn components_from_props(props: &PropertySet) -> Option<crate::image::Components> {
use crate::property::Value;
match props.get(crate::image::K_IMAGE_EFFECT_PROP_COMPONENTS, 0)? {
Value::String(s) => match s.to_string_lossy().as_ref() {
"OfxImageComponentRGBA" => Some(crate::image::Components::Rgba),
"OfxImageComponentRGB" => Some(crate::image::Components::Rgb),
"OfxImageComponentAlpha" => Some(crate::image::Components::Alpha),
_ => None,
},
_ => None,
}
}
/// IEEE 754 半精度 → 单精度(无 half 依赖,手写位转换;非规格数/
/// Inf/NaN 均按标准展开)。
fn f16_to_f32(bits: u16) -> f32 {
let sign = ((bits >> 15) & 1) as u32;
let exp = ((bits >> 10) & 0x1f) as u32;
let mant = (bits & 0x3ff) as u32;
let f32_bits = if exp == 0 {
if mant == 0 {
sign << 31
} else {
// 非规格数:规格化到 f32 指数域。
let mut m = mant;
let mut e: i32 = 127 - 15;
while m & 0x400 == 0 {
m <<= 1;
e -= 1;
}
let m = (m & 0x3ff) << 13;
(sign << 31) | (((e + 1) as u32) << 23) | m
}
} else if exp == 0x1f {
// Inf/NaN。
(sign << 31) | (0xff << 23) | (mant << 13)
} else {
(sign << 31) | ((exp + 127 - 15) << 23) | (mant << 13)
};
f32::from_bits(f32_bits)
}
impl ClipInstance {
/// 按描述符实例化(createInstance 路径调用;公开:宿主与测试
/// 都需要构造 clip 实例)。实例 props 是描述符 props 的深拷贝
/// (HS: ClipBase 的实例构造,ofxhClip.cpp:57-70——插件在实例期
/// 读 supported components 等)。
///
/// ofxColour(M11 §4):输入 clip 的 kOfxImageClipPropColourspace
/// 由宿主写为工作空间(ACEScg,ofxColour.h "Hosts should set this
/// property to the colourspace of the input clip. Typically it will
/// be set to the working colourspace");输出 clip 由
/// GetOutputColourspace action 后写。
pub fn from_descriptor(desc: &crate::descriptor::ClipDescriptor) -> Self {
let props = desc.props.clone();
let name = desc.name.clone();
if name != "Output" {
props.set_one(
crate::host::PROP_CLIP_COLOURSPACE,
crate::property::Value::String(
std::ffi::CString::new(crate::host::WORKING_COLOURSPACE).unwrap(),
),
);
}
Self {
props,
name,
input_texture: std::sync::Mutex::new(None),
output_texture: std::sync::Mutex::new(None),
}
}
/// 写协商后的像素格式(C++ `OliveClipInstance::setParams` 的 props
/// 侧:setPixelDepth/setComponents,oliveclip.cpp:700-709)。
/// `format` 为 olive::PixelFormat::Format(0=u8, 2=u16, 3=f16,
/// 4=f32);`channels` 为分量数。
pub fn set_video_params(&self, format: i32, channels: i32) {
let depth = match format {
0 => "OfxBitDepthByte",
2 => "OfxBitDepthShort",
3 => "OfxBitDepthHalf",
_ => "OfxBitDepthFloat",
};
let comps = match channels {
1 => "OfxImageComponentAlpha",
3 => "OfxImageComponentRGB",
_ => "OfxImageComponentRGBA",
};
self.props.set_one(
crate::image::K_IMAGE_EFFECT_PROP_PIXEL_DEPTH,
crate::property::Value::String(std::ffi::CString::new(depth).unwrap()),
);
self.props.set_one(
crate::image::K_IMAGE_EFFECT_PROP_COMPONENTS,
crate::property::Value::String(std::ffi::CString::new(comps).unwrap()),
);
}
/// 写协商 RoD(C++ `setRegionOfDefinition` 的单槽版,
/// oliveclip.cpp:674-678——C++ 按 time 存 map,本驱动一帧一槽;
/// 落点与 image effect suite 的 clipGetRegionOfDefinition 读取处
/// 一致)。
pub fn set_region_of_definition(&self, rod: OfxRectD, _time: f64) {
use crate::property::Value;
self.props.define(
"OfxImageEffectPropRegionOfDefinition",
vec![
Value::Double(rod.x1),
Value::Double(rod.y1),
Value::Double(rod.x2),
Value::Double(rod.y2),
],
);
}
/// 挂接输入纹理(oaknode 侧 clip 输入值变化时由 param/render 桥
/// 调用)。`time` 用于多帧纹理选择。None 断开。
pub fn set_input_texture(&self, texture: Option<crate::render::Texture>, _time: f64) {
*self.input_texture.lock().unwrap_or_else(|e| e.into_inner()) = texture;
}
/// 挂接输出纹理(render 驱动创建并经值传入;C++
/// `setOutputTexture` 的 phase 1 单槽版)。`time` 用于多帧纹理
/// 选择(`// [P2]`)。None 断开。
pub fn set_output_texture(&self, texture: Option<crate::render::Texture>, _time: f64) {
*self
.output_texture
.lock()
.unwrap_or_else(|e| e.into_inner()) = texture;
}
/// 抓取本 clip 在 `time` 的图像(OFX clipGetImage 的宿主侧)。
/// CPU 路径:把 oakrender 纹理 readback 成 [`crate::image::Image`]
/// (像素格式按协商结果,全链路 F32)。
/// `// [P2]` GL 路径:clipLoadTexture 语义在此扩展。
///
/// 输入帧支持 U8/U16/F16/F32:非 F32 归一化转换为 F32(对齐
/// oliveclip.cpp setInputTexture 的格式转换路径);转换中的
/// NaN/Inf 清洗为 0(oliveclip.cpp copy_pixels 的 scrub)。
/// `region` 只支持 None(整帧)——子区域随 renderer 桥落地。
pub fn fetch_image(
&self,
time: f64,
scale: RenderScale,
region: Option<OfxRectD>,
) -> crate::error::Result<crate::image::Image> {
use crate::render::PIXEL_FORMAT_F32;
use crate::error::Error;
let _ = (time, scale);
if region.is_some() {
return Err(Error::Failed("fetch_image 子区域第 1 期不支持".into()));
}
let texture = self
.input_texture
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
.ok_or(Error::NotFound)?;
// 占位纹理(dummy):视作无输入。
if texture.is_dummy() {
return Err(Error::NotFound);
}
// 纹理 → CPU 帧(GPU 纹理后端下载;帧随 drop 释放)。
let frame = crate::render::texture_get_frame(&texture)?;
let params = frame.video_params();
let format = params.format;
if format != PIXEL_FORMAT_F32
&& format != crate::render::PIXEL_FORMAT_U8
&& format != oak_core::PixelFormat::U16 as i32
&& format != oak_core::PixelFormat::F16 as i32
{
return Err(Error::Failed(format!(
"输入帧格式 {format} 不支持(仅 U8/U16/F16/F32)"
)));
}
let (w, h) = (params.width as f64, params.height as f64);
// 分量按协商结果(getClipPreferences 已写入 clip.props)。
let components =
components_from_props(&self.props).unwrap_or(crate::image::Components::Rgba);
let mut image = crate::image::Image::allocate(
crate::image::BitDepth::Float,
components,
OfxRectD {
x1: 0.0,
y1: 0.0,
x2: w,
y2: h,
},
);
let src = frame.data();
if src.is_null() {
return Err(Error::Failed("帧无数据".into()));
}
// 行优先 + 格式转换(帧行跨度经 linesize 读取——真实
// oakrender 帧可有行填充;目标 Image 恒紧凑 F32)。
// U8/U16/F16 输入归一化到 [0,1] 浮点(对齐 oliveclip.cpp
// setInputTexture 的 swscale 转换路径:插件侧永远见到协商位
// 深);F32/转换结果中的 NaN/Inf 清洗为 0(oliveclip.cpp
// copy_pixels 的 scrub——CImg 对 NaN 未定义行为)。
let channels = components.channel_count();
let samples_per_row = (w as usize) * channels;
let src_bpc = match format {
f if f == crate::render::PIXEL_FORMAT_U8 => 1,
f if f == oak_core::PixelFormat::U16 as i32 => 2,
f if f == oak_core::PixelFormat::F16 as i32 => 2,
_ => 4,
};
let tight_src = samples_per_row * src_bpc;
let row = frame.linesize_bytes();
let row = if row > 0 { row } else { tight_src };
let src_bytes = unsafe { std::slice::from_raw_parts(src, row * h as usize) };
let dst = image.pixels_mut();
let mut scrubbed = false;
for y in 0..h as usize {
let s = y * row;
for i in 0..samples_per_row {
let v = match format {
f if f == crate::render::PIXEL_FORMAT_U8 => {
src_bytes[s + i] as f32 / 255.0
}
f if f == oak_core::PixelFormat::U16 as i32 => {
let off = s + i * 2;
let bits = u16::from_le_bytes([src_bytes[off], src_bytes[off + 1]]);
bits as f32 / 65535.0
}
f if f == oak_core::PixelFormat::F16 as i32 => {
let off = s + i * 2;
let bits = u16::from_le_bytes([src_bytes[off], src_bytes[off + 1]]);
let v = f16_to_f32(bits);
if v.is_nan() || v.is_infinite() {
scrubbed = true;
0.0
} else {
v
}
}
_ => {
let off = s + i * 4;
let v = f32::from_le_bytes([
src_bytes[off],
src_bytes[off + 1],
src_bytes[off + 2],
src_bytes[off + 3],
]);
if v.is_nan() || v.is_infinite() {
scrubbed = true;
0.0
} else {
v
}
}
};
let d = (y * samples_per_row + i) * 4;
dst[d..d + 4].copy_from_slice(&v.to_le_bytes());
}
}
if scrubbed {
eprintln!("[PLUGIN] NaN/Inf scrubbed from input frame data during fetch");
}
Ok(image)
}
/// 把输出图像回写为 oakrender 纹理(render 完成后由
/// [`crate::instance::Instance::render`] 的调用方使用)。
///
/// 输出纹理由 oakrender 侧创建并经 [`Self::set_output_texture`]
/// 挂入——本函数取该纹理的 CPU 帧(GPU 纹理经后端下载,写回后
/// 对 `Texture::Gpu` 再经
/// [`oak_render::backend::GpuContextLike::upload`] 上传),按帧
/// 参数校验 F32 与尺寸后整帧拷贝图像像素(全链路 F32;C++
/// pluginrenderer 的 `readback/wrap` 路径第 1 期以 CPU 拷贝表达,
/// GL 走 [`crate::render`] 的 `// [P2]`)。未挂输出纹理
/// 或纹理为占位(dummy)→ [`crate::error::Error::NotFound`]。
/// 成功返回纹理值(克隆,随 drop 释放)。
pub fn store_output_image(
&self,
image: &crate::image::Image,
) -> crate::error::Result<crate::render::Texture> {
use crate::render::{texture_get_frame, PIXEL_FORMAT_F32};
use crate::error::Error;
let texture = self
.output_texture
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
.ok_or(Error::NotFound)?;
if texture.is_dummy() {
return Err(Error::NotFound);
}
let mut frame = texture_get_frame(&texture)?;
let params = frame.video_params();
if params.format != PIXEL_FORMAT_F32 {
return Err(Error::Failed(format!(
"输出帧格式 {} 非 F32(第 1 期约束)",
params.format
)));
}
let (w, h) = (params.width as usize, params.height as usize);
// 图像与帧必须同尺寸(全链路 F32;宽高/行宽/总长逐项校验)。
let tight = w * image.components().channel_count() * 4;
if tight != image.row_bytes() || tight * h != image.pixels().len() {
return Err(Error::Failed("图像尺寸与输出帧不一致".into()));
}
let dst = frame.data_mut();
if dst.is_null() {
return Err(Error::Failed("输出帧无数据".into()));
}
// 行优先拷贝(目标帧行跨度经 linesize 读取——真实 oakrender
// 帧可有行填充;M11 §4 修复同 fetch_image)。
let row = frame.linesize_bytes();
let row = if row > 0 { row } else { tight };
let dst_bytes = unsafe { std::slice::from_raw_parts_mut(dst, row * h) };
let pixels = image.pixels();
for y in 0..h {
let d = y * row;
let s = y * tight;
dst_bytes[d..d + tight].copy_from_slice(&pixels[s..s + tight]);
}
// GPU 目标纹理:拷贝只落在下载帧上,经后端 upload 回写
// (CPU 纹理无需上传)。
if let crate::render::Texture::Gpu { token, ctx, .. } = &texture {
ctx.upload(*token, &frame)
.map_err(|e| Error::Failed(format!("输出纹理上传失败:{e}")))?;
}
Ok(texture)
}
/// 本 clip 的时间域(clipGetFrameRange)。
///
/// `// TODO(value-model)`:输入范围经 oakrender 帧的时间基推导
/// (time_base)——随 clip 迁移到 `oak_render::texture::Texture`
/// 值模型落地。
pub fn frame_range(&self) -> crate::error::Result<OfxRangeD> {
let _ = OfxRangeD::default();
Err(crate::error::Error::Failed(
"frame_range 待 renderer 桥".into(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn f16_to_f32_covers_special_values() {
// 常规值:1.0 = 0x3C00,-2.0 = 0xC000,0.5 = 0x3800。
assert_eq!(f16_to_f32(0x3C00), 1.0);
assert_eq!(f16_to_f32(0xC000), -2.0);
assert_eq!(f16_to_f32(0x3800), 0.5);
// 零与负零。
assert_eq!(f16_to_f32(0x0000), 0.0);
assert_eq!(f16_to_f32(0x8000).to_bits(), (0.0f32).to_bits() | (1 << 31));
// 非规格数:最小正规格数 2^-14 ≈ 0.00006104;2^-24 是最小非
// 规格数之一。
assert!((f16_to_f32(0x0400) - 2f32.powi(-14)).abs() < 1e-12);
assert!((f16_to_f32(0x0001) - 2f32.powi(-24)).abs() < 1e-12);
// Inf/NaN。
assert!(f16_to_f32(0x7C00).is_infinite() && f16_to_f32(0x7C00) > 0.0);
assert!(f16_to_f32(0xFC00).is_infinite() && f16_to_f32(0xFC00) < 0.0);
assert!(f16_to_f32(0x7E00).is_nan());
}
}
+133
View File
@@ -0,0 +1,133 @@
// 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/>.
//! describe 的产物:效果描述符与 clip 描述符。
//!
//! 参照:HS: ofxhImageEffect.cpp `Descriptor`(describe action 期间
//! 插件可读写的属性容器)。
//!
//! 句柄约定([`crate::suites::tag`]):`props` 在偏移 0 且
//! `#[repr(C)]`;`params`/`clips` 元素装箱(Vec 重分配不移动对象)。
use std::ffi::CString;
use crate::param::ParamDef;
use crate::property::{PropertySet, Value};
fn cs(s: &str) -> CString {
CString::new(s).unwrap()
}
// ---- clip 描述符属性(ofxImageEffect.h / ofxCore.h)----
/// kOfxImageClipPropOptional。
pub(crate) const CLIP_OPTIONAL: &str = "OfxImageClipPropOptional";
/// kOfxImageClipPropIsMask。
pub(crate) const CLIP_IS_MASK: &str = "OfxImageClipPropIsMask";
/// kOfxImageClipPropFieldExtraction。
pub(crate) const CLIP_FIELD_EXTRACTION: &str = "OfxImageClipPropFieldExtraction";
/// kOfxImageEffectPropSupportedComponents。
pub(crate) const CLIP_SUPPORTED_COMPONENTS: &str = "OfxImageEffectPropSupportedComponents";
/// kOfxImageEffectPropTemporalClipAccess。
pub(crate) const CLIP_TEMPORAL_ACCESS: &str = "OfxImageEffectPropTemporalClipAccess";
/// kOfxImageEffectPropSupportsTiles。
pub(crate) const CLIP_SUPPORTS_TILES: &str = "OfxImageEffectPropSupportsTiles";
/// kOfxImageFieldDoubled(FieldExtraction 默认值)。
pub(crate) const CLIP_FIELD_DOUBLED: &str = "OfxImageFieldDoubled";
/// kOfxTypeClip。
pub(crate) const CLIP_TYPE: &str = "OfxTypeClip";
/// clip 描述符(describe 期间由插件定义)。
/// `#[repr(C)]` + props 在偏移 0(句柄约定;describe 期 clip handle
/// 即 &props,与实例期 [`crate::clip::ClipInstance`] 共用 CLIP 标签)。
#[repr(C)]
pub struct ClipDescriptor {
/// 描述属性:label、可选性(kOfxImageClipPropOptional)、支持分量
/// (kOfxImageEffectPropSupportedComponents)、field 支持等。
pub props: PropertySet,
/// clip 名(如 "Source"/"Output")。
pub name: String,
}
impl ClipDescriptor {
/// 按名构建(镜像 HS ofxhClip.cpp `ClipDescriptor::ClipDescriptor`
/// + clipDescriptorStuffs 属性表,ofxhClip.cpp:22-38)。公开:
/// 测试构造 clip 实例(GL suite 往返)。
pub fn new(name: &str) -> Self {
let props = PropertySet::new();
props.set_one(crate::param::PROP_TYPE, Value::String(cs(CLIP_TYPE)));
props.set_one(crate::param::PROP_NAME, Value::String(cs(name)));
props.set_one(crate::param::PROP_LABEL, Value::String(cs(name)));
props.set_one(crate::param::PROP_SHORT_LABEL, Value::String(cs("")));
props.set_one(crate::param::PROP_LONG_LABEL, Value::String(cs("")));
props.define(CLIP_SUPPORTED_COMPONENTS, vec![]);
props.set_one(CLIP_TEMPORAL_ACCESS, Value::Int(0));
props.set_one(CLIP_OPTIONAL, Value::Int(0));
props.set_one(CLIP_IS_MASK, Value::Int(0));
props.set_one(CLIP_FIELD_EXTRACTION, Value::String(cs(CLIP_FIELD_DOUBLED)));
props.set_one(CLIP_SUPPORTS_TILES, Value::Int(1));
// ofxColour(M11 §4):clip 色彩空间属性族。Colourspace 由宿主
// 在实例化时写入(输入 clip = 工作空间 ACEScg);Preferred 由
// 插件在 GetClipPreferences 写(宿主侧预置空数组)。
props.set_one(crate::host::PROP_CLIP_COLOURSPACE, Value::String(cs("")));
props.define(crate::host::PROP_CLIP_PREFERRED_COLOURSPACES, vec![]);
Self {
props,
name: name.to_string(),
}
}
}
/// 效果描述符。
/// `#[repr(C)]` + props 在偏移 0(句柄约定:describe 期 effect/
/// param-set handle 即 &props)。
#[repr(C)]
pub struct EffectDescriptor {
/// 效果级属性:label、描述、分组、单帧/时间域标记等。
pub props: PropertySet,
/// 参数定义集(describe 期间插件经 Param suite 填充;
/// 值类型见 [`crate::param::ParamDef`];Box 保证句柄地址稳定)。
pub params: Vec<Box<ParamDef>>,
/// clip 定义集(含 "Output";Box 保证句柄地址稳定)。
pub clips: Vec<Box<ClipDescriptor>>,
}
impl EffectDescriptor {
/// 空描述符(describe action 前由 host 创建并预置根属性)。
pub fn new() -> Self {
Self {
props: PropertySet::new(),
params: Vec::new(),
clips: Vec::new(),
}
}
/// 按名找 clip。
pub fn clip(&self, name: &str) -> Option<&ClipDescriptor> {
self.clips
.iter()
.find(|c| c.name == name)
.map(|b| b.as_ref())
}
/// 按名找参数定义。
pub fn param(&self, name: &str) -> Option<&ParamDef> {
self.params
.iter()
.find(|p| p.name == name)
.map(|b| b.as_ref())
}
}
+117
View File
@@ -0,0 +1,117 @@
// 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/>.
//! 错误码。与 `include/*/error.h` 逐字对应;项目统一 -MMCCCC 方案
//! (模块号注册表见 include/common/error.h),跨模块透传不翻译。
use thiserror::Error;
/// 成功。
pub const OAKPLUGIN_OK: i32 = 0;
/// 空句柄或非法参数。
pub const OAKPLUGIN_E_INVALID: i32 = -90001;
/// 当前状态不允许该调用(如未扫描就创建实例)。
pub const OAKPLUGIN_E_STATE: i32 = -90002;
/// 底层操作失败(OFX action 返回非 kOfxStatOK、插件入口拒绝等)。
pub const OAKPLUGIN_E_FAILED: i32 = -90003;
/// 索引越界 / 指定标识的插件不存在。
pub const OAKPLUGIN_E_NOT_FOUND: i32 = -90004;
/// 分配失败。
pub const OAKPLUGIN_E_NOMEM: i32 = -90005;
/// crate 内部统一的结果类型;FFI 层把它映射为上述 i32 码。
pub type Result<T> = std::result::Result<T, Error>;
/// crate 内部错误。`code()` 给出对外错误码。
#[derive(Debug, Error)]
pub enum Error {
/// 空句柄或非法参数。
#[error("plugin: invalid argument")]
Invalid,
/// 状态不允许。
#[error("plugin: call not valid in the current state")]
State,
/// 底层失败,附人类可读上下文(仅日志,不出界)。
#[error("plugin: operation failed: {0}")]
Failed(String),
/// 未找到。
#[error("plugin: not found")]
NotFound,
/// 分配失败。
#[error("plugin: out of memory")]
NoMem,
}
impl Error {
/// 映射为 `include/plugin/error.h` 的错误码。
pub fn code(&self) -> i32 {
match self {
Error::Invalid => OAKPLUGIN_E_INVALID,
Error::State => OAKPLUGIN_E_STATE,
Error::Failed(_) => OAKPLUGIN_E_FAILED,
Error::NotFound => OAKPLUGIN_E_NOT_FOUND,
Error::NoMem => OAKPLUGIN_E_NOMEM,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// One instance of every variant (data-carrying ones get a sample
/// payload).
fn all_errors() -> Vec<Error> {
vec![
Error::Invalid,
Error::State,
Error::Failed("boom".to_string()),
Error::NotFound,
Error::NoMem,
]
}
#[test]
fn display_is_non_empty_for_every_variant() {
for e in all_errors() {
let s = e.to_string();
assert!(!s.is_empty(), "Display produced an empty message for {e:?}");
}
}
#[test]
fn error_is_object_safe() {
// `Box<dyn std::error::Error>` must be constructible for every
// variant; `source()` stays None (no wrapped downstream error).
let errors: Vec<Box<dyn std::error::Error>> = all_errors()
.into_iter()
.map(|e| Box::new(e) as Box<dyn std::error::Error>)
.collect();
for e in &errors {
assert!(!e.to_string().is_empty());
assert!(e.source().is_none());
}
}
#[test]
fn code_is_unaffected_by_trait_impl() {
assert_eq!(Error::Invalid.code(), OAKPLUGIN_E_INVALID);
assert_eq!(Error::State.code(), OAKPLUGIN_E_STATE);
assert_eq!(Error::Failed("boom".to_string()).code(), OAKPLUGIN_E_FAILED);
assert_eq!(Error::NotFound.code(), OAKPLUGIN_E_NOT_FOUND);
assert_eq!(Error::NoMem.code(), OAKPLUGIN_E_NOMEM);
}
}
+996
View File
@@ -0,0 +1,996 @@
// 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/>.
//! GL 互操作桥(方案 B 落地:离屏 GL 上下文 + 纹理/FBO + 回读)。
//!
//! ## 背景(阶段 6a spike 结论,已落地)
//!
//! OFX 的 `OpenGLRender` 扩展要求宿主把 clip 纹理以 **GL 纹理名**
//! (`kOfxImageEffectPropOpenGLTextureIndex`)递给插件,插件直接画进
//! 输出纹理。oak 的渲染后端是 wgpu(macOS 为 Metal),Metal 与 GL
//! 纹理名之间没有共享命名空间(方案 A 不可行,详见 0.1 版的 spike
//! 文档)。本模块实现**方案 B**:
//!
//! ```text
//! 宿主自建原生离屏 GL 上下文(macOS = CGL)
//! → 为每帧建输出 GL 纹理 + FBO(插件 render 画进附着纹理)
//! → 插件经 GL suite 取到真实纹理名(OpenGLTextureIndex)
//! → render 返回后 glReadPixels 回读为 CPU 帧
//! → 按目标帧格式转换(F32/RGBA8)装帧
//! ```
//!
//! 渲染跑在 oak-worker 进程内(M15 进程隔离),GL 上下文在 worker
//! 进程内创建即可;主进程无需 GL。
//!
//! ## 上下文生命周期与线程模型
//!
//! - **进程级共享单例**:`OnceLock` 惰性创建(`imp::context`),一次
//! 创建、整个进程共用(CGL 上下文可在任意线程置为 current,但不能
//! 同时)。
//! - **串行化**:[`acquire`] 取全局 `Mutex` 并把上下文置为当前线程
//! current;返回 [`GlGuard`],drop 时清 current 并放锁。OFX 插件
//! 渲染已由实例锁(`Instance::render_lock`)串行化,但不同实例可在
//! 不同线程渲染——GL 侧必须再串行一次,保证同一时刻只有一条线程
//! 持有 current 上下文。
//! - **current 的跨调用保持**:ofxGPURender.h 要求宿主在 Render/
//! Begin/EndSequenceRender 期间让上下文保持 current(插件在 suite
//! 调用之间直接发 GL 命令)。因此 render 驱动**一次** acquire 整个
//! render action(含 suite 回调),[`GlGuard`] 跨整个 action 持有;
//! 本模块其余函数假定上下文已 current(guard 已持有),不再加锁。
//! - **同线程可重入**:[`acquire`] 在同一线程已持外层 guard 时只递增
//! 线程局部嵌套深度(上下文已 current,不重取锁);最外层 guard
//! drop 时才清 current 放锁。interact draw 的宿主测试需要"一次
//! acquire 覆盖 FBO 装配 → 插件绘制 → 回读"而 `Interact::draw`
//! 内部又要自行 acquire(宿主侧每次 action 前都要保证 current)——
//! 嵌套 acquire 免去死锁。
//! - **清理**:进程退出时 `OnceLock` 里的 [`GlContext`] drop,销毁
//! CGL 上下文与像素格式。
//!
//! ## 平台
//!
//! - **macOS(真实实现)**:Core OpenGL(`OpenGL.framework`,
//! `#[link(name = "OpenGL", kind = "framework")]`,无需新 crate)。
//! 像素格式:3.2 core profile、offline renderer 允许(无 GPU 的无头
//! 环境可回退软件渲染)、24 位颜色 + 8 位 alpha。离屏渲染(FBO)
//! 无需 drawable,不 swap buffer。
//! - **Linux(预留 EGL)**:`cfg(target_os = "linux")` 走 stub,全部
//! 返回失败/`false`(use_opengl 决策据此回退 CPU)。接线点:
//! `imp` 换成 EGL(`eglGetDisplay/eglCreateContext` + GLES3),
//! FFI 同构,GL 命令一致。
//! - **Windows(预留 WGL)**:同理,stub。接线点:`wglCreateContext`
//! + `wglMakeCurrent`,FFI 同构。
//!
//! ## 回读格式转换(真实正确)
//!
//! 输出 GL 纹理的内部格式按目标帧格式选择(管线 F32 → `GL_RGBA32F`,
//! U8 目标 → `GL_RGBA8`)。`glReadPixels` 按纹理类型回读(`GL_FLOAT`
//! 或 `GL_UNSIGNED_BYTE`),垂直翻转(GL 原点左下 vs 帧缓冲原点左上),
//! U8 按 `v/255.0` 归一化到 F32——与 CPU 路径输出格式(F32 RGBA)
//! 一致,经 `write_output_frame` 装配。
use std::sync::Arc;
use crate::image::Image;
use crate::render::VideoParams;
// ---- 对外 API(平台无关签名;实现按平台 cfg 分派)----------------------
/// GL 上下文是否可用(离屏上下文可创建)。use_opengl 决策用它当
/// "目标纹理有有效 GL 名" 的门:桥能为目标帧建出真实 GL 纹理 ⟺
/// 上下文可用。惰性创建,幂等。
pub fn gl_available() -> bool {
imp::gl_available()
}
/// 取得进程级 GL 上下文并把本线程置为 current(全局串行)。
/// 返回的 guard 在 drop 时清 current 并放锁。失败(无 GL / 上下文
/// 创建失败)→ 调用方回退 CPU。
pub fn acquire() -> crate::error::Result<GlGuard> {
imp::acquire()
}
/// 创建输出 GL 纹理(尺寸 = 目标帧,内部格式按 `params.format`:
/// F32 → RGBA32F,U8 → RGBA8),返回真实 GL 纹理名。
///
/// # Safety
///
/// 要求 GL 上下文已 current([`GlGuard`] 持有期间调用)。
pub fn create_output_texture(w: i32, h: i32, params: &VideoParams) -> crate::error::Result<i32> {
imp::create_output_texture(w, h, params)
}
/// 创建输入 GL 纹理(RGBA32F)并把 F32 像素数据上传,返回真实 GL
/// 纹理名。`pixels` 必须为 `w*h*4*4` 字节(紧凑 RGBA F32,行优先)。
///
/// # Safety
///
/// 要求 GL 上下文已 current([`GlGuard`] 持有期间调用)。
pub fn create_input_texture(w: i32, h: i32, pixels: &[u8]) -> crate::error::Result<i32> {
imp::create_input_texture(w, h, pixels)
}
/// 删除 GL 纹理。
///
/// # Safety
///
/// 要求 GL 上下文已 current。
pub fn delete_gl_texture(name: i32) {
imp::delete_gl_texture(name);
}
/// 创建 FBO 并把 `tex` 挂为颜色附件(绑定并校验完整性)。
/// 返回 FBO 名(当前已绑定)。失败时已清理。
///
/// # Safety
///
/// 要求 GL 上下文已 current。
pub fn create_fbo(tex: i32, w: i32, h: i32) -> crate::error::Result<i32> {
imp::create_fbo(tex, w, h)
}
/// 绑定 FBO(0 = 系统帧缓冲)。
///
/// # Safety
///
/// 要求 GL 上下文已 current。
pub fn bind_fbo(fbo: i32) {
imp::bind_fbo(fbo);
}
/// 删除 FBO。
///
/// # Safety
///
/// 要求 GL 上下文已 current。
pub fn delete_fbo(fbo: i32) {
imp::delete_fbo(fbo);
}
/// 设置视口(像素坐标)。
///
/// # Safety
///
/// 要求 GL 上下文已 current。
pub fn set_viewport(w: i32, h: i32) {
imp::set_viewport(w, h);
}
/// 回读当前绑定 FBO 并装配成 F32 RGBA 图像(垂直翻转、U8 归一化)。
/// 返回的 Image 与 CPU 路径输出格式一致,可直接交
/// [`crate::render_driver::write_output_frame`]。
///
/// # Safety
///
/// 要求 GL 上下文已 current、目标 FBO 仍绑定。
pub fn read_pixels_to_image(w: i32, h: i32, params: &VideoParams) -> crate::error::Result<Arc<Image>> {
imp::read_pixels_to_image(w, h, params)
}
/// 设置 clear 颜色(FBO 测试/失败紫屏用)。
///
/// # Safety
///
/// 要求 GL 上下文已 current。
pub fn gl_clear_color(r: f32, g: f32, b: f32, a: f32) {
imp::gl_clear_color(r, g, b, a);
}
/// 清除颜色缓冲(FBO 测试用;插件正常路径自行发 GL 命令)。
///
/// # Safety
///
/// 要求 GL 上下文已 current。
pub fn gl_clear() {
imp::gl_clear();
}
/// 当前 GL 实现的版本串(真实上下文证据;测试用)。
pub fn gl_version_string() -> Option<String> {
imp::gl_version_string()
}
/// GL 上下文句柄(持有全局锁 + 上下文 current;drop 时清 current 放锁)。
pub struct GlGuard {
_inner: imp::GuardInner,
}
/// 当前线程是否持有 GL current(嵌套 guard 内也算;[`acquire`] 成功
/// 后为 true)。无 GL 的调用方(Draw suite 在 draw action 外被调)据此
/// 不触 GL 命令——macOS 无 current 上下文时调 GL 是未定义行为。
pub fn is_current() -> bool {
imp::is_current()
}
// ---- 平台实现 ----------------------------------------------------------
#[cfg(target_os = "macos")]
mod imp {
use super::*;
use crate::image::{BitDepth, Components};
use std::ffi::{c_char, c_void};
use std::sync::{Arc, Mutex, OnceLock};
// ---- OpenGL 常量(GL 规范值,非 OFX 宏)----
const GL_TEXTURE_2D: u32 = 0x0DE1;
const GL_RGBA: u32 = 0x1908;
const GL_UNSIGNED_BYTE: u32 = 0x1401;
const GL_FLOAT: u32 = 0x1406;
const GL_RGBA32F: u32 = 0x8814;
const GL_RGBA8: u32 = 0x8058;
const GL_TEXTURE_MIN_FILTER: u32 = 0x2801;
const GL_TEXTURE_MAG_FILTER: u32 = 0x2800;
const GL_NEAREST: u32 = 0x2600;
const GL_TEXTURE_WRAP_S: u32 = 0x2802;
const GL_TEXTURE_WRAP_T: u32 = 0x2803;
const GL_CLAMP_TO_EDGE: u32 = 0x812F;
const GL_FRAMEBUFFER: u32 = 0x8D40;
const GL_COLOR_ATTACHMENT0: u32 = 0x8CE0;
const GL_FRAMEBUFFER_COMPLETE: u32 = 0x8CD5;
const GL_COLOR_BUFFER_BIT: u32 = 0x4000;
const GL_PACK_ALIGNMENT: u32 = 0x0D05;
const GL_UNPACK_ALIGNMENT: u32 = 0x0CF5;
const GL_VERSION: u32 = 0x1F02;
const GL_NO_ERROR: u32 = 0;
// CGL 像素格式属性(CGLPixelFormatAttribute,CGL.h)。
const K_CGL_PFA_OPENGL_PROFILE: i32 = 99;
const K_CGLOGLP_VERSION_3_2_CORE: i32 = 0x3200;
const K_CGL_PFA_ALLOW_OFFLINE_RENDERERS: i32 = 96;
const K_CGL_PFA_COLOR_SIZE: i32 = 8;
const K_CGL_PFA_ALPHA_SIZE: i32 = 11;
/// macOS:CGL + OpenGL 的 FFI 声明(直接链接 OpenGL.framework)。
///
/// # Safety
///
/// 全部是系统 framework 导出函数;指针参数语义见各函数注释。
/// CGL* 类型用 `*mut c_void` 表示不透明对象指针(CGLContextObj /
/// CGLPixelFormatObj)。
#[link(name = "OpenGL", kind = "framework")]
unsafe extern "C" {
/// 按属性列表选像素格式(成功返回 kCGLNoError=0;`npix` 是
/// CGL 要求返回的像素格式计数,本桥只取格式对象,可丢弃——
/// 但实参必须给足,否则是未定义行为)。
fn CGLChoosePixelFormat(attrs: *const i32, pix: *mut *mut c_void, npix: *mut i32) -> i32;
/// 建上下文(share = NULL 无共享组)。返回 kCGLNoError=0。
fn CGLCreateContext(pix: *mut c_void, share: *mut c_void, ctx: *mut *mut c_void) -> i32;
fn CGLDestroyPixelFormat(pix: *mut c_void);
fn CGLDestroyContext(ctx: *mut c_void);
/// 置为当前线程的 current 上下文(NULL = 清)。返回 kCGLNoError=0。
fn CGLSetCurrentContext(ctx: *mut c_void) -> i32;
fn glGenTextures(n: i32, textures: *mut u32);
fn glDeleteTextures(n: i32, textures: *const u32);
fn glBindTexture(target: u32, texture: u32);
fn glTexParameteri(target: u32, pname: u32, param: i32);
fn glPixelStorei(pname: u32, param: i32);
/// 分配/上传 2D 纹理图像。`pixels` 为 NULL 时只分配。
fn glTexImage2D(
target: u32,
level: i32,
internalformat: i32,
width: i32,
height: i32,
border: i32,
format: u32,
type_: u32,
pixels: *const c_void,
);
fn glGenFramebuffers(n: i32, framebuffers: *mut u32);
fn glDeleteFramebuffers(n: i32, framebuffers: *const u32);
fn glBindFramebuffer(target: u32, framebuffer: u32);
fn glFramebufferTexture2D(target: u32, attachment: u32, textarget: u32, texture: u32, level: i32);
fn glCheckFramebufferStatus(target: u32) -> u32;
fn glViewport(x: i32, y: i32, width: i32, height: i32);
fn glClearColor(r: f32, g: f32, b: f32, a: f32);
fn glClear(mask: u32);
fn glReadPixels(
x: i32,
y: i32,
width: i32,
height: i32,
format: u32,
type_: u32,
pixels: *mut c_void,
);
fn glGetError() -> u32;
/// 返回当前上下文的信息字符串(非空 = 上下文真实可用)。
fn glGetString(name: u32) -> *const c_char;
}
/// CGL 上下文单例(OnceLock 惰性创建;Send+Sync 见下)。
pub struct GlContext {
ctx: *mut c_void,
pixel_format: *mut c_void,
}
// SAFETY: CGL 上下文对象可在任意线程经 CGLSetCurrentContext 置为
// current,但不能同时被两条线程使用——本模块用全局 Mutex 串行化
// 一切置 current 与 GL 调用,指针只在线程间传递(Arc 共享)而从不
// 并发解引用;Drop 只在进程退出(单线程)执行。Send/Sync 因此安全。
unsafe impl Send for GlContext {}
unsafe impl Sync for GlContext {}
impl Drop for GlContext {
fn drop(&mut self) {
// SAFETY: 进程退出期单线程;先清 current 再销毁对象,顺序
// 满足 CGL 文档(context 必须先取消 current 再 destroy)。
unsafe {
CGLSetCurrentContext(std::ptr::null_mut());
if !self.ctx.is_null() {
CGLDestroyContext(self.ctx);
}
if !self.pixel_format.is_null() {
CGLDestroyPixelFormat(self.pixel_format);
}
}
}
}
static GL_CONTEXT: OnceLock<Result<Arc<GlContext>, String>> = OnceLock::new();
/// GL 全局串行锁:同一时刻只有一条线程把共享上下文置为 current。
static GL_LOCK: Mutex<()> = Mutex::new(());
fn lock() -> std::sync::MutexGuard<'static, ()> {
GL_LOCK.lock().unwrap_or_else(|e| e.into_inner())
}
fn err(msg: &str) -> crate::error::Error {
crate::error::Error::Failed(format!("gl_bridge: {msg}"))
}
/// 惰性创建进程级 CGL 上下文(幂等)。
fn context() -> crate::error::Result<&'static Arc<GlContext>> {
let res = GL_CONTEXT.get_or_init(create_context);
match res {
Ok(c) => Ok(c),
Err(e) => Err(err(&format!("CGL 上下文创建失败:{e}"))),
}
}
fn create_context() -> Result<Arc<GlContext>, String> {
// SAFETY: CGLChoosePixelFormat 把像素格式对象写入 pix;属性表
// 以 0 结尾(kCGLPFAOpenGLProfile 之后是 profile 值、kCGLPFA
// AllowOfflineRenderers 后跟 1;见 CGL.h 的 attr 配对约定)。
let attrs = [
K_CGL_PFA_OPENGL_PROFILE,
K_CGLOGLP_VERSION_3_2_CORE,
K_CGL_PFA_ALLOW_OFFLINE_RENDERERS,
1,
K_CGL_PFA_COLOR_SIZE,
24,
K_CGL_PFA_ALPHA_SIZE,
8,
0,
];
unsafe {
let mut pix: *mut c_void = std::ptr::null_mut();
// npix 是 CGL 的 out 参数(像素格式计数);本桥不需要,但
// 必须给足实参(CGL 会写它)。
let mut npix: i32 = 0;
let st = CGLChoosePixelFormat(attrs.as_ptr(), &mut pix, &mut npix);
if st != 0 || pix.is_null() {
return Err(format!("CGLChoosePixelFormat 失败:{st}"));
}
let mut ctx: *mut c_void = std::ptr::null_mut();
// share = NULL:无共享组(本进程唯一 GL 使用方,无需与其他
// 上下文共享命名空间)。
let st = CGLCreateContext(pix, std::ptr::null_mut(), &mut ctx);
if st != 0 || ctx.is_null() {
CGLDestroyPixelFormat(pix);
return Err(format!("CGLCreateContext 失败:{st}"));
}
Ok(Arc::new(GlContext { ctx, pixel_format: pix }))
}
}
/// guard 持有期:全局锁 + 上下文 current。
pub struct GuardInner {
/// 最外层 guard 持有全局锁;同线程嵌套 guard 为 None(只递增
/// 深度,见 [`acquire`])。
_lock: Option<std::sync::MutexGuard<'static, ()>>,
_ctx: Arc<GlContext>,
}
/// 当前线程的 acquire 嵌套深度。>0 = 本线程已持外层 guard(上下文
/// 已 current);嵌套 acquire 只递增深度,不重取锁。
thread_local! {
static ACQUIRE_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
pub fn is_current() -> bool {
ACQUIRE_DEPTH.with(|d| d.get() > 0)
}
pub fn acquire() -> crate::error::Result<GlGuard> {
let ctx = context()?.clone();
let depth = ACQUIRE_DEPTH.with(|d| d.get());
if depth > 0 {
// 嵌套:上下文已 current(外层 guard 持有期),只递增深度。
ACQUIRE_DEPTH.with(|d| d.set(depth + 1));
return Ok(GlGuard {
_inner: GuardInner {
_lock: None,
_ctx: ctx,
},
});
}
let guard = lock();
// SAFETY: ctx 是有效 CGLContextObj;置 current 后本线程可发 GL
// 命令。失败返回非 0。
let st = unsafe { CGLSetCurrentContext(ctx.ctx) };
if st != 0 {
drop(guard);
return Err(err(&format!("CGLSetCurrentContext 失败:{st}")));
}
ACQUIRE_DEPTH.with(|d| d.set(1));
Ok(GlGuard {
_inner: GuardInner {
_lock: Some(guard),
_ctx: ctx,
},
})
}
impl Drop for GuardInner {
fn drop(&mut self) {
let depth = ACQUIRE_DEPTH.with(|d| d.get());
if depth <= 1 {
// 最外层:清 current(NULL)并释放全局锁。LIFO 栈纪律
// 保证外层 drop 前所有嵌套 guard 已 drop(深度归 1),
// 故 _lock 必为 Some。
ACQUIRE_DEPTH.with(|d| d.set(0));
// SAFETY: 清 current(NULL)后放锁;见模块文档的线程模型。
unsafe {
CGLSetCurrentContext(std::ptr::null_mut());
}
drop(self._lock.take());
} else {
// 嵌套 guard drop:只递减深度,不清 current/不放锁。
ACQUIRE_DEPTH.with(|d| d.set(depth - 1));
}
}
}
pub fn gl_available() -> bool {
context().is_ok()
}
/// GL 错误检查(测试断言用;返回最近错误或 GL_NO_ERROR)。
fn check_error(what: &str) -> crate::error::Result<()> {
// SAFETY: glGetError 无参数,读取当前上下文的错误状态。
let e = unsafe { glGetError() };
if e != GL_NO_ERROR {
Err(err(&format!("{what} 失败:GL error 0x{e:x}")))
} else {
Ok(())
}
}
/// 目标帧格式 → 输出 GL 纹理格式。
/// 返回 (internal format, readback type, bytes per channel)。
fn gl_texture_format(params: &VideoParams) -> crate::error::Result<(u32, u32, usize)> {
match params.format {
f if f == crate::render::PIXEL_FORMAT_F32 => Ok((GL_RGBA32F, GL_FLOAT, 4)),
f if f == crate::render::PIXEL_FORMAT_U8 => Ok((GL_RGBA8, GL_UNSIGNED_BYTE, 1)),
f => Err(err(&format!(
"目标帧格式 {f} 不支持 GL 输出(仅 F32/U8)"
))),
}
}
/// 建纹理并设采样参数(FBO 完整性要求非 mipmap 的 min filter 与
/// clamp-to-edge)。
fn new_texture(w: i32, h: i32, internal: u32) -> crate::error::Result<u32> {
if w <= 0 || h <= 0 {
return Err(err("纹理尺寸非法"));
}
unsafe {
let mut tex: u32 = 0;
glGenTextures(1, &mut tex);
if tex == 0 {
return Err(err("glGenTextures 失败"));
}
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST as i32);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST as i32);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE as i32);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE as i32);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// internalformat 是 GLenum(无符号);C 签名里 glTexImage2D
// 的 internalformat 实为 GLint——此处值 < 2^31 安全。
glTexImage2D(
GL_TEXTURE_2D,
0,
internal as i32,
w,
h,
0,
GL_RGBA,
GL_FLOAT,
std::ptr::null(),
);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glBindTexture(GL_TEXTURE_2D, 0);
check_error("glTexImage2D")?;
Ok(tex)
}
}
pub fn create_output_texture(
w: i32,
h: i32,
params: &VideoParams,
) -> crate::error::Result<i32> {
let (internal, _, _) = gl_texture_format(params)?;
new_texture(w, h, internal).map(|t| t as i32)
}
pub fn create_input_texture(w: i32, h: i32, pixels: &[u8]) -> crate::error::Result<i32> {
let tex = new_texture(w, h, GL_RGBA32F)?;
// 上传 F32 RGBA 像素(紧凑,行优先;先确保 unpack alignment=1)。
let expected = (w as usize) * (h as usize) * 4 * 4;
if pixels.len() != expected {
let _ = delete_gl_texture(tex as i32);
return Err(err(&format!(
"输入像素长度 {} 与 w*h*4*4={expected} 不符",
pixels.len()
)));
}
unsafe {
glBindTexture(GL_TEXTURE_2D, tex);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA32F as i32,
w,
h,
0,
GL_RGBA,
GL_FLOAT,
pixels.as_ptr() as *const c_void,
);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glBindTexture(GL_TEXTURE_2D, 0);
}
check_error("输入纹理上传")?;
Ok(tex as i32)
}
pub fn delete_gl_texture(name: i32) {
if name <= 0 {
return;
}
// SAFETY: name 是之前 glGenTextures 产出的纹理名;删除后不可
// 再用(本桥保证不再引用)。要求上下文 current。
unsafe {
let t = name as u32;
glDeleteTextures(1, &t);
}
}
pub fn create_fbo(tex: i32, _w: i32, _h: i32) -> crate::error::Result<i32> {
if tex <= 0 {
return Err(err("FBO 附着纹理无效"));
}
unsafe {
let mut fbo: u32 = 0;
glGenFramebuffers(1, &mut fbo);
if fbo == 0 {
return Err(err("glGenFramebuffers 失败"));
}
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(
GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
tex as u32,
0,
);
let status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if status != GL_FRAMEBUFFER_COMPLETE {
glDeleteFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return Err(err(&format!("FBO 不完整:0x{status:x}")));
}
Ok(fbo as i32)
}
}
pub fn bind_fbo(fbo: i32) {
// SAFETY: 绑定 0(系统帧缓冲)或本桥创建的 FBO 名。
unsafe {
glBindFramebuffer(GL_FRAMEBUFFER, fbo as u32);
}
}
pub fn delete_fbo(fbo: i32) {
if fbo <= 0 {
return;
}
// SAFETY: fbo 是本桥 glGenFramebuffers 的产物;删除前先解除绑定。
unsafe {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
let f = fbo as u32;
glDeleteFramebuffers(1, &f);
}
}
pub fn set_viewport(w: i32, h: i32) {
// SAFETY: 视口是 GL 上下文状态,直接写。
unsafe {
glViewport(0, 0, w, h);
}
}
/// 回读原始像素(紧凑、行优先、GL 原点左下)。
fn read_pixels(w: i32, h: i32, format: u32, type_: u32, bpc: usize) -> crate::error::Result<Vec<u8>> {
let size = (w as usize) * (h as usize) * 4 * bpc;
let mut buf = vec![0u8; size];
unsafe {
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, w, h, format, type_, buf.as_mut_ptr() as *mut c_void);
glPixelStorei(GL_PACK_ALIGNMENT, 4);
}
check_error("glReadPixels")?;
Ok(buf)
}
pub fn read_pixels_to_image(
w: i32,
h: i32,
params: &VideoParams,
) -> crate::error::Result<Arc<Image>> {
let (_, gl_type, bpc) = gl_texture_format(params)?;
let raw = read_pixels(w, h, GL_RGBA, gl_type, bpc)?;
let (w, h) = (w as usize, h as usize);
let mut img = Image::allocate(
BitDepth::Float,
Components::Rgba,
crate::instance::OfxRectD {
x1: 0.0,
y1: 0.0,
x2: w as f64,
y2: h as f64,
},
);
let dst = img.pixels_mut();
let src_row = w * 4 * bpc;
let dst_row = w * 4 * 4;
for y in 0..h {
// 垂直翻转:GL 读回原点在左下,帧缓冲原点在左上。
let src_y = h - 1 - y;
let src = &raw[src_y * src_row..(src_y + 1) * src_row];
let d = &mut dst[y * dst_row..(y + 1) * dst_row];
for x in 0..w {
let (r, g, b, a): (f32, f32, f32, f32) = if bpc == 4 {
let p = &src[x * 16..x * 16 + 16];
(
f32::from_ne_bytes(p[0..4].try_into().unwrap()),
f32::from_ne_bytes(p[4..8].try_into().unwrap()),
f32::from_ne_bytes(p[8..12].try_into().unwrap()),
f32::from_ne_bytes(p[12..16].try_into().unwrap()),
)
} else {
let p = &src[x * 4..x * 4 + 4];
(
p[0] as f32 / 255.0,
p[1] as f32 / 255.0,
p[2] as f32 / 255.0,
p[3] as f32 / 255.0,
)
};
let o = x * 16;
d[o..o + 4].copy_from_slice(&r.to_ne_bytes());
d[o + 4..o + 8].copy_from_slice(&g.to_ne_bytes());
d[o + 8..o + 12].copy_from_slice(&b.to_ne_bytes());
d[o + 12..o + 16].copy_from_slice(&a.to_ne_bytes());
}
}
Ok(Arc::new(img))
}
pub fn gl_clear_color(r: f32, g: f32, b: f32, a: f32) {
// SAFETY: 写当前上下文的 clear 颜色状态。
unsafe {
glClearColor(r, g, b, a);
}
}
pub fn gl_clear() {
// SAFETY: 清除当前绑定帧缓冲的颜色缓冲。
unsafe {
glClear(GL_COLOR_BUFFER_BIT);
}
}
pub fn gl_version_string() -> Option<String> {
// SAFETY: glGetString 返回当前上下文内驻字符串;拷贝成 Rust
// String 后再返回,不持指针。
unsafe {
let p = glGetString(GL_VERSION);
if p.is_null() {
None
} else {
Some(std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned())
}
}
}
}
/// 非 macOS:GL 桥 stub(Linux 预留 EGL、Windows 预留 WGL 的接线点;
/// 全部失败/false,use_opengl 决策回退 CPU)。
#[cfg(not(target_os = "macos"))]
mod imp {
use super::*;
/// Linux 接线点:替换为 EGL(eglGetDisplay → eglInitialize →
/// eglChooseConfig → eglCreateContext → eglMakeCurrent);Windows
/// 替换为 WGL(wglCreateContext/wglMakeCurrent)。签名与 macOS
/// 实现同构。
pub struct GuardInner;
pub fn gl_available() -> bool {
false
}
pub fn is_current() -> bool {
false
}
pub fn acquire() -> crate::error::Result<GlGuard> {
Err(crate::error::Error::Failed("gl_bridge: 平台无 GL 实现(Linux/Windows stub)".into()))
}
pub fn create_output_texture(_w: i32, _h: i32, _p: &VideoParams) -> crate::error::Result<i32> {
Err(crate::error::Error::Failed("gl_bridge: 平台无 GL 实现".into()))
}
pub fn create_input_texture(_w: i32, _h: i32, _p: &[u8]) -> crate::error::Result<i32> {
Err(crate::error::Error::Failed("gl_bridge: 平台无 GL 实现".into()))
}
pub fn delete_gl_texture(_name: i32) {}
pub fn create_fbo(_tex: i32, _w: i32, _h: i32) -> crate::error::Result<i32> {
Err(crate::error::Error::Failed("gl_bridge: 平台无 GL 实现".into()))
}
pub fn bind_fbo(_fbo: i32) {}
pub fn delete_fbo(_fbo: i32) {}
pub fn set_viewport(_w: i32, _h: i32) {}
pub fn read_pixels_to_image(
_w: i32,
_h: i32,
_p: &VideoParams,
) -> crate::error::Result<Arc<Image>> {
Err(crate::error::Error::Failed("gl_bridge: 平台无 GL 实现".into()))
}
pub fn gl_clear_color(_r: f32, _g: f32, _b: f32, _a: f32) {}
pub fn gl_clear() {}
pub fn gl_version_string() -> Option<String> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::image::{BitDepth, Components};
use crate::render::VideoParams;
/// GL 不可用时 skip(无 GPU 无头环境);可用时返回 guard。
fn maybe_gl() -> Option<GlGuard> {
match acquire() {
Ok(g) => Some(g),
Err(e) => {
println!("SKIP: GL 上下文不可用:{e}");
None
}
}
}
fn f32_params(w: i32, h: i32) -> VideoParams {
let mut p = VideoParams::default();
p.width = w;
p.height = h;
p.format = crate::render::PIXEL_FORMAT_F32;
p
}
fn u8_params(w: i32, h: i32) -> VideoParams {
let mut p = VideoParams::default();
p.width = w;
p.height = h;
p.format = crate::render::PIXEL_FORMAT_U8;
p
}
/// 真实 GL 上下文证据:acquire 后能取到非空版本串。
#[test]
fn gl_context_is_real() {
let Some(_g) = maybe_gl() else {
return;
};
let v = gl_version_string();
assert!(v.is_some(), "真实 CGL 上下文应返回 GL_VERSION");
let v = v.unwrap();
// macOS 上 Apple 的 OpenGL 实现构建于 Metal 之上,GL_VERSION
// 形如 "4.1 Metal - 90.5"(无头/有头皆然)——只断言非空。
assert!(!v.trim().is_empty(), "GL_VERSION 应非空,got {v:?}");
assert!(gl_available(), "上下文可用后 gl_available 应为 true");
}
/// 上下文单例与跨线程 current 串行:两条线程轮流 acquire 都能
/// 拿到真实上下文(不崩、版本一致)。
#[test]
fn gl_context_thread_serialized() {
let mut handles = Vec::new();
for _ in 0..4 {
handles.push(std::thread::spawn(|| {
let Some(_g) = maybe_gl() else {
return;
};
let v = gl_version_string().unwrap_or_default();
assert!(!v.is_empty());
}));
}
for h in handles {
h.join().unwrap();
}
}
/// 输出纹理 + FBO + clear + 回读 round-trip(F32 目标):clear 到
/// 已知颜色 → glReadPixels 读回,逐像素断言。
#[test]
fn fbo_clear_readback_f32() {
let Some(_g) = maybe_gl() else {
return;
};
let (w, h) = (4i32, 2i32);
let params = f32_params(w, h);
let tex = create_output_texture(w, h, &params).expect("输出纹理应可建");
assert!(tex > 0, "GL 纹理名必须为真实非零 GL 名,got {tex}");
let fbo = create_fbo(tex, w, h).expect("FBO 应完整");
bind_fbo(fbo);
set_viewport(w, h);
gl_clear_color(0.1, 0.2, 0.3, 1.0);
gl_clear();
let img = read_pixels_to_image(w, h, &params).expect("回读应成功");
delete_fbo(fbo);
delete_gl_texture(tex);
assert_eq!(img.components(), Components::Rgba);
assert_eq!(img.depth(), BitDepth::Float);
assert_eq!(img.bounds().x2, w as f64);
assert_eq!(img.bounds().y2, h as f64);
let px = &img.pixels()[0..16];
let px_f: Vec<f32> = px.chunks_exact(4).map(|c| f32::from_ne_bytes(c.try_into().unwrap())).collect();
assert!((px_f[0] - 0.1).abs() < 1e-6, "R={}", px_f[0]);
assert!((px_f[1] - 0.2).abs() < 1e-6, "G={}", px_f[1]);
assert!((px_f[2] - 0.3).abs() < 1e-6, "B={}", px_f[2]);
assert!((px_f[3] - 1.0).abs() < 1e-6, "A={}", px_f[3]);
// 整帧同色(clear 覆盖全 FBO)。
let all: Vec<f32> = img.pixels()[..]
.chunks_exact(4)
.map(|c| f32::from_ne_bytes(c.try_into().unwrap()))
.collect();
assert!(all.chunks(4).all(|px| (px[0] - 0.1).abs() < 1e-6), "整帧应为清屏色");
}
/// U8 目标:clear → GL_RGBA8 存储 → 回读归一化为 F32(容差内)。
#[test]
fn fbo_clear_readback_u8() {
let Some(_g) = maybe_gl() else {
return;
};
let (w, h) = (3i32, 3i32);
let params = u8_params(w, h);
let tex = create_output_texture(w, h, &params).expect("U8 输出纹理应可建");
let fbo = create_fbo(tex, w, h).expect("FBO 应完整");
bind_fbo(fbo);
set_viewport(w, h);
gl_clear_color(0.5, 0.25, 0.0, 1.0);
gl_clear();
let img = read_pixels_to_image(w, h, &params).expect("U8 回读应成功");
delete_fbo(fbo);
delete_gl_texture(tex);
let px_f: Vec<f32> = img.pixels()[0..16]
.chunks_exact(4)
.map(|c| f32::from_ne_bytes(c.try_into().unwrap()))
.collect();
// 0.5*255=127.5→128(round),128/255≈0.50196;0.25→64→0.25098。
assert!((px_f[0] - 0.502).abs() < 0.01, "R={}", px_f[0]);
assert!((px_f[1] - 0.251).abs() < 0.01, "G={}", px_f[1]);
assert!(px_f[2].abs() < 0.01, "B={}", px_f[2]);
assert!((px_f[3] - 1.0).abs() < 0.01, "A={}", px_f[3]);
}
/// 输入纹理上传:建 RGBA32F 纹理 + 上传已知像素,读回纹理内容
/// (经 FBO 附着 + glReadPixels)与源像素一致。
#[test]
fn input_texture_upload_roundtrip() {
let Some(_g) = maybe_gl() else {
return;
};
let (w, h) = (2i32, 2i32);
let mut px = Vec::new();
for i in 0..(w * h) as usize {
for c in 0..4 {
px.extend_from_slice(&((i * 4 + c) as f32 * 0.1).to_ne_bytes());
}
}
let tex = create_input_texture(w, h, &px).expect("输入纹理应可建");
let params = f32_params(w, h);
let fbo = create_fbo(tex, w, h).expect("FBO 应完整");
bind_fbo(fbo);
let img = read_pixels_to_image(w, h, &params).expect("回读应成功");
delete_fbo(fbo);
delete_gl_texture(tex);
let got: Vec<f32> = img.pixels()[0..w as usize * h as usize * 16]
.chunks_exact(4)
.map(|c| f32::from_ne_bytes(c.try_into().unwrap()))
.collect();
let want: Vec<f32> = px
.chunks_exact(4)
.map(|c| f32::from_ne_bytes(c.try_into().unwrap()))
.collect();
// 源是逐像素相异序列:read_pixels_to_image 垂直翻转(GL 左下 →
// 帧左上)后,最终图像第 r 行 = 源第 (h-1-r) 行。
let stride = w as usize * 4;
for (i, g) in got.iter().enumerate() {
let row = i / stride;
let inv_row = (h as usize - 1 - row) as usize;
let expected = want[inv_row * stride + i % stride];
assert!(
(g - expected).abs() < 1e-6,
"pixel {i}: got {g} want {expected}"
);
}
}
/// 同线程可重入 acquire:外层 guard 持有期再 acquire 不死锁,GL
/// 调用仍可达;嵌套 guard drop 后上下文保持 current(外层仍有效),
/// 外层 drop 后清 current。模拟 interact draw 的"一次 acquire 覆盖
/// FBO 装配 → 插件绘制 → 回读"场景。
#[test]
fn acquire_is_reentrant_on_same_thread() {
let Some(_outer) = maybe_gl() else {
return;
};
// 嵌套 acquire(interact::draw 内部路径)。
let inner = acquire().expect("嵌套 acquire 应成功(同线程重入)");
let v1 = gl_version_string();
assert!(v1.is_some(), "嵌套 guard 期间 GL 应仍 current");
drop(inner);
// 外层仍持有:GL 仍 current。
let v2 = gl_version_string();
assert!(v2.is_some(), "嵌套 guard drop 后外层仍应 current");
// 再套一层(深度 2)验证深度计数不串。
{
let inner2 = acquire().expect("二次嵌套应成功");
assert!(gl_version_string().is_some());
drop(inner2);
}
}
}
+43
View File
@@ -0,0 +1,43 @@
// 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/>.
//! 句柄机制的历史遗留:`RefBox<T>` 容器。
//!
//! 单库化(M14 R5)后 crate 内部不再传 CHandle——原 CHandle 装拆
//! (`make_owned`/`make_borrowed`/`get`)、panic 兜底(`guard`/
//! `guard_handle`/`guard_void`)与身份注册表(`Registry`)均已删除:
//! 前者只被测试使用,后者在 src 无读取方(param 桥实际走
//! [`crate::suites::param`] 的 props 地址映射与 [`crate::node`] 的
//! 身份注册表)。
//!
//! 仅 [`RefBox`] 保留:它是 [`crate::host::Host::create_instance`] 的
//! 返回值容器(`Arc<RefBox<Instance>>`),该类型被 oakengine 的
//! test_support 显式标注消费,是本 crate 在 facade 边界的公开类型。
use std::sync::atomic::AtomicU32;
/// 边界盒:`Arc<RefBox<Instance>>` 的承载类型。
///
/// 原为 C 句柄(`{ctx, addref, release, abi_version}`)背后的堆盒子,
/// addref/release thunk 经 `refs` 计数;装拆删除后 `refs` 不再被读写,
/// 仅以固定值 1 构造("单个拥有者"语义),生命周期完全由外层
/// `Arc` 管理。
pub struct RefBox<T: ?Sized> {
/// 引用计数(句柄时代遗留,现无 thunk 读写)。
pub refs: AtomicU32,
/// 内含对象。
pub value: T,
}
File diff suppressed because it is too large Load Diff
+254
View File
@@ -0,0 +1,254 @@
// 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/>.
//! OFX image: an OFX view of a frame buffer (CPU path).
//!
//! Counterpart of the C++ `OliveImage`. Pixel memory is owned by this
//! crate (this was historically a hotspot of memory bugs: ownership
//! must be single, and lifetime is guaranteed by this type).
//! GL texture views are deferred to phase 2 (`// [P2]`).
//!
//! Property writes mirror the C++ `Image::allocate`
//! (image.cpp:132-172) and the HostSupport image property table
//! (HS: ofxhClip.cpp:458-472): Data/RowBytes/Bounds/
//! RegionOfDefinition/Components/PixelDepth/UniqueIdentifier.
//! This struct does not distinguish bounds from ROD (unified), and
//! does not model field/renderScale/pixelAspect/premultiplication
//! (`// [P2]`).
use std::ffi::{c_void, CString};
use std::sync::atomic::{AtomicU64, Ordering};
use crate::instance::OfxRectD;
use crate::property::{PropertySet, Value};
// ---- OFX property names (macro strings of ofxCore.h / ofxImageEffect.h) ----
/// kOfxImagePropData (ofxCore.h:1275): pixel data pointer.
pub(crate) const K_IMAGE_PROP_DATA: &str = "OfxImagePropData";
/// kOfxImagePropRowBytes (ofxCore.h:1322): row byte count.
pub(crate) const K_IMAGE_PROP_ROW_BYTES: &str = "OfxImagePropRowBytes";
/// kOfxImagePropBounds (ofxCore.h:1291): pixel coordinates, Int x 4.
pub(crate) const K_IMAGE_PROP_BOUNDS: &str = "OfxImagePropBounds";
/// kOfxImagePropRegionOfDefinition (ofxCore.h:1307): pixel coordinates, Int x 4.
pub(crate) const K_IMAGE_PROP_ROD: &str = "OfxImagePropRegionOfDefinition";
/// kOfxImageEffectPropComponents (ofxImageEffect.h:915).
pub(crate) const K_IMAGE_EFFECT_PROP_COMPONENTS: &str = "OfxImageEffectPropComponents";
/// kOfxImageEffectPropPixelDepth (ofxImageEffect.h:901).
pub(crate) const K_IMAGE_EFFECT_PROP_PIXEL_DEPTH: &str = "OfxImageEffectPropPixelDepth";
/// kOfxImagePropUniqueIdentifier (ofxCore.h:927): host-assigned unique id.
pub(crate) const K_IMAGE_PROP_UNIQUE_ID: &str = "OfxImagePropUniqueIdentifier";
/// Process-wide monotonically increasing id (zero-dependency
/// replacement for HostSupport's UUID generation).
static NEXT_IMAGE_ID: AtomicU64 = AtomicU64::new(0);
/// Pixel bit depth (OFX kOfxBitDepth*; the full pipeline only uses
/// Float, the rest are kept for compatibility).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BitDepth {
/// 8-bit integer (compat).
Byte,
/// 16-bit integer (compat).
Short,
/// 16-bit half float (compat).
Half,
/// 32-bit float (main path).
Float,
}
impl BitDepth {
/// Bytes per component.
pub(crate) fn bytes_per_component(self) -> usize {
match self {
BitDepth::Byte => 1,
BitDepth::Short | BitDepth::Half => 2,
BitDepth::Float => 4,
}
}
/// OFX bit depth string (kOfxBitDepth*, ofxCore.h:866-880).
pub(crate) fn to_ofx(self) -> &'static str {
match self {
BitDepth::Byte => "OfxBitDepthByte",
BitDepth::Short => "OfxBitDepthShort",
BitDepth::Half => "OfxBitDepthHalf",
BitDepth::Float => "OfxBitDepthFloat",
}
}
}
/// Component layout (OFX kOfxImageComponent*).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Components {
/// RGBA.
Rgba,
/// RGB.
Rgb,
/// Single-channel Alpha.
Alpha,
}
impl Components {
/// Channel count.
pub(crate) fn channel_count(self) -> usize {
match self {
Components::Rgba => 4,
Components::Rgb => 3,
Components::Alpha => 1,
}
}
/// OFX component string (kOfxImageComponent*, ofxImageEffect.h:46-55).
pub(crate) fn to_ofx(self) -> &'static str {
match self {
Components::Rgba => "OfxImageComponentRGBA",
Components::Rgb => "OfxImageComponentRGB",
Components::Alpha => "OfxImageComponentAlpha",
}
}
}
/// A single frame. `data` is row-major; the row stride may be padded
/// for alignment; bounds are in pixel coordinates.
/// `#[repr(C)]` with `props` at offset 0 (handle convention,
/// see [`crate::suites::tag`]).
#[repr(C)]
pub struct Image {
/// Image-level properties (bounds, row bytes, depth, components,
/// unique identifier).
pub props: PropertySet,
/// Pixel buffer (length = row_bytes * height).
data: Vec<u8>,
/// Bit depth.
depth: BitDepth,
/// Components.
components: Components,
/// Pixel bounds.
bounds: OfxRectD,
/// Row byte count.
row_bytes: usize,
}
impl Image {
/// Allocate by format (uninitialized pixels).
///
/// Property writes mirror the C++ `Image::allocate`
/// (image.cpp:156-172): Data/RowBytes/Bounds/RegionOfDefinition/
/// Components/PixelDepth; UniqueIdentifier is also written per the
/// image property table (HS: ofxhClip.cpp:470).
/// ROD is unified with bounds (this struct does not distinguish
/// the two; both are pixel coordinates). A zero-size or inverted
/// rectangle yields an empty buffer (mirrors the
/// `buffer_size < 0 -> 0` guard in image.cpp:147-149).
pub fn allocate(depth: BitDepth, components: Components, bounds: OfxRectD) -> Self {
let (w, h) = {
let width = (bounds.x2 - bounds.x1).round();
let height = (bounds.y2 - bounds.y1).round();
if width > 0.0 && height > 0.0 {
(width as usize, height as usize)
} else {
(0, 0)
}
};
let row_bytes = w * components.channel_count() * depth.bytes_per_component();
let mut img = Self {
props: PropertySet::new(),
data: vec![0u8; row_bytes * h],
depth,
components,
bounds,
row_bytes,
};
// `data` is a heap buffer; moving/borrowing the vec does not move
// the buffer, and it is never resized after allocation, so the
// pointer stays valid for the whole Image lifetime (ownership
// discipline: this is the only place that holds the buffer).
img.props.define(
K_IMAGE_PROP_DATA,
vec![Value::Pointer(img.data.as_mut_ptr() as *mut c_void)],
);
img.props
.define(K_IMAGE_PROP_ROW_BYTES, vec![Value::Int(row_bytes as i32)]);
let b = |v: f64| Value::Int(v.round() as i32);
img.props.define(
K_IMAGE_PROP_BOUNDS,
vec![b(bounds.x1), b(bounds.y1), b(bounds.x2), b(bounds.y2)],
);
img.props.define(
K_IMAGE_PROP_ROD,
vec![b(bounds.x1), b(bounds.y1), b(bounds.x2), b(bounds.y2)],
);
img.props.define(
K_IMAGE_EFFECT_PROP_COMPONENTS,
vec![Value::String(CString::new(components.to_ofx()).unwrap())],
);
img.props.define(
K_IMAGE_EFFECT_PROP_PIXEL_DEPTH,
vec![Value::String(CString::new(depth.to_ofx()).unwrap())],
);
img.props.define(
K_IMAGE_PROP_UNIQUE_ID,
vec![Value::String(unique_identifier())],
);
img
}
/// Mutable pixel slice (for writing plugin output). The length is
/// consistent with the format by type construction.
pub fn pixels_mut(&mut self) -> &mut [u8] {
&mut self.data
}
/// Read-only pixel slice.
pub fn pixels(&self) -> &[u8] {
&self.data
}
/// Pixel bounds (canonical coordinates; the Image keeps bounds and
/// ROD unified).
pub fn bounds(&self) -> OfxRectD {
self.bounds
}
/// Bit depth.
pub fn depth(&self) -> BitDepth {
self.depth
}
/// Components.
pub fn components(&self) -> Components {
self.components
}
/// Row byte count.
pub fn row_bytes(&self) -> usize {
self.row_bytes
}
}
/// Unique identifier string (monotonically increasing per process,
/// hexadecimal; corresponds to the `uniqueIdentifier` parameter of
/// HS: ofxhClip.cpp:537).
pub(crate) fn unique_identifier() -> CString {
let n = NEXT_IMAGE_ID.fetch_add(1, Ordering::Relaxed);
// Hexadecimal ASCII, no NUL; unwrap cannot fail.
CString::new(format!("{:x}", n)).unwrap()
}
File diff suppressed because it is too large Load Diff
+74
View File
@@ -0,0 +1,74 @@
// 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/>.
//! # oakplugin — Oak 的插件模块(自研 OFX 宿主)
//!
//! 本 crate 是 oakplugin 模块的全部实现(M11):
//!
//! - **OFX 宿主**:扫描 bundle、加载插件、实现八张 suite
//! (property/memory/image_effect/param/message/progress/timeline/
//! multithread),驱动 describe/createInstance/render 等 action。
//! - **桥**:把 OFX 实例的参数接到 oaknode([`node`],节点值 POD +
//! 身份注册表与 undoable 回写)、把 clip 的输入输出接到 oakrender
//! 纹理([`render`],纹理/帧/渲染器值类型)、把参数修改包成 undo
//! 命令(直接经 `oak_undo::undocommand::UndoCommand`,见
//! [`instance::Instance::submit_undo_command`])。
//!
//! ## 单库化(single-lib unification)
//!
//! 本 crate 的 C ABI 出口(原 [`ffi`])与模块桥(原 [`bridge`])已
//! 删除:oaknode/oakrender/oakundo 均以 path 依赖直接链接。桥以
//! 直接 Rust 类型重建([`node`] 的身份注册表与
//! `set_input_*_undoable`;[`render`] 的 `Texture`/`Frame`/`Renderer`
//! 值类型)。GL 纹理名(旧 `oakrender_texture_id` 的 GL 命名空间)
//! 由 [`gl_bridge`](方案 B:离屏 CGL 上下文 + 回读)提供;
//! [`render::texture_id`] 对 oakrender 纹理保持恒 0(wgpu/Metal 无
//! GL 命名空间),use_opengl 决策与 GL suite 的 OpenGLTextureIndex
//! 改从 [`gl_bridge`] 取真实名。
//!
//! ## 句柄纪律(全 crate 最高优先级约定)
//!
//! 1. 插件可在任意自起线程回调 suite(multithread suite 存活期
//! 内);一切共享状态走 `Mutex`。
//! 2. OFX 语义以 openfx HostSupport 为参照系;协商与时序实现点必须
//! 注释对应 HostSupport 文件与行号(格式:`// HS: ofxhImageEffect.cpp:2776`)。
//!
//! ## 第 1 期范围
//!
//! filter/generator/transition 上下文;CPU 渲染路径。GL 纹理 suite
//! 与 ofxColour 为第 2 期([`clip`]/[`image`] 内以 `// [P2]` 标记
//! 预留点)。
#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs)]
pub mod clip;
pub mod descriptor;
pub mod error;
pub mod gl_bridge;
pub mod handle;
pub mod host;
pub mod image;
pub mod instance;
pub mod node;
pub mod node_factory;
pub mod param;
pub mod param_curve;
pub mod progress;
pub mod property;
pub mod render;
pub mod render_driver;
pub mod suites;
+686
View File
@@ -0,0 +1,686 @@
// 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/>.
//! oaknode 桥(single-lib unification):节点值 POD、身份注册表与
//! undoable 参数回写。
//!
//! ## Value 布局冻结
//!
//! [`Value`] 即 include/node/node.h:93 的 `oaknode_value` POD,字段
//! 逐字一致(type/num/den/f[4];`type` 取值见 [`node_value_type`])。
//! 字符串族输入(k_file/k_text/k_font/k_str_combo,node.h:48-52)没有
//! POD 表示——走 `*_input_string_*` 专用函数(本桥的
//! [`set_input_string_undoable`]);`OAKNODE_VALUE_STRING` 的 POD 里
//! 不携带字符串数据。
//!
//! ## 身份注册表(单库化重建)
//!
//! oaknode 的 C ABI 已删除(单库化):节点对象是
//! `oak_node::project::Project`(Arc<Mutex<Project>>)里的
//! `oak_node::graph::Graph` 条目,按 [`oak_node::id::NodeId`] 定位。
//! 本 crate 的 [`NodeRef`] 即旧句柄盒
//! `(Arc<Mutex<Project>>, NodeId)` 的值型复刻;进程级注册表
//! [`register_node`]/[`node_from_identity`] 按
//! [`oak_node::id::NodeId::identity`] 的打包身份(u64)做弱引用
//! 映射(project 释放后条目自然失效,升级失败 → None)——
//! 对应 M9 C++ 版 `oaknode_node_identity()` 注册表的地址语义。
//! facade 装配期调 [`register_node`] 登记节点,把返回身份写进
//! [`crate::instance::Instance::bind_node`](`node_identity`)。
//!
//! ## undoable 回写
//!
//! [`set_input_undoable`]/[`set_input_string_undoable`] 按
//! `oak_node::ops::set_value_at_time_command` 的同一 closure
//! 模式(`command_from_closures`)构造未执行的
//! `oak_undo::undocommand::UndoCommand`:redo 闭包锁 project、
//! `graph.get_mut(id)`、`NodeCore::set_standard_value` 写标准值;
//! undo 闭包回放创建期快照的旧值。命令由调用方
//! ([`crate::param::notify_instance_changed`] →
//! [`crate::instance::Instance::submit_undo_command`])提交。
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, Weak};
use oak_undo::undocommand::UndoCommand;
/// oaknode 节点引用(single-lib):旧 C ABI 句柄盒
/// `(Arc<Mutex<Project>>, NodeId)` 的值型复刻。
#[derive(Clone)]
pub struct NodeRef {
/// 所属 project(节点生命周期随 project)。
pub project: Arc<Mutex<oak_node::project::Project>>,
/// 节点在 project.graph 里的 id。
pub id: oak_node::id::NodeId,
}
/// oaknode_value_type 的取值(node.h:74)。
pub mod node_value_type {
/// OAKNODE_VALUE_NONE。
pub const NONE: i32 = 0;
/// OAKNODE_VALUE_INT。
pub const INT: i32 = 1;
/// OAKNODE_VALUE_FLOAT。
pub const FLOAT: i32 = 2;
/// OAKNODE_VALUE_BOOL。
pub const BOOL: i32 = 3;
/// OAKNODE_VALUE_RATIONAL。
pub const RATIONAL: i32 = 4;
/// OAKNODE_VALUE_COLOR。
pub const COLOR: i32 = 5;
/// OAKNODE_VALUE_VEC2。
pub const VEC2: i32 = 6;
/// OAKNODE_VALUE_VEC3。
pub const VEC3: i32 = 7;
/// OAKNODE_VALUE_VEC4。
pub const VEC4: i32 = 8;
/// OAKNODE_VALUE_COMBO。
pub const COMBO: i32 = 9;
/// OAKNODE_VALUE_STRING。
pub const STRING: i32 = 10;
}
/// oaknode_value(include/node/node.h:93,字段逐字一致)。
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Value {
/// 类型([`node_value_type`])。
pub r#type: i32,
/// INT/COMBO 值、BOOL 0/1、RATIONAL 分子。
pub num: i64,
/// RATIONAL 分母。
pub den: i64,
/// FLOAT f[0];VEC2/3/4 f[0..n-1];COLOR r,g,b,a。
pub f: [f64; 4],
}
impl Value {
/// 类型化构造:整数 / choice 索引。
pub const fn int(v: i64) -> Self {
Self {
r#type: node_value_type::INT,
num: v,
den: 0,
f: [0.0; 4],
}
}
/// 类型化构造:浮点。
pub const fn float(v: f64) -> Self {
Self {
r#type: node_value_type::FLOAT,
num: 0,
den: 0,
f: [v, 0.0, 0.0, 0.0],
}
}
/// 类型化构造:布尔。
pub const fn bool_(v: bool) -> Self {
Self {
r#type: node_value_type::BOOL,
num: v as i64,
den: 0,
f: [0.0; 4],
}
}
/// 类型化构造:choice(COMBO)。
pub const fn combo(v: i64) -> Self {
Self {
r#type: node_value_type::COMBO,
num: v,
den: 0,
f: [0.0; 4],
}
}
/// 类型化构造:颜色。
pub const fn color(r: f64, g: f64, b: f64, a: f64) -> Self {
Self {
r#type: node_value_type::COLOR,
num: 0,
den: 0,
f: [r, g, b, a],
}
}
/// 类型化构造:vec2/3/4(长度按 f 数组尾部 0 判定)。
pub const fn vec(v: &[f64]) -> Self {
let t = match v.len() {
2 => node_value_type::VEC2,
3 => node_value_type::VEC3,
_ => node_value_type::VEC4,
};
let mut f = [0.0; 4];
let mut i = 0;
while i < v.len() && i < 4 {
f[i] = v[i];
i += 1;
}
Self {
r#type: t,
num: 0,
den: 0,
f,
}
}
/// 类型化构造:字符串族(POD 不携带数据;值经
/// [`set_input_string_undoable`] 传递)。
pub const fn string() -> Self {
Self {
r#type: node_value_type::STRING,
num: 0,
den: 0,
f: [0.0; 4],
}
}
/// POD → [`oak_node::value::NodeValue`],按 POD kind 映射(与
/// `oak_node::value::OakNodeValue::to_node_value` 的 kind 分支一致,
/// 不按声明类型重量化)。`STRING` 族 POD 不携带数据 → `None`;
/// `NONE` → [`oak_node::value::NodeValue::None`]。
pub fn to_node_value(&self) -> Option<oak_node::value::NodeValue> {
use oak_node::value::NodeValue as NV;
match self.r#type {
node_value_type::NONE => Some(NV::None),
node_value_type::INT => Some(NV::Int(self.num)),
node_value_type::FLOAT => Some(NV::Float(self.f[0])),
node_value_type::BOOL => Some(NV::Boolean(self.num != 0)),
node_value_type::RATIONAL => Some(NV::Rational(oak_core::Rational::new(
self.num, self.den,
))),
node_value_type::COLOR => Some(NV::Color(self.f)),
node_value_type::VEC2 => Some(NV::Vec2([self.f[0], self.f[1]])),
node_value_type::VEC3 => Some(NV::Vec3([self.f[0], self.f[1], self.f[2]])),
node_value_type::VEC4 => Some(NV::Vec4(self.f)),
node_value_type::COMBO => Some(NV::Combo(self.num)),
_ => None,
}
}
/// [`oak_node::value::NodeValue`] → POD(`ValueType::to_oak` 的逆)。
/// 无 POD 表达的类型(字符串族/纹理/采样/矩阵等)→ `None`。
pub fn from_node_value(v: &oak_node::value::NodeValue) -> Option<Value> {
use oak_node::value::NodeValue as NV;
Some(match v {
NV::None => Value {
r#type: node_value_type::NONE,
num: 0,
den: 0,
f: [0.0; 4],
},
NV::Int(i) => Value::int(*i),
NV::Float(f) => Value::float(*f),
NV::Boolean(b) => Value::bool_(*b),
NV::Rational(r) => Value {
r#type: node_value_type::RATIONAL,
num: r.numerator(),
den: r.denominator(),
f: [0.0; 4],
},
NV::Color(c) => Value::color(c[0], c[1], c[2], c[3]),
NV::Vec2(a) => Value::vec(&[a[0], a[1]]),
NV::Vec3(a) => Value::vec(&[a[0], a[1], a[2]]),
NV::Vec4(a) => Value::vec(&[a[0], a[1], a[2], a[3]]),
NV::Combo(i) => Value::combo(*i),
_ => return None,
})
}
}
// ---- 身份注册表 -----------------------------------------------------------
/// 注册表条目:弱 project 引用(project 释放后升级失败,条目变死)
/// + 节点 id。
struct RegistryEntry {
/// 所属 project(弱引用;强引用由调用方/节点持有)。
project: Weak<Mutex<oak_node::project::Project>>,
/// 节点 id。
id: oak_node::id::NodeId,
}
/// 进程级身份注册表(OnceLock 惰性初始化;测试进程内可重复 register)。
static NODE_REGISTRY: OnceLock<Mutex<HashMap<u64, RegistryEntry>>> = OnceLock::new();
fn registry() -> &'static Mutex<HashMap<u64, RegistryEntry>> {
NODE_REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}
/// 登记 oaknode 节点(facade 装配期调用;对应 M9 C++ 版
/// `oaknode_node_identity()` 注册表的登记侧)。返回打包身份
/// ([`oak_node::id::NodeId::identity`]),写入
/// [`crate::instance::Instance::bind_node`]。同一身份重复登记
/// 覆盖旧条目(重绑定)。
pub fn register_node(
project: Arc<Mutex<oak_node::project::Project>>,
id: oak_node::id::NodeId,
) -> u64 {
let identity = id.identity();
let entry = RegistryEntry {
project: Arc::downgrade(&project),
id,
};
registry()
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(identity, entry);
identity
}
/// 摘除身份(节点销毁路径调用;未知身份 no-op)。
pub fn unregister_node(identity: u64) {
registry()
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&identity);
}
/// 身份 → 节点引用(param 回写入口)。
///
/// `None`:身份未登记,或 project 已释放(弱引用升级失败——旧 C
/// ABI 对悬垂句柄的可解释失败路径)。调用方
/// ([`crate::param::notify_instance_changed`])按 "未绑定节点 →
/// no-op" 处理。
pub fn node_from_identity(identity: usize) -> Option<NodeRef> {
let (project, id) = {
let reg = registry()
.lock()
.unwrap_or_else(|e| e.into_inner());
let entry = reg.get(&(identity as u64))?;
(entry.project.clone(), entry.id)
};
let project = project.upgrade()?;
Some(NodeRef { project, id })
}
// ---- 桥调用面(undoable 回写)---------------------------------------------
/// oaknode 桥错误(set_input* 的失败原因;调用方按失败跳过提交)。
#[derive(Debug, thiserror::Error)]
pub enum NodeBridgeError {
/// 节点 id 已失效(图内无此节点)。
#[error("node id is stale or not present in the graph")]
StaleNode,
/// 节点上无该输入。
#[error("node has no input '{0}'")]
UnknownInput(String),
/// 值 POD 无法转换(STRING 族 POD 不携带数据;数值族恒可转换)。
#[error("value POD of type {0} cannot be converted to a node value")]
InvalidValue(i32),
/// 输入不是字符串族类型(string setter 限定 Text/StrCombo)。
#[error("input '{0}' is not a string-family input")]
NotStringInput(String),
}
/// 取锁(毒锁接管,一次 panic 不级联)。
fn lock_any<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
/// 从 redo/undo 闭包构造未执行的 [`UndoCommand`](closure 模式,与
/// `oak_node::ops::command_from_closures` 同构)。
fn command_from_closures(
redo: impl FnMut() + Send + 'static,
undo: impl FnMut() + Send + 'static,
) -> UndoCommand {
UndoCommand::from_closures(redo, undo)
}
/// 以 undoable 方式设置节点的标准输入值(POD 路径;数值族输入)。
///
/// 返回**未执行**的 [`UndoCommand`](调用方
/// [`crate::instance::Instance::submit_undo_command`] 提交):redo
/// 锁 project、`graph.get_mut(id)`、`NodeCore::set_standard_value`
/// 写新值;undo 回放创建期快照的旧值(与
/// `oak_node::ops::set_value_at_time_command` 的 standard-value 分支
/// 同构,element = -1 整值)。节点/输入失效时返回
/// [`NodeBridgeError`](不产出命令)。
pub fn set_input_undoable(
node: &NodeRef,
input: &str,
value: &Value,
) -> Result<UndoCommand, NodeBridgeError> {
let nv = value
.to_node_value()
.ok_or(NodeBridgeError::InvalidValue(value.r#type))?;
// 校验节点与输入存在性 + 旧值快照(创建期状态,redo/undo 据此
// 回放;不校验声明类型——按 POD kind 存原样,与 ops.rs 一致)。
let old = {
let mut guard = lock_any(&node.project);
let entry = guard
.graph
.get_mut(node.id)
.ok_or(NodeBridgeError::StaleNode)?;
if entry.core.input_data_type(input).is_none() {
return Err(NodeBridgeError::UnknownInput(input.to_string()));
}
entry.core.standard_value(input, -1)
};
let project = node.project.clone();
let id = node.id;
let input_redo = input.to_string();
let input_undo = input.to_string();
let value_redo = nv.clone();
let project_redo = project.clone();
let project_undo = project.clone();
Ok(command_from_closures(
move || {
let mut guard = lock_any(&project_redo);
if let Some(entry) = guard.graph.get_mut(id) {
entry
.core
.set_standard_value(&input_redo, -1, value_redo.clone());
}
},
move || {
let mut guard = lock_any(&project_undo);
if let Some(entry) = guard.graph.get_mut(id) {
entry
.core
.set_standard_value(&input_undo, -1, old.clone());
}
},
))
}
/// 以 undoable 方式设置节点的标准输入值(字符串族输入:Text /
/// StrCombo / Parametric——POD 不携带字符串数据)。
///
/// 按输入的声明类型([`oak_node::value::ValueType`])选存储变体:
/// `StrCombo` → [`oak_node::value::NodeValue::StrCombo`],
/// `Text` / `Parametric`(值 = 曲线 JSON 文本)→
/// [`oak_node::value::NodeValue::Text`]。声明类型不是字符串族 →
/// [`NodeBridgeError::NotStringInput`]。命令语义与
/// [`set_input_undoable`] 相同。
pub fn set_input_string_undoable(
node: &NodeRef,
input: &str,
value: &str,
) -> Result<UndoCommand, NodeBridgeError> {
let (old, declared) = {
let guard = lock_any(&node.project);
let entry = guard
.graph
.get(node.id)
.ok_or(NodeBridgeError::StaleNode)?;
let declared = entry
.core
.input_data_type(input)
.ok_or_else(|| NodeBridgeError::UnknownInput(input.to_string()))?;
(entry.core.standard_value(input, -1), declared)
};
let nv = match declared {
oak_node::value::ValueType::StrCombo => oak_node::value::NodeValue::StrCombo(value.to_string()),
oak_node::value::ValueType::Text | oak_node::value::ValueType::Parametric => {
oak_node::value::NodeValue::Text(value.to_string())
}
_ => return Err(NodeBridgeError::NotStringInput(input.to_string())),
};
let project = node.project.clone();
let id = node.id;
let input_redo = input.to_string();
let input_undo = input.to_string();
let value_redo = nv.clone();
let project_redo = project.clone();
let project_undo = project.clone();
Ok(command_from_closures(
move || {
let mut guard = lock_any(&project_redo);
if let Some(entry) = guard.graph.get_mut(id) {
entry
.core
.set_standard_value(&input_redo, -1, value_redo.clone());
}
},
move || {
let mut guard = lock_any(&project_undo);
if let Some(entry) = guard.graph.get_mut(id) {
entry
.core
.set_standard_value(&input_undo, -1, old.clone());
}
},
))
}
#[cfg(test)]
mod tests {
use super::*;
/// 建一个含 Text/StrCombo/Float 输入的测试节点。
fn test_project() -> (Arc<Mutex<oak_node::project::Project>>, oak_node::id::NodeId) {
let project = oak_node::project::Project::new();
let mut guard = project.lock().unwrap();
let id = guard.graph.add_node(
oak_node::node::NodeCore::empty(),
Box::new(oak_node::nodes::EmptyBehavior),
);
// NodeCore::empty 无输入;手动声明三种输入。
use oak_node::input::Input;
let core = guard.graph.get_mut(id).unwrap();
core.core.add_input(Input::new(
"label",
oak_node::value::ValueType::Text,
oak_node::value::NodeValue::Text(String::new()),
));
core.core.add_input(Input::new(
"choice",
oak_node::value::ValueType::StrCombo,
oak_node::value::NodeValue::StrCombo(String::new()),
));
core.core.add_input(Input::new(
"opacity",
oak_node::value::ValueType::Float,
oak_node::value::NodeValue::Float(1.0),
));
drop(guard);
(project, id)
}
/// 注册表:register → node_from_identity → unregister 全链。
#[test]
fn identity_register_roundtrip() {
let (project, id) = test_project();
let identity = register_node(project.clone(), id);
let node = node_from_identity(identity as usize).expect("已登记身份应可解析");
assert_eq!(node.id, id);
let found = node.project.lock().unwrap().graph.get(id).is_some();
assert!(found);
// 未登记身份 → None。
assert!(node_from_identity(0xfeed_face).is_none());
unregister_node(identity);
assert!(node_from_identity(identity as usize).is_none());
}
/// project 释放后弱条目升级失败 → None(悬垂语义);重复登记
/// 覆盖死条目后重新解析到新 project。
#[test]
fn identity_project_dropped() {
let (project, id) = test_project();
let identity = register_node(project.clone(), id);
drop(project);
assert!(node_from_identity(identity as usize).is_none());
// 新 project 同槽位身份重登记(覆盖死条目)。
let (project2, id2) = test_project();
register_node(project2.clone(), id2);
let node = node_from_identity(identity as usize).expect("重登记后应可解析");
assert_eq!(node.id, id2);
let alive = node.project.lock().unwrap().graph.get(id2).is_some();
assert!(alive);
}
/// Value POD ↔ NodeValue 全类型映射;STRING 族 POD 无数据。
#[test]
fn pod_node_value_roundtrip() {
use oak_node::value::NodeValue as NV;
let cases: Vec<(Value, NV)> = vec![
(Value::int(7), NV::Int(7)),
(Value::float(1.5), NV::Float(1.5)),
(Value::bool_(true), NV::Boolean(true)),
(Value::combo(3), NV::Combo(3)),
(
Value {
r#type: node_value_type::RATIONAL,
num: 3,
den: 2,
f: [0.0; 4],
},
NV::Rational(oak_core::Rational::new(3, 2)),
),
(Value::color(0.1, 0.2, 0.3, 0.4), NV::Color([0.1, 0.2, 0.3, 0.4])),
(Value::vec(&[1.0, 2.0]), NV::Vec2([1.0, 2.0])),
(Value::vec(&[1.0, 2.0, 3.0]), NV::Vec3([1.0, 2.0, 3.0])),
(
Value::vec(&[1.0, 2.0, 3.0, 4.0]),
NV::Vec4([1.0, 2.0, 3.0, 4.0]),
),
];
for (pod, nv) in cases {
let to = pod.to_node_value().expect("POD 应可转换");
assert_eq!(to, nv, "POD → NodeValue");
assert_eq!(Value::from_node_value(&nv), Some(pod), "NodeValue → POD");
}
// STRING POD 无数据。
assert!(Value::string().to_node_value().is_none());
// 无 POD 表达的类型。
assert_eq!(Value::from_node_value(&NV::Text("x".into())), None);
assert_eq!(Value::from_node_value(&NV::Matrix([0.0; 16])), None);
}
/// set_input_undoable:redo 写标准值、undo 回放旧值;错误路径。
#[test]
fn set_input_undoable_applies_and_undoes() {
let (project, id) = test_project();
let node = NodeRef {
project: project.clone(),
id,
};
let mut cmd = set_input_undoable(&node, "opacity", &Value::float(0.25)).unwrap();
// 命令未执行时值未变。
assert_eq!(
project
.lock()
.unwrap()
.graph
.get(id)
.unwrap()
.core
.standard_value("opacity", -1),
oak_node::value::NodeValue::Float(1.0)
);
cmd.redo_now();
assert_eq!(
project
.lock()
.unwrap()
.graph
.get(id)
.unwrap()
.core
.standard_value("opacity", -1),
oak_node::value::NodeValue::Float(0.25)
);
cmd.undo_now();
assert_eq!(
project
.lock()
.unwrap()
.graph
.get(id)
.unwrap()
.core
.standard_value("opacity", -1),
oak_node::value::NodeValue::Float(1.0)
);
// 未知输入 / STRING POD / 失效节点。
assert!(matches!(
set_input_undoable(&node, "nope", &Value::float(1.0)),
Err(NodeBridgeError::UnknownInput(_))
));
assert!(matches!(
set_input_undoable(&node, "opacity", &Value::string()),
Err(NodeBridgeError::InvalidValue(_))
));
let stale = NodeRef {
project,
id: oak_node::id::NodeId::from_identity(999).unwrap(),
};
assert!(matches!(
set_input_undoable(&stale, "opacity", &Value::float(1.0)),
Err(NodeBridgeError::StaleNode)
));
}
/// set_input_string_undoable:Text/StrCombo 变体选择与回放。
#[test]
fn set_input_string_undoable_variants() {
let (project, id) = test_project();
let node = NodeRef {
project: project.clone(),
id,
};
let mut cmd = set_input_string_undoable(&node, "label", "hello").unwrap();
cmd.redo_now();
assert_eq!(
project
.lock()
.unwrap()
.graph
.get(id)
.unwrap()
.core
.standard_value("label", -1),
oak_node::value::NodeValue::Text("hello".to_string())
);
cmd.undo_now();
assert_eq!(
project
.lock()
.unwrap()
.graph
.get(id)
.unwrap()
.core
.standard_value("label", -1),
oak_node::value::NodeValue::Text(String::new())
);
let mut cmd = set_input_string_undoable(&node, "choice", "low").unwrap();
cmd.redo_now();
assert_eq!(
project
.lock()
.unwrap()
.graph
.get(id)
.unwrap()
.core
.standard_value("choice", -1),
oak_node::value::NodeValue::StrCombo("low".to_string())
);
// 数值输入走字符串 setter → NotStringInput。
assert!(matches!(
set_input_string_undoable(&node, "opacity", "1.0"),
Err(NodeBridgeError::NotStringInput(_))
));
}
}
File diff suppressed because it is too large Load Diff
+938
View File
@@ -0,0 +1,938 @@
// 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/>.
//! 参数体系:13 种参数实例 + param ↔ oaknode 桥。
//!
//! 对应 C++ 的 `ParamInstance`/`OliveParamInstance`。桥的语义
//! (M9 已定):节点输入值变化 → 写回 OFX 参数;OFX 参数被插件
//! 改动 → 经 oaknode 回写节点(undoable 经
//! `oak_undo::undocommand::UndoCommand`)。
//!
//! 句柄约定([`crate::suites::tag`]):`ParamDef`/`ParamInstance`
//! `#[repr(C)]` 且 `props` 在偏移 0;元素装箱(`Vec<Box<..>>`)保证
//! Vec 重分配不移动对象、句柄不悬垂。
//!
//! 节点值布局:随 [`crate::node`] 冻结(`include/node/node.h` 的
//! `oaknode_value` POD);单库化后 oaknode 的身份注册表随其 ffi
//! 删除,回写路径是保留失败路径的本地桩(见 [`crate::node`])。
use std::ffi::CString;
use crate::property::{PropertySet, Value};
// ---- OFX 参数类型字符串(ofxParam.h)----
/// kOfxParamTypeInteger。
pub const TYPE_INTEGER: &str = "OfxParamTypeInteger";
/// kOfxParamTypeInteger2D。
pub const TYPE_INTEGER2D: &str = "OfxParamTypeInteger2D";
/// kOfxParamTypeInteger3D。
pub const TYPE_INTEGER3D: &str = "OfxParamTypeInteger3D";
/// kOfxParamTypeDouble。
pub const TYPE_DOUBLE: &str = "OfxParamTypeDouble";
/// kOfxParamTypeDouble2D。
pub const TYPE_DOUBLE2D: &str = "OfxParamTypeDouble2D";
/// kOfxParamTypeDouble3D。
pub const TYPE_DOUBLE3D: &str = "OfxParamTypeDouble3D";
/// kOfxParamTypeBoolean。
pub const TYPE_BOOLEAN: &str = "OfxParamTypeBoolean";
/// kOfxParamTypeChoice。
pub const TYPE_CHOICE: &str = "OfxParamTypeChoice";
/// kOfxParamTypeString。
pub const TYPE_STRING: &str = "OfxParamTypeString";
/// kOfxParamTypeStrChoice。
pub const TYPE_STRCHOICE: &str = "OfxParamTypeStrChoice";
/// kOfxParamTypeRGB。
pub const TYPE_RGB: &str = "OfxParamTypeRGB";
/// kOfxParamTypeRGBA。
pub const TYPE_RGBA: &str = "OfxParamTypeRGBA";
/// kOfxParamTypeBytes。
pub const TYPE_BYTES: &str = "OfxParamTypeBytes";
/// kOfxParamTypeCustom。
pub const TYPE_CUSTOM: &str = "OfxParamTypeCustom";
/// kOfxParamTypePushButton。
pub const TYPE_PUSHBUTTON: &str = "OfxParamTypePushButton";
/// kOfxParamTypeGroup。
pub const TYPE_GROUP: &str = "OfxParamTypeGroup";
/// kOfxParamTypePage。
pub const TYPE_PAGE: &str = "OfxParamTypePage";
/// kOfxParamTypeParametric(值 = 曲线列表,经
/// OfxParametricParameterSuite 读写,见
/// [`crate::suites::parametric`] 与 [`crate::param_curve`])。
pub const TYPE_PARAMETRIC: &str = "OfxParamTypeParametric";
// ---- 属性名(ofxParam.h / ofxCore.h)----
/// kOfxParamPropSecret。
pub(crate) const P_SECRET: &str = "OfxParamPropSecret";
/// kOfxParamPropHint。
pub(crate) const P_HINT: &str = "OfxParamPropHint";
/// kOfxParamPropScriptName。
pub(crate) const P_SCRIPT_NAME: &str = "OfxParamPropScriptName";
/// kOfxParamPropParent。
pub(crate) const P_PARENT: &str = "OfxParamPropParent";
/// kOfxParamPropEnabled。
pub(crate) const P_ENABLED: &str = "OfxParamPropEnabled";
/// kOfxParamPropDataPtr。
pub(crate) const P_DATA_PTR: &str = "OfxParamPropDataPtr";
/// kOfxParamPropType。
pub(crate) const P_TYPE: &str = "OfxParamPropType";
/// kOfxParamPropIsAnimating。
pub(crate) const P_IS_ANIMATING: &str = "OfxParamPropIsAnimating";
/// kOfxParamPropIsAutoKeying。
pub(crate) const P_IS_AUTO_KEYING: &str = "OfxParamPropIsAutoKeying";
/// kOfxParamPropPersistant。
pub(crate) const P_PERSISTANT: &str = "OfxParamPropPersistant";
/// kOfxParamPropEvaluateOnChange。
pub(crate) const P_EVALUATE_ON_CHANGE: &str = "OfxParamPropEvaluateOnChange";
/// kOfxParamPropCanUndo。
pub(crate) const P_CAN_UNDO: &str = "OfxParamPropCanUndo";
/// kOfxParamPropCacheInvalidation。
pub(crate) const P_CACHE_INVALIDATION: &str = "OfxParamPropCacheInvalidation";
/// kOfxParamInvalidateValueChange(P_CACHE_INVALIDATION 的默认值)。
pub(crate) const V_INVALIDATE_VALUE_CHANGE: &str = "OfxParamInvalidateValueChange";
/// kOfxParamPropAnimates。
pub(crate) const P_ANIMATES: &str = "OfxParamPropAnimates";
/// kOfxParamPropDefault。
pub(crate) const P_DEFAULT: &str = "OfxParamPropDefault";
/// kOfxParamPropDisplayMin。
pub(crate) const P_DISPLAY_MIN: &str = "OfxParamPropDisplayMin";
/// kOfxParamPropDisplayMax。
pub(crate) const P_DISPLAY_MAX: &str = "OfxParamPropDisplayMax";
/// kOfxParamPropMin。
pub(crate) const P_MIN: &str = "OfxParamPropMin";
/// kOfxParamPropMax。
pub(crate) const P_MAX: &str = "OfxParamPropMax";
/// kOfxParamPropIncrement。
pub(crate) const P_INCREMENT: &str = "OfxParamPropIncrement";
/// kOfxParamPropDigits。
pub(crate) const P_DIGITS: &str = "OfxParamPropDigits";
/// kOfxParamPropDoubleType。
pub(crate) const P_DOUBLE_TYPE: &str = "OfxParamPropDoubleType";
/// kOfxParamDoubleTypePlain。
pub(crate) const V_DOUBLE_TYPE_PLAIN: &str = "OfxParamDoubleTypePlain";
/// kOfxParamPropDefaultCoordinateSystem。
pub(crate) const P_DEFAULT_COORD_SYS: &str = "OfxParamPropDefaultCoordinateSystem";
/// kOfxParamCoordinatesCanonical。
pub(crate) const V_COORD_CANONICAL: &str = "OfxParamCoordinatesCanonical";
/// kOfxParamCoordinatesNormalised(ofxParam.h:514)。
pub(crate) const V_COORD_NORMALISED: &str = "OfxParamCoordinatesNormalised";
/// kOfxParamPropShowTimeMarker。
pub(crate) const P_SHOW_TIME_MARKER: &str = "OfxParamPropShowTimeMarker";
/// kOfxParamPropDimensionLabel。
pub(crate) const P_DIMENSION_LABEL: &str = "OfxParamPropDimensionLabel";
/// kOfxParamPropStringMode。
pub(crate) const P_STRING_MODE: &str = "OfxParamPropStringMode";
/// kOfxParamStringIsSingleLine。
pub(crate) const V_STRING_SINGLE_LINE: &str = "OfxParamStringIsSingleLine";
/// kOfxParamPropStringFilePathExists。
pub(crate) const P_STRING_FILE_EXISTS: &str = "OfxParamPropStringFilePathExists";
/// kOfxParamPropChoiceOption。
pub(crate) const P_CHOICE_OPTION: &str = "OfxParamPropChoiceOption";
/// kOfxParamPropChoiceOrder。
pub(crate) const P_CHOICE_ORDER: &str = "OfxParamPropChoiceOrder";
/// kOfxParamPropChoiceEnum。
pub(crate) const P_CHOICE_ENUM: &str = "OfxParamPropChoiceEnum";
/// kOfxParamPageSkipRow(page 子项哨兵,ofxParam.h:178)。
pub(crate) const PAGE_SKIP_ROW: &str = "OfxParamPageSkipRow";
/// kOfxParamPageSkipColumn(page 子项哨兵,ofxParam.h:186)。
pub(crate) const PAGE_SKIP_COLUMN: &str = "OfxParamPageSkipColumn";
/// kOfxParamPropCustomInterpCallbackV1。
pub(crate) const P_CUSTOM_INTERP: &str = "OfxParamPropCustomCallbackV1";
/// kOfxParamPropParametricDimension(int×1,默认 1)。
pub(crate) const P_PARAMETRIC_DIMENSION: &str = "OfxParamPropParametricDimension";
/// kOfxParamPropParametricRange(double×2,默认 (0,1))。
pub(crate) const P_PARAMETRIC_RANGE: &str = "OfxParamPropParametricRange";
/// kOfxParamPropParametricUIColour(double×3N,默认未设)。
pub(crate) const P_PARAMETRIC_UI_COLOUR: &str = "OfxParamPropParametricUIColour";
/// kOfxParamPropParametricInteractBackground(pointer×1,默认 NULL)。
pub(crate) const P_PARAMETRIC_INTERACT_BG: &str = "OfxParamPropParametricInteractBackground";
/// kOfxParamPropPageChild。
pub(crate) const P_PAGE_CHILD: &str = "OfxParamPropPageChild";
/// kOfxParamPropGroupOpen。
pub(crate) const P_GROUP_OPEN: &str = "OfxParamPropGroupOpen";
/// kOfxParamPropInteractV1。
pub(crate) const P_INTERACT_V1: &str = "OfxParamPropInteractV1";
/// kOfxParamPropInteractSize。
pub(crate) const P_INTERACT_SIZE: &str = "OfxParamPropInteractSize";
/// kOfxParamPropInteractSizeAspect。
pub(crate) const P_INTERACT_ASPECT: &str = "OfxParamPropInteractSizeAspect";
/// kOfxParamPropInteractMinimumSize。
pub(crate) const P_INTERACT_MIN_SIZE: &str = "OfxParamPropInteractMinimumSize";
/// kOfxParamPropInteractPreferedSize。
pub(crate) const P_INTERACT_PREF_SIZE: &str = "OfxParamPropInteractPreferedSize";
/// kOfxPropType。
pub(crate) const PROP_TYPE: &str = "OfxPropType";
/// kOfxPropName。
pub(crate) const PROP_NAME: &str = "OfxPropName";
/// kOfxPropLabel。
pub(crate) const PROP_LABEL: &str = "OfxPropLabel";
/// kOfxPropShortLabel。
pub(crate) const PROP_SHORT_LABEL: &str = "OfxPropShortLabel";
/// kOfxPropLongLabel。
pub(crate) const PROP_LONG_LABEL: &str = "OfxPropLongLabel";
/// kOfxPropIcon。
pub(crate) const PROP_ICON: &str = "OfxPropIcon";
/// kOfxTypeParameter。
pub(crate) const TYPE_PARAMETER: &str = "OfxTypeParameter";
fn cs(s: &str) -> CString {
// 静态 ASCII 常量,无内嵌 NUL。
CString::new(s).unwrap()
}
/// 参数值类别(param shim 的变长参数分发;与
/// cbits/ofx_param_shim.c 的 KIND_* 枚举逐字对应)。
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ParamKind {
/// Integer。
Int = 1,
/// Integer2D。
Int2 = 2,
/// Integer3D。
Int3 = 3,
/// Double。
Double = 4,
/// Double2D。
Double2 = 5,
/// Double3D。
Double3 = 6,
/// Boolean。
Bool = 7,
/// Choice。
Choice = 8,
/// RGB。
Rgb = 9,
/// RGBA。
Rgba = 10,
/// String。
Str = 11,
/// StrChoice。
StrChoice = 12,
}
/// OFX 类型字符串 → 值类别 + 维度(HS: ofxhParam.cpp `findType`)。
/// 无值类(PushButton/Group/Page)与 parametric(曲线值走
/// OfxParametricParameterSuite,无标量变长入口)返回 None。
pub(crate) fn kind_of_type(ofx_type: &str) -> Option<(ParamKind, usize)> {
match ofx_type {
TYPE_INTEGER => Some((ParamKind::Int, 1)),
TYPE_INTEGER2D => Some((ParamKind::Int2, 2)),
TYPE_INTEGER3D => Some((ParamKind::Int3, 3)),
TYPE_DOUBLE => Some((ParamKind::Double, 1)),
TYPE_DOUBLE2D => Some((ParamKind::Double2, 2)),
TYPE_DOUBLE3D => Some((ParamKind::Double3, 3)),
TYPE_BOOLEAN => Some((ParamKind::Bool, 1)),
TYPE_CHOICE => Some((ParamKind::Choice, 1)),
TYPE_STRING => Some((ParamKind::Str, 1)),
TYPE_STRCHOICE => Some((ParamKind::StrChoice, 1)),
TYPE_RGB => Some((ParamKind::Rgb, 3)),
TYPE_RGBA => Some((ParamKind::Rgba, 4)),
_ => None,
}
}
/// 数值类参数(Min/Max/DisplayMin/Max 表格适用;HS
/// `addNumericParamProps` 的 isDoubleParam || isIntParam ||
/// isColourParam)。
fn is_numeric_type(ofx_type: &str) -> bool {
matches!(
ofx_type,
TYPE_INTEGER
| TYPE_INTEGER2D
| TYPE_INTEGER3D
| TYPE_DOUBLE
| TYPE_DOUBLE2D
| TYPE_DOUBLE3D
| TYPE_RGB
| TYPE_RGBA
)
}
/// 该类型的默认 ParamValue(describe 期基线;HS 的属性默认在 props
/// 的 kOfxParamPropDefault,值语义等价)。
fn type_default(ofx_type: &str) -> ParamValue {
match kind_of_type(ofx_type) {
Some((ParamKind::Int, d)) | Some((ParamKind::Int2, d)) | Some((ParamKind::Int3, d)) => {
ParamValue::Int([0; 3], d)
}
Some((ParamKind::Double, d))
| Some((ParamKind::Double2, d))
| Some((ParamKind::Double3, d)) => ParamValue::Double([0.0; 3], d),
Some((ParamKind::Rgb, d)) | Some((ParamKind::Rgba, d)) => ParamValue::Color([0.0; 4], d),
Some((ParamKind::Bool, _)) => ParamValue::Bool(false),
Some((ParamKind::Choice, _)) => ParamValue::Choice(0),
Some((ParamKind::Str, _)) => ParamValue::String(cs("")),
Some((ParamKind::StrChoice, _)) => ParamValue::StrChoice(cs("")),
None => match ofx_type {
TYPE_BYTES | TYPE_CUSTOM => ParamValue::Bytes(Vec::new()),
TYPE_PUSHBUTTON => ParamValue::PushButton,
TYPE_GROUP | TYPE_PAGE => ParamValue::Container,
// parametric 默认 = 1 条恒等曲线(range 默认 (0,1))。
TYPE_PARAMETRIC => ParamValue::Parametric(vec![crate::param_curve::Curve::identity(
0.0, 1.0,
)]),
_ => ParamValue::Container, // 未知类型占位(paramDefine 已拒绝)
},
}
}
/// 数值属性表的值(Min/Max/Display 族;HS ofxhParam.cpp:420-449)。
/// `is_max` 选 ±f64::MAX / ±i32::MAX;colour 参数恒 0/1。
fn numeric_value(ofx_type: &str, kind: ParamKind, dim: usize, is_max: bool) -> Vec<Value> {
if ofx_type == TYPE_RGB || ofx_type == TYPE_RGBA {
// colour:display 范围 0..1,min/max 同。
let v = Value::Double(if is_max { 1.0 } else { 0.0 });
return vec![v; dim];
}
match kind {
ParamKind::Double | ParamKind::Double2 | ParamKind::Double3 => {
let v = Value::Double(if is_max { f64::MAX } else { f64::MIN });
vec![v; dim]
}
_ => {
let v = Value::Int(if is_max { i32::MAX } else { i32::MIN });
vec![v; dim]
}
}
}
/// 参数值(与 OFX 参数类型一一对应)。
#[derive(Clone, Debug, PartialEq)]
pub enum ParamValue {
/// kOfxParamTypeInteger / Integer2D / Integer3D。
Int([i32; 3], usize),
/// kOfxParamTypeDouble / Double2D / Double3D。
Double([f64; 3], usize),
/// kOfxParamTypeBoolean。
Bool(bool),
/// kOfxParamTypeChoice(选项索引)。
Choice(i32),
/// kOfxParamTypeString。
String(std::ffi::CString),
/// kOfxParamTypeRGB / RGBA。
Color([f64; 4], usize),
/// kOfxParamTypeStrChoice。
StrChoice(std::ffi::CString),
/// kOfxParamTypeBytes / Custom(不透明字节串)。
Bytes(Vec<u8>),
/// kOfxParamTypePushButton(无值,仅触发)。
PushButton,
/// kOfxParamTypeGroup / Page(容器,无值)。
Container,
/// kOfxParamTypeParametric:每维一条曲线(曲线模型见
/// [`crate::param_curve`];默认 = 1 条恒等曲线,维度由属性
/// `OfxParamPropParametricDimension` 决定,见
/// [`ParamDef::new`])。
Parametric(Vec<crate::param_curve::Curve>),
}
/// 参数定义(describe 产物,见 [`crate::descriptor::EffectDescriptor`])。
/// `#[repr(C)]` + props 在偏移 0(句柄约定,见 [`crate::suites::tag`])。
#[derive(Clone)]
#[repr(C)]
pub struct ParamDef {
/// 定义属性(label/hint/parent/coordinate-system/secret/
/// display min-max/choice 选项与排序等;describe 期预置
/// HostSupport 同款表格)。
pub props: PropertySet,
/// 参数名(OFX 标识)。
pub name: String,
/// OFX 类型字符串(kOfxParamType*)。
pub ofx_type: String,
/// 默认值(describe 后读取)。
pub default: ParamValue,
}
impl ParamDef {
/// 按 OFX 类型构建定义(镜像 HS ofxhParam.cpp:224-352:
/// universalProps + addStandardParamProps 的分类型属性表)。
pub(crate) fn new(name: &str, ofx_type: &str) -> Self {
let mut props = PropertySet::new();
let uname = name.to_string();
let utype = ofx_type.to_string();
// universalProps(HS ofxhParam.cpp:229-246)。
props.set_one(PROP_TYPE, Value::String(cs(TYPE_PARAMETER)));
props.set_one(P_SECRET, Value::Int(0));
props.set_one(P_HINT, Value::String(cs("")));
props.set_one(P_SCRIPT_NAME, Value::String(cs(&uname)));
props.set_one(P_PARENT, Value::String(cs("")));
props.set_one(P_ENABLED, Value::Int(1));
props.set_one(P_DATA_PTR, Value::Pointer(std::ptr::null_mut()));
props.set_one(P_TYPE, Value::String(cs(&utype)));
props.set_one(PROP_NAME, Value::String(cs(&uname)));
props.set_one(PROP_LABEL, Value::String(cs(&uname)));
props.set_one(PROP_SHORT_LABEL, Value::String(cs(&uname)));
props.set_one(PROP_LONG_LABEL, Value::String(cs(&uname)));
props.define(
PROP_ICON,
vec![Value::String(cs("")), Value::String(cs(""))],
);
// 值类参数(HS addValueParamProps,ofxhParam.cpp:352-380)。
if let Some((kind, dim)) = kind_of_type(ofx_type) {
props.set_one(P_IS_ANIMATING, Value::Int(0));
props.set_one(P_IS_AUTO_KEYING, Value::Int(0));
props.set_one(P_PERSISTANT, Value::Int(1));
props.set_one(P_EVALUATE_ON_CHANGE, Value::Int(1));
props.set_one(P_CAN_UNDO, Value::Int(1));
props.set_one(
P_CACHE_INVALIDATION,
Value::String(cs(V_INVALIDATE_VALUE_CHANGE)),
);
// 可动画性(HS ofxhParam.cpp:367-372:custom/string/
// boolean/choice 默认不可动画)。
let animates = ofx_type != TYPE_CUSTOM
&& ofx_type != TYPE_STRING
&& ofx_type != TYPE_BOOLEAN
&& ofx_type != TYPE_CHOICE;
props.set_one(P_ANIMATES, Value::Int(animates as i32));
props.define(P_DEFAULT, default_values(kind, dim));
// 数值类(HS addNumericParamProps,ofxhParam.cpp:391-455)。
if is_numeric_type(ofx_type) {
props.define(P_DISPLAY_MIN, numeric_value(ofx_type, kind, dim, false));
props.define(P_DISPLAY_MAX, numeric_value(ofx_type, kind, dim, true));
props.define(P_MIN, numeric_value(ofx_type, kind, dim, false));
props.define(P_MAX, numeric_value(ofx_type, kind, dim, true));
if matches!(
kind,
ParamKind::Double | ParamKind::Double2 | ParamKind::Double3
) {
props.set_one(P_INCREMENT, Value::Double(1.0));
props.set_one(P_DIGITS, Value::Int(2));
}
if ofx_type == TYPE_DOUBLE || ofx_type == TYPE_DOUBLE2D || ofx_type == TYPE_DOUBLE3D
{
props.set_one(P_DOUBLE_TYPE, Value::String(cs(V_DOUBLE_TYPE_PLAIN)));
props.set_one(P_DEFAULT_COORD_SYS, Value::String(cs(V_COORD_CANONICAL)));
if dim == 1 {
props.set_one(P_SHOW_TIME_MARKER, Value::Int(0));
}
}
if dim == 2 || dim == 3 {
let labels: Vec<Value> = ["x", "y", "z"][..dim]
.iter()
.map(|l| Value::String(cs(l)))
.collect();
props.define(P_DIMENSION_LABEL, labels);
}
}
}
// 分类型附加(HS addStandardParamProps,ofxhParam.cpp:248-301)。
match ofx_type {
TYPE_STRING => {
props.set_one(P_STRING_MODE, Value::String(cs(V_STRING_SINGLE_LINE)));
props.set_one(P_STRING_FILE_EXISTS, Value::Int(1));
}
TYPE_CHOICE => {
// 维度 0:选项数由插件 SetN 决定。
props.define(P_CHOICE_OPTION, vec![]);
}
TYPE_CUSTOM => {
props.set_one(P_CUSTOM_INTERP, Value::Pointer(std::ptr::null_mut()));
}
TYPE_PAGE => {
props.define(P_PAGE_CHILD, vec![]);
}
TYPE_GROUP => {
props.set_one(P_GROUP_OPEN, Value::Int(1));
}
TYPE_PARAMETRIC => {
// parametric(HS addValueParamProps(eDouble, 0) 的
// invariantProps + allParametric,ofxhParam.cpp:285-330):
// 值类 invariant 属性照旧;Animates=1(HS 的 animates 计算
// 对 parametric 为真);另加 4 个 parametric 专属属性。
// 数值属性表(Min/Max/Display)HS 也加(变量维 double),
// 但插件侧从不读 parametric 的数值属性(ofxsPropertyValidation
// 只校验本块 4 个 + 通用属性),本 crate 遵循
// is_numeric_type 的门控,不为 parametric 预置。
props.set_one(P_IS_ANIMATING, Value::Int(0));
props.set_one(P_IS_AUTO_KEYING, Value::Int(0));
props.set_one(P_PERSISTANT, Value::Int(1));
props.set_one(P_EVALUATE_ON_CHANGE, Value::Int(1));
props.set_one(P_CAN_UNDO, Value::Int(1));
props.set_one(
P_CACHE_INVALIDATION,
Value::String(cs(V_INVALIDATE_VALUE_CHANGE)),
);
props.set_one(P_ANIMATES, Value::Int(1));
props.set_one(P_PARAMETRIC_DIMENSION, Value::Int(1));
props.define(P_PARAMETRIC_UI_COLOUR, vec![]);
props.set_one(P_PARAMETRIC_INTERACT_BG, Value::Pointer(std::ptr::null_mut()));
props.define(
P_PARAMETRIC_RANGE,
vec![Value::Double(0.0), Value::Double(1.0)],
);
}
_ => {}
}
// 交互属性(HS addInteractParamProps,ofxhParam.cpp:305-317;
// group/page 除外)。
if ofx_type != TYPE_GROUP && ofx_type != TYPE_PAGE {
props.set_one(P_INTERACT_V1, Value::Pointer(std::ptr::null_mut()));
props.define(
P_INTERACT_SIZE,
vec![Value::Double(0.0), Value::Double(0.0)],
);
props.set_one(P_INTERACT_ASPECT, Value::Double(1.0));
props.define(
P_INTERACT_MIN_SIZE,
vec![Value::Double(10.0), Value::Double(10.0)],
);
props.define(P_INTERACT_PREF_SIZE, vec![Value::Int(10), Value::Int(10)]);
}
Self {
props,
name: uname,
ofx_type: utype,
default: type_default(ofx_type),
}
}
/// 值类别(变长参数分发用;无值类返回 None)。
pub(crate) fn kind(&self) -> Option<ParamKind> {
kind_of_type(&self.ofx_type).map(|(k, _)| k)
}
}
/// kOfxParamPropDefault 的属性值(HS ofxhParam.cpp:376-377)。
fn default_values(kind: ParamKind, dim: usize) -> Vec<Value> {
match kind {
ParamKind::Int
| ParamKind::Int2
| ParamKind::Int3
| ParamKind::Bool
| ParamKind::Choice => {
vec![Value::Int(0); dim.max(1)]
}
ParamKind::Double
| ParamKind::Double2
| ParamKind::Double3
| ParamKind::Rgb
| ParamKind::Rgba => vec![Value::Double(0.0); dim.max(1)],
ParamKind::Str | ParamKind::StrChoice => vec![Value::String(cs(""))],
}
}
/// 参数实例(createInstance 后由 [`ParamDef`] 实例化)。
/// `#[repr(C)]` + props 在偏移 0(句柄约定)。
#[repr(C)]
pub struct ParamInstance {
/// 实例级属性(当前值镜像等)。
pub props: PropertySet,
/// 对应定义。
pub def: ParamDef,
/// 当前值(节点桥与 OFX 侧的同步点)。
value: std::sync::Mutex<ParamValue>,
}
impl ParamInstance {
/// 从定义实例化(createInstance 路径调用)。实例 props 是定义
/// props 的深拷贝(HS: SetInstance::makeParam 的 descriptor 属性
/// 复制语义——插件在实例期读 label/min/max 等)。
pub fn from_def(def: ParamDef) -> Self {
let value = def.default.clone();
let props = def.props.clone();
Self {
props,
def,
value: std::sync::Mutex::new(value),
}
}
/// 读当前值。
pub fn get(&self) -> ParamValue {
self.value.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
/// 写当前值(OFX 语义:paramSetValue action 语义,不打节点桥)。
pub fn set_ofx(&self, value: ParamValue) {
*self.value.lock().unwrap_or_else(|e| e.into_inner()) = value;
}
/// 字符串值的内驻指针(param suite 的 get_string 用;指向实例
/// 存储,下次 set 前有效——克隆的 CString 指针会悬垂,不能给)。
pub(crate) fn string_ptr(&self) -> Option<*const std::ffi::c_char> {
let v = self.value.lock().unwrap_or_else(|e| e.into_inner());
match &*v {
ParamValue::String(s) | ParamValue::StrChoice(s) => Some(s.as_ptr()),
_ => None,
}
}
/// 从 oaknode 输入值写入(节点→插件方向)。类型映射表逐行对照
/// C++ 的 `valueconvert`/`paraminstance.h`(`node_get` 的镜像):
/// INT→Integer、FLOAT→Double、BOOL→Boolean、COMBO→Choice、
/// COLOR→RGB/RGBA、VEC2/VEC3→Double(2D/3D)/Integer(2D/3D)。
/// 维度不齐按 OFX 语义截断/补零(缺失元素按 0)。字符串族
/// (OAKNODE_VALUE_STRING)的 POD 不携带数据——此路径不改值
/// (走 facade 的字符串 API,见 `include/plugin/instance.h`);
/// parametric 同理(曲线 JSON 文本经渲染期注入
/// [`crate::node_factory`] 的 set_text_param 写回,见
/// `crate::node_factory::execute_plugin_job`)。
/// 类型不匹配 → 忽略(保持现值;C++ `node_get` 失败时参数不回写)。
pub fn set_from_node(&self, node_value: &crate::node::Value) {
if let Some(pv) = param_value_from_node(node_value, &self.def.ofx_type) {
self.set_ofx(pv);
}
}
}
/// 节点值 → ParamValue(按参数类型解释;字符串族走专用路径)。
/// 镜像 `set_from_node` 的映射表;render 驱动的参数覆盖
/// (apply_param_overrides)复用同一转换。
pub(crate) fn param_value_from_node(
v: &crate::node::Value,
ofx_type: &str,
) -> Option<ParamValue> {
use crate::node::node_value_type as T;
match ofx_type {
TYPE_DOUBLE => (v.r#type == T::FLOAT).then(|| ParamValue::Double([v.f[0], 0.0, 0.0], 1)),
TYPE_DOUBLE2D => (v.r#type == T::VEC2).then(|| ParamValue::Double([v.f[0], v.f[1], 0.0], 2)),
TYPE_DOUBLE3D => {
(v.r#type == T::VEC3).then(|| ParamValue::Double([v.f[0], v.f[1], v.f[2]], 3))
}
TYPE_INTEGER => (v.r#type == T::INT).then(|| ParamValue::Int([v.num as i32, 0, 0], 1)),
TYPE_INTEGER2D | TYPE_INTEGER3D => {
let dim = if ofx_type == TYPE_INTEGER2D { 2 } else { 3 };
Some(ParamValue::Int(
[v.f[0] as i32, v.f[1] as i32, v.f[2] as i32],
dim,
))
}
TYPE_BOOLEAN => (v.r#type == T::BOOL).then(|| ParamValue::Bool(v.num != 0)),
TYPE_CHOICE => (v.r#type == T::COMBO).then(|| ParamValue::Choice(v.num as i32)),
TYPE_RGB => {
(v.r#type == T::COLOR).then(|| ParamValue::Color([v.f[0], v.f[1], v.f[2], 0.0], 3))
}
TYPE_RGBA => (v.r#type == T::COLOR)
.then(|| ParamValue::Color([v.f[0], v.f[1], v.f[2], v.f[3]], 4)),
_ => None, // 字符串/无值类:POD 无数据,不改值
}
}
/// ParamValue → [`crate::node::Value`](插件→节点方向;
/// 字符串族经 [`crate::node::set_input_string_undoable`])。
/// 镜像 C++ `paraminstance.h` 的 `value_int`/`value_double`/
/// `value_vec`/`value_color` 构造:RGB 颜色补 alpha=1(C++
/// `RGBInstance::set` 的 `value_color(r,g,b,1.0)`)。无值类与 Bytes
/// 无节点对应 → None。
pub(crate) fn to_node_value(v: &ParamValue) -> Option<crate::node::Value> {
use crate::node::node_value_type as T;
let mut out = crate::node::Value::default();
match v {
ParamValue::Double(d, 1) => {
out.r#type = T::FLOAT;
out.f = [d[0], 0.0, 0.0, 0.0];
}
ParamValue::Double(d, 2) => {
out.r#type = T::VEC2;
out.f = [d[0], d[1], 0.0, 0.0];
}
ParamValue::Double(d, 3) => {
out.r#type = T::VEC3;
out.f = [d[0], d[1], d[2], 0.0];
}
ParamValue::Double(d, _) => {
out.r#type = T::FLOAT;
out.f = [d[0], 0.0, 0.0, 0.0];
}
ParamValue::Int(a, 1) => {
out.r#type = T::INT;
out.num = a[0] as i64;
}
ParamValue::Int(a, 2) => {
out.r#type = T::VEC2;
out.f = [a[0] as f64, a[1] as f64, 0.0, 0.0];
}
ParamValue::Int(a, 3) => {
out.r#type = T::VEC3;
out.f = [a[0] as f64, a[1] as f64, a[2] as f64, 0.0];
}
ParamValue::Bool(b) => {
out.r#type = T::BOOL;
out.num = *b as i64;
}
ParamValue::Choice(c) => {
out.r#type = T::COMBO;
out.num = *c as i64;
}
ParamValue::Color(c, 3) => {
out.r#type = T::COLOR;
out.f = [c[0], c[1], c[2], 1.0];
}
ParamValue::Color(c, 4) => {
out.r#type = T::COLOR;
out.f = *c;
}
_ => return None,
}
Some(out)
}
/// 参数实例集(实例级)。
pub struct ParamSetInstance {
/// 全部参数(定义顺序稳定;Box 保证句柄地址稳定)。
pub params: Vec<Box<ParamInstance>>,
}
impl ParamSetInstance {
/// 按名查找。
pub fn find(&self, name: &str) -> Option<&ParamInstance> {
self.params
.iter()
.find(|p| p.def.name == name)
.map(|b| b.as_ref())
}
/// 快照(内省 C ABI 与快照测试用)。
///
/// 声明原为 `Vec<(&str, &ParamValue)>`:值在 Mutex 内,无法返回
/// 活引用——改为拥有型 `(String, ParamValue)`(内省语义不变)。
pub fn snapshot(&self) -> Vec<(String, ParamValue)> {
self.params
.iter()
.map(|p| (p.def.name.clone(), p.get()))
.collect()
}
}
/// 插件 → 节点方向的回写入口(instanceChanged action 触发)。
/// 经 [`crate::node`] 定位绑定节点(身份注册表),再经
/// `oak_undo::undocommand::UndoCommand` 包成 undoable 修改。未绑定
/// 节点或身份查无时 no-op(单库化后身份注册表重建为
/// [`crate::node::register_node`]/[`crate::node::node_from_identity`];
/// facade 装配期登记,project 释放后弱条目自然失效)。
///
/// 语义对照 C++ `paraminstance.h` 的 `set()` 路径(`detail::node_set`/
/// `node_set_at`):
/// - 只回写 [`ChangeReason::PluginEdited`](插件自改)。UserEdited/
/// TimeChanged 是宿主侧变更,值已由 [`ParamInstance::set_from_node`]
/// 同步,不重复写回;
/// - 字符串族经 [`crate::node::set_input_string_undoable`]
/// (POD 不携带字符串数据);parametric 曲线同样经该字符串 setter
/// 以 JSON 文本写回输入([`crate::param_curve::curves_to_json`],
/// 与标量回写同一 undo 语义——插件在实例上改曲线 → 节点输入更新,
/// 工程序列化随标准值保留);
/// - 无值类(PushButton/Group/Page)与 Bytes 无节点对应 → no-op;
/// - 编辑事务内([`crate::instance::Instance::in_edit`])并入 multi
/// 命令,否则单命令立即 redo 生效(C++ `submit_undo_command`)。
pub(crate) fn notify_instance_changed(
instance: &crate::instance::Instance,
param_name: &str,
reason: ChangeReason,
) {
use crate::node;
use std::sync::atomic::Ordering;
if !matches!(reason, ChangeReason::PluginEdited) {
return;
}
// 未绑定节点 → no-op(C++:!node_.ctx 时 set 只写本地值)。
let node_id = instance.node_identity.load(Ordering::Relaxed);
if node_id == 0 {
return;
}
// 身份查无(未登记 / project 已释放)→ no-op。
let Some(node_ref) = node::node_from_identity(node_id) else {
return;
};
let Some(param) = instance.params.find(param_name) else {
return;
};
let value = param.get();
let label = format!("Change {param_name}");
match to_node_value(&value) {
Some(nv) => {
if let Ok(cmd) = node::set_input_undoable(&node_ref, param_name, &nv) {
instance.submit_undo_command(cmd, &label);
}
}
None => match &value {
ParamValue::String(s) | ParamValue::StrChoice(s) => {
let Ok(s) = s.to_str() else {
return;
};
if let Ok(cmd) = node::set_input_string_undoable(&node_ref, param_name, s) {
instance.submit_undo_command(cmd, &label);
}
}
// parametric:曲线序列化为 JSON 文本写回输入(节点输入是
// Parametric 声明类型的 Text 值;经字符串 setter 存储)。
ParamValue::Parametric(curves) => {
let json = crate::param_curve::curves_to_json(curves);
if let Ok(cmd) = node::set_input_string_undoable(&node_ref, param_name, &json) {
instance.submit_undo_command(cmd, &label);
}
}
_ => {} // 无值类 / Bytes:无节点对应
},
}
}
/// instanceChanged 的原因(OFX kOfxChange*)。
#[derive(Clone, Copy, Debug)]
pub enum ChangeReason {
/// 用户编辑。
UserEdited,
/// 插件自改。
PluginEdited,
/// 时间变化。
TimeChanged,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::node::node_value_type as T;
fn param(ofx_type: &str) -> ParamInstance {
ParamInstance::from_def(ParamDef::new("p", ofx_type))
}
/// ParamValue → oaknode Value 的类型映射表(镜像 C++
/// paraminstance.h 的 value_* 构造)。
#[test]
fn to_node_value_mapping() {
use crate::node::Value;
let c = |t: i32| Value {
r#type: t,
num: 0,
den: 0,
f: [0.0; 4],
};
// Double 族。
let v = to_node_value(&ParamValue::Double([1.5, 0.0, 0.0], 1)).unwrap();
assert_eq!(v, Value::float(1.5));
let v = to_node_value(&ParamValue::Double([1.0, 2.0, 0.0], 2)).unwrap();
assert_eq!(v, Value::vec(&[1.0, 2.0]));
let v = to_node_value(&ParamValue::Double([1.0, 2.0, 3.0], 3)).unwrap();
assert_eq!(v, Value::vec(&[1.0, 2.0, 3.0]));
// Int 族(2D/3D 升格为 VEC2/VEC3 浮点载荷)。
let v = to_node_value(&ParamValue::Int([7, 0, 0], 1)).unwrap();
assert_eq!(v, Value::int(7));
let v = to_node_value(&ParamValue::Int([1, 2, 0], 2)).unwrap();
assert_eq!(v, Value::vec(&[1.0, 2.0]));
// Bool / Choice。
assert_eq!(
to_node_value(&ParamValue::Bool(true)).unwrap(),
Value::bool_(true)
);
assert_eq!(
to_node_value(&ParamValue::Choice(3)).unwrap(),
Value::combo(3)
);
// Color:RGB 补 alpha=1(C++ oracle),RGBA 全透传。
let v = to_node_value(&ParamValue::Color([0.1, 0.2, 0.3, 0.0], 3)).unwrap();
assert_eq!(v, Value::color(0.1, 0.2, 0.3, 1.0));
let v = to_node_value(&ParamValue::Color([0.1, 0.2, 0.3, 0.9], 4)).unwrap();
assert_eq!(v, Value::color(0.1, 0.2, 0.3, 0.9));
// 无值类 / Bytes → None(无节点对应)。
assert_eq!(to_node_value(&ParamValue::PushButton), None);
assert_eq!(to_node_value(&ParamValue::Container), None);
assert_eq!(to_node_value(&ParamValue::Bytes(vec![1])), None);
// 字符串族走专用桥(POD 路径 None)。
assert_eq!(to_node_value(&ParamValue::String(cs(""))), None);
let _ = c(T::NONE); // 哨兵:类型常量可达
}
/// type_default 的无值类/字节族基线(paramDefine 拒绝前的兜底)。
#[test]
fn type_default_edge_cases() {
assert!(matches!(type_default(TYPE_BYTES), ParamValue::Bytes(_)));
assert!(matches!(type_default(TYPE_CUSTOM), ParamValue::Bytes(_)));
assert!(matches!(
type_default(TYPE_PUSHBUTTON),
ParamValue::PushButton
));
assert!(matches!(type_default(TYPE_GROUP), ParamValue::Container));
assert!(matches!(type_default(TYPE_PAGE), ParamValue::Container));
// 未知类型占位(paramDefine 已拒绝,此处兜底)。
assert!(matches!(
type_default("OfxParamTypeBogus"),
ParamValue::Container
));
// 数值族的默认 0。
assert!(matches!(
type_default(TYPE_INTEGER),
ParamValue::Int([0, 0, 0], 1)
));
assert!(matches!(
type_default(TYPE_DOUBLE2D),
ParamValue::Double([0.0, 0.0, 0.0], 2)
));
assert!(matches!(
type_default(TYPE_RGBA),
ParamValue::Color([0.0, 0.0, 0.0, 0.0], 4)
));
}
/// parametric 的默认:1 条恒等曲线;4 个专属属性就位
/// (dimension=1、range=(0,1)、UIColour 未设、interact 背景 NULL)。
#[test]
fn parametric_type_default() {
assert!(matches!(
type_default(TYPE_PARAMETRIC),
ParamValue::Parametric(ref c) if c.len() == 1 && c[0].len() == 2
));
let d = ParamDef::new("curve", TYPE_PARAMETRIC);
assert!(matches!(d.default, ParamValue::Parametric(ref c) if c.len() == 1));
assert!(matches!(
d.props.get(P_PARAMETRIC_DIMENSION, 0),
Some(Value::Int(1))
));
assert!(matches!(
d.props.get(P_PARAMETRIC_RANGE, 0),
Some(Value::Double(0.0))
));
assert!(matches!(
d.props.get(P_PARAMETRIC_RANGE, 1),
Some(Value::Double(1.0))
));
assert_eq!(d.props.dimension(P_PARAMETRIC_UI_COLOUR), 0);
assert!(matches!(
d.props.get(P_PARAMETRIC_INTERACT_BG, 0),
Some(Value::Pointer(p)) if p.is_null()
));
// 默认曲线求值为恒等。
if let ParamValue::Parametric(curves) = &d.default {
assert_eq!(curves[0].evaluate(0.5), 0.5);
}
}
/// set_from_node 的维度截断/补零与字符串静默路径。
#[test]
fn set_from_node_dimension_rules() {
// Integer2D 缺第三维补零;浮点截断。
let p = param(TYPE_INTEGER2D);
p.set_from_node(&crate::node::Value::vec(&[1.9, 2.9]));
assert_eq!(p.get(), ParamValue::Int([1, 2, 0], 2));
// StrChoice 参数遇 STRING 类型:POD 无数据 → 不改值。
let p = param(TYPE_STRCHOICE);
p.set_from_node(&crate::node::Value::string());
assert!(matches!(p.get(), ParamValue::StrChoice(_)));
// Bytes/Custom 参数:任意节点值都不改(无映射)。
let p = param(TYPE_CUSTOM);
p.set_from_node(&crate::node::Value::float(3.0));
assert!(matches!(p.get(), ParamValue::Bytes(_)));
}
}
+734
View File
@@ -0,0 +1,734 @@
// 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/>.
//! 参数化曲线模型(OfxParametricParameterSuite 的宿主侧数据与求值)。
//!
//! 曲线 = 按 key 升序排列的控制点列表,每个控制点携带 Hermite 切线
//! (slope)。suite([`crate::suites::parametric`])只暴露 key/value
//! 编辑入口,slope 一律由 [`Curve::recompute_slopes`] 自动计算——
//! 内部点用两侧差分(centered finite difference),端点用单侧差分;
//! 字段保持 `pub`,便于测试/宿主显式编辑斜率。
//!
//! 求值 = 分段三次 Hermite(见 [`Curve::evaluate`])。这是 OFX 规范
//! 建议宿主采用的"曲线编辑器式"表示(ofxParametricParam.h 的
//! parametric 参数文档),与贝塞尔形式等价(Hermite 切线 × 段长即
//! 贝塞尔控制臂)。
/// 曲线控制点:`key`(parametric 位置,定义域由
/// `OfxParamPropParametricRange` 限定)、`value`(求值结果)、
/// `slope`(该点处的一阶导数,三次 Hermite 的切线)。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ControlPoint {
/// parametric 位置(x)。
pub key: f64,
/// 求值结果(y)。
pub value: f64,
/// 一阶导数(自动差分 / 显式编辑)。
pub slope: f64,
}
impl ControlPoint {
/// 按 key/value 构造(slope 由 [`Curve::recompute_slopes`] 填入)。
pub fn new(key: f64, value: f64) -> Self {
Self {
key,
value,
slope: 0.0,
}
}
}
/// 一条参数曲线:控制点按 key 升序(不变量;由本模块的修改接口
/// 维护)。
#[derive(Clone, Debug, PartialEq)]
pub struct Curve {
/// 控制点序列(key 升序,无重复 key)。
pub points: Vec<ControlPoint>,
}
impl Curve {
/// 空曲线(`DeleteAllControlPoints` 后的状态;求值退化为恒等,
/// 见 [`Curve::evaluate`])。
pub fn empty() -> Self {
Self {
points: Vec::new(),
}
}
/// 恒等曲线:`{(lo, lo), (hi, hi)}` + 自动 slope —— parametric
/// 参数的默认 default(ofxParametricParam.h:"The default default
/// value of a parametric curve is to be an identity lookup")。
/// `lo`/`hi` 来自 `OfxParamPropParametricRange`(默认 (0,1))。
pub fn identity(lo: f64, hi: f64) -> Self {
let mut c = Self {
points: vec![
ControlPoint::new(lo, lo),
ControlPoint::new(hi, hi),
],
};
c.recompute_slopes();
c
}
/// 由 key/value 对构造(slope 自动差分;按传入顺序——调用方
/// 保证升序,或经 [`Curve::upsert`] 逐点插入)。
pub fn from_pairs(pairs: &[(f64, f64)]) -> Self {
let mut c = Self {
points: pairs
.iter()
.map(|&(k, v)| ControlPoint::new(k, v))
.collect(),
};
c.recompute_slopes();
c
}
/// 控制点数。
pub fn len(&self) -> usize {
self.points.len()
}
/// 是否为空(`DeleteAllControlPoints` 后)。
pub fn is_empty(&self) -> bool {
self.points.is_empty()
}
/// 第 `i` 个控制点(越界 → None)。
pub fn nth(&self, i: usize) -> Option<&ControlPoint> {
self.points.get(i)
}
/// 重算全部 slope:内部点中心差分(两侧跨距),端点单侧差分;
/// 单点/空曲线无差分 → slope 0。修改 key/value 后必须调用,
/// 否则 Hermite 切线滞后于控制点几何。
pub fn recompute_slopes(&mut self) {
let n = self.points.len();
for i in 0..n {
self.points[i].slope = slope_at(&self.points, i);
}
}
/// 三次 Hermite 求值。
///
/// - 空曲线:恒等(f(x) = x)——与"默认 default 是恒等查找"
/// 一致,`DeleteAllControlPoints` 后曲线退化为中性恒等,无端点
/// 可钳制,直接返回 x;
/// - 单点曲线:常数(该点 value);
/// - x 在首/末 key 之外:钳制到端点值(任务/规范:越界 key
/// 钳制到端点值)。
///
/// 数学:段 [x0, x1] 上令 t = (x - x0)/(x1 - x0),h = x1 - x0,
/// 三次 Hermite 基函数
/// h00 = 2t³ - 3t² + 1, h01 = -2t³ + 3t²
/// h10 = t³ - 2t² + t, h11 = t³ - t²
/// f(x) = h00·y0 + h01·y1 + h·(h10·m0 + h11·m1)。
/// slope 为 1 的恒等曲线恰退化为 f(x) = x(端点钳制外)。
pub fn evaluate(&self, x: f64) -> f64 {
let n = self.points.len();
if n == 0 {
return x;
}
if n == 1 {
return self.points[0].value;
}
if x <= self.points[0].key {
return self.points[0].value;
}
if x >= self.points[n - 1].key {
return self.points[n - 1].value;
}
// 定位所在段:points[i].key <= x < points[i+1].key。
let i = self.points.partition_point(|p| p.key <= x) - 1;
let a = self.points[i];
let b = self.points[i + 1];
let h = b.key - a.key;
if h <= 0.0 {
return a.value; // 防御:重复 key(不变量保证不出现)
}
let t = (x - a.key) / h;
let t2 = t * t;
let t3 = t2 * t;
let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
let h01 = -2.0 * t3 + 3.0 * t2;
let h10 = t3 - 2.0 * t2 + t;
let h11 = t3 - t2;
h00 * a.value + h01 * b.value + h * (h10 * a.slope + h11 * b.slope)
}
/// 放入 (key, value):同 key 已存在 → 覆盖其值(返回 false);
/// 否则按 key 升序插入(返回 true)。随后重算 slope。
/// 这是 Add 与 SetNth 的公共落点(SetNth 先移除再落点)。
pub fn upsert(&mut self, key: f64, value: f64) -> bool {
if let Some(p) = self.points.iter_mut().find(|p| p.key == key) {
p.value = value;
self.recompute_slopes();
return false;
}
let idx = self.points.partition_point(|p| p.key < key);
self.points.insert(idx, ControlPoint::new(key, value));
self.recompute_slopes();
true
}
/// 改第 `nth` 个控制点为 (key, value)。key 变化可能破坏有序性
/// (ofxParametricParam.h:SetNthControlPoint 的 key 可前移/后移
/// 到其他点之前/之后)——先移除再按 key 插入;新 key 撞上其他
/// 点的 key 时按覆盖语义处理。nth 越界 → Err(())。
pub fn set_nth(&mut self, nth: usize, key: f64, value: f64) -> Result<(), ()> {
if nth >= self.points.len() {
return Err(());
}
self.points.remove(nth);
self.upsert(key, value);
Ok(())
}
/// 删第 `nth` 个控制点(nth 越界 → Err(()));随后重算 slope。
pub fn delete_nth(&mut self, nth: usize) -> Result<(), ()> {
if nth >= self.points.len() {
return Err(());
}
self.points.remove(nth);
self.recompute_slopes();
Ok(())
}
/// 删除全部控制点(`DeleteAllControlPoints`)。
pub fn clear(&mut self) {
self.points.clear();
}
}
// ---- 曲线集 ↔ JSON(节点输入 / 工程序列化的值载荷)--------------------
//
// 格式(确定性、紧凑,无空白):
// {"curves":[[{"key":0.0,"value":0.0,"slope":1.0},...],...]}
// 外层按 dimension 顺序一维一条曲线;每维一个控制点对象,字段序固定
// key/value/slope。数值用 Rust 最短往返格式化(`{}`)。非有限值 JSON
// 无标准写法,取对称 token:NaN → `null`,+Inf → `"inf"`,
// -Inf → `"-inf"`(字符串字面量;解析器对称处理,有限值恒为裸数字)。
// 解析器容忍空白与字段乱序;结构不符 → None(调用方按字符串族静默
// 路径处理)。手写实现,不引入 serde(crate 无该依赖)。
/// 曲线集 → JSON(节点输入默认值 / 插件回写节点输入的载荷)。
pub fn curves_to_json(curves: &[Curve]) -> String {
let mut out =
String::with_capacity(8 + 12 * curves.iter().map(|c| c.len()).sum::<usize>());
out.push_str("{\"curves\":[");
for (ci, c) in curves.iter().enumerate() {
if ci > 0 {
out.push(',');
}
out.push('[');
for (pi, p) in c.points.iter().enumerate() {
if pi > 0 {
out.push(',');
}
out.push_str("{\"key\":");
push_num(&mut out, p.key);
out.push_str(",\"value\":");
push_num(&mut out, p.value);
out.push_str(",\"slope\":");
push_num(&mut out, p.slope);
out.push('}');
}
out.push(']');
}
out.push_str("]}");
out
}
/// JSON → 曲线集(格式见 [`curves_to_json`];结构不符 → None)。
pub fn curves_from_json(text: &str) -> Option<Vec<Curve>> {
let mut p = JsonParser {
bytes: text.as_bytes(),
pos: 0,
};
p.skip_ws();
if !p.eat(b'{') {
return None;
}
p.skip_ws();
if p.parse_string()?.as_str() != "curves" {
return None;
}
p.skip_ws();
if !p.eat(b':') {
return None;
}
p.skip_ws();
let mut curves = Vec::new();
if p.eat(b'[') {
loop {
p.skip_ws();
if p.eat(b']') {
break;
}
curves.push(p.parse_curve()?);
p.skip_ws();
if p.eat(b',') {
continue;
}
if p.eat(b']') {
break;
}
return None;
}
} else {
return None;
}
p.skip_ws();
if !p.eat(b'}') {
return None;
}
p.skip_ws();
if p.pos != p.bytes.len() {
return None;
}
Some(curves)
}
/// 单个数值 → JSON token(有限值裸数字;NaN/±Inf 见模块文档)。
fn push_num(out: &mut String, v: f64) {
if v.is_nan() {
out.push_str("null");
} else if v == f64::INFINITY {
out.push_str("\"inf\"");
} else if v == f64::NEG_INFINITY {
out.push_str("\"-inf\"");
} else {
out.push_str(&format!("{v}"));
}
}
/// 手写 JSON 解析器(仅本格式的子集;字段名无转义引号,控制点字段
/// 均为固定标识符)。
struct JsonParser<'a> {
bytes: &'a [u8],
pos: usize,
}
impl<'a> JsonParser<'a> {
fn skip_ws(&mut self) {
while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_whitespace() {
self.pos += 1;
}
}
fn eat(&mut self, byte: u8) -> bool {
if self.bytes.get(self.pos) == Some(&byte) {
self.pos += 1;
true
} else {
false
}
}
/// 原样匹配一段字节(字段名;不做字符串语义)。
fn eat_str(&mut self, want: &[u8]) -> bool {
if self.bytes[self.pos..].starts_with(want) {
self.pos += want.len();
true
} else {
false
}
}
/// 引号字符串(无转义;字段名/`"inf"` token 用)。
fn parse_string(&mut self) -> Option<String> {
if !self.eat(b'"') {
return None;
}
let start = self.pos;
while self.pos < self.bytes.len() && self.bytes[self.pos] != b'"' {
self.pos += 1;
}
let s = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?.to_string();
if !self.eat(b'"') {
return None;
}
Some(s)
}
/// 数值 token:`null` → NaN;`"inf"`/`"-inf"` → ±∞;否则裸数字
/// (`f64::from_str`,上溢 → ±∞,与 `{}` 最短往返格式对称)。
fn parse_num(&mut self) -> Option<f64> {
if self.eat_str(b"null") {
return Some(f64::NAN);
}
if self.bytes.get(self.pos) == Some(&b'"') {
return match self.parse_string()?.as_str() {
"inf" => Some(f64::INFINITY),
"-inf" => Some(f64::NEG_INFINITY),
_ => None,
};
}
let start = self.pos;
while self.pos < self.bytes.len()
&& matches!(
self.bytes[self.pos],
b'-' | b'+' | b'.' | b'0'..=b'9' | b'e' | b'E'
)
{
self.pos += 1;
}
if self.pos == start {
return None;
}
std::str::from_utf8(&self.bytes[start..self.pos])
.ok()?
.parse()
.ok()
}
/// 一条曲线:`[` 控制点* `]`(控制点按 key 升序存储,解析按原序)。
fn parse_curve(&mut self) -> Option<Curve> {
if !self.eat(b'[') {
return None;
}
let mut points = Vec::new();
loop {
self.skip_ws();
if self.eat(b']') {
break;
}
points.push(self.parse_point()?);
self.skip_ws();
if self.eat(b',') {
continue;
}
if self.eat(b']') {
break;
}
return None;
}
Some(Curve { points })
}
/// 一个控制点:`{` ("name" `:` 数值)* `}`(字段乱序可;未知字段
/// 拒绝)。
fn parse_point(&mut self) -> Option<ControlPoint> {
if !self.eat(b'{') {
return None;
}
let mut key = None;
let mut value = None;
let mut slope = None;
loop {
self.skip_ws();
if self.eat(b'}') {
break;
}
let name = self.parse_string()?;
self.skip_ws();
if !self.eat(b':') {
return None;
}
self.skip_ws();
let v = self.parse_num()?;
match name.as_str() {
"key" => key = Some(v),
"value" => value = Some(v),
"slope" => slope = Some(v),
_ => return None,
}
self.skip_ws();
if self.eat(b',') {
continue;
}
if self.eat(b'}') {
break;
}
return None;
}
Some(ControlPoint {
key: key?,
value: value?,
slope: slope.unwrap_or(0.0),
})
}
}
/// 第 `i` 点处的差分斜率(不重算,供 [`Curve::recompute_slopes`])。
/// 内部点:中心差分 (y_{i+1} - y_{i-1}) / (x_{i+1} - x_{i-1});
/// 端点:单侧差分;单点/空曲线:0。防御重复 key 时除零 → 0。
fn slope_at(points: &[ControlPoint], i: usize) -> f64 {
let n = points.len();
if n < 2 {
return 0.0;
}
let (a, b) = if i == 0 {
(&points[0], &points[1])
} else if i == n - 1 {
(&points[n - 2], &points[n - 1])
} else {
(&points[i - 1], &points[i + 1])
};
let dx = b.key - a.key;
if dx == 0.0 {
return 0.0;
}
(b.value - a.value) / dx
}
#[cfg(test)]
mod tests {
use super::*;
fn close(a: f64, b: f64, eps: f64) -> bool {
(a - b).abs() <= eps
}
/// 恒等曲线:{(0,0),(1,1)} + 自动 slope(1,1)→ Hermite 恰为
/// f(x) = x(数学上精确,浮点逐位不保证——近似比较);非默认
/// range 同样恒等。
#[test]
fn identity_curve_evaluates_to_x() {
let c = Curve::identity(0.0, 1.0);
assert_eq!(c.len(), 2);
assert_eq!(
c.points[0],
ControlPoint {
key: 0.0,
value: 0.0,
slope: 1.0
}
);
assert_eq!(
c.points[1],
ControlPoint {
key: 1.0,
value: 1.0,
slope: 1.0
}
);
for x in [0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0] {
assert!(close(c.evaluate(x), x, 1e-12), "identity at {x}");
}
// 非默认 range(插件改 OfxParamPropParametricRange 后,
// 新曲线的默认 default 相应平移)。
let c = Curve::identity(0.0, 255.0);
assert!(close(c.evaluate(128.0), 128.0, 1e-12));
}
/// 单段抛物线形状:{(0,0),(0.5,0.25),(1,1)}(y = x² 采样)。
/// 自动 slope = (0.5, 1, 1.5)(端点单侧、中点中心差分);
/// 求值精确等于分段三次 Hermite 的解析值(过控制点、两侧
/// 单调递增、中点手算值)。
#[test]
fn parabola_shape_honours_hermite() {
let c = Curve::from_pairs(&[(0.0, 0.0), (0.5, 0.25), (1.0, 1.0)]);
assert_eq!(
c.points.iter().map(|p| p.slope).collect::<Vec<_>>(),
vec![0.5, 1.0, 1.5]
);
// 插值性质:控制点处精确命中。
assert_eq!(c.evaluate(0.0), 0.0);
assert_eq!(c.evaluate(0.5), 0.25);
assert_eq!(c.evaluate(1.0), 1.0);
// 中点解析值(t = 1/2 段内,精确二进制分数)。
assert_eq!(c.evaluate(0.125), 0.05078125);
assert_eq!(c.evaluate(0.25), 0.09375);
assert_eq!(c.evaluate(0.75), 0.59375);
// 形状:单调递增;首段在抛物线 y = x² 之上(Hermite 端点
// 用弦斜率、中点用中心差分 → 首段整体上凸)。
let xs = [0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9];
for w in xs.windows(2) {
assert!(c.evaluate(w[0]) < c.evaluate(w[1]));
}
assert!(c.evaluate(0.25) > 0.25 * 0.25); // 高于抛物线采样点
}
/// 越界钳制:x 在首/末 key 之外 → 端点值。
#[test]
fn out_of_range_clamps_to_endpoints() {
let c = Curve::from_pairs(&[(0.2, 0.3), (0.8, 0.9)]);
assert_eq!(c.evaluate(-100.0), 0.3);
assert_eq!(c.evaluate(0.19), 0.3);
assert_eq!(c.evaluate(0.2), 0.3);
assert_eq!(c.evaluate(0.81), 0.9);
assert_eq!(c.evaluate(100.0), 0.9);
}
/// 增删点后求值正确:upsert 新点 → 该点命中、重排有序;删除后
/// 恢复;同 key 覆盖不增点。
#[test]
fn upsert_and_delete_keep_evaluation_consistent() {
let mut c = Curve::from_pairs(&[(0.0, 0.0), (1.0, 1.0)]);
// 插入中点(返回 true = 新增),求值在其 key 处精确命中。
assert!(c.upsert(0.3, 0.7));
assert_eq!(c.len(), 3);
assert_eq!(c.evaluate(0.3), 0.7);
// 有序性保持。
let keys: Vec<f64> = c.points.iter().map(|p| p.key).collect();
assert_eq!(keys, vec![0.0, 0.3, 1.0]);
// 同 key 覆盖(返回 false = 覆盖),数量不变。
assert!(!c.upsert(0.3, 0.5));
assert_eq!(c.len(), 3);
assert_eq!(c.evaluate(0.3), 0.5);
// 删除 → 恢复双点(恒等;非 2 幂 key 处逐位有舍入)。
c.delete_nth(1).unwrap();
assert_eq!(c.len(), 2);
assert!(close(c.evaluate(0.3), 0.3, 1e-12));
// 越界删除 → Err。
assert!(c.delete_nth(2).is_err());
}
/// set_nth 改 key 后保持有序(点在序列中移动)。
#[test]
fn set_nth_reorders_on_key_change() {
let mut c = Curve::from_pairs(&[(0.0, 0.0), (0.5, 0.5), (1.0, 1.0)]);
// 把第 0 点挪到 0.75(原第 1、2 点之前……之后)。
c.set_nth(0, 0.75, 0.75).unwrap();
let pairs: Vec<(f64, f64)> = c
.points
.iter()
.map(|p| (p.key, p.value))
.collect();
assert_eq!(pairs, vec![(0.5, 0.5), (0.75, 0.75), (1.0, 1.0)]);
assert_eq!(c.evaluate(0.75), 0.75);
// 越界 nth → Err。
assert!(c.set_nth(3, 0.9, 0.9).is_err());
}
/// slope 编辑生效:同为 {(0,0),(1,1)},自动 slope (1,1) 时
/// 求值 = 恒等;把 slope 显式压平为 0 后曲线变 S 形缓起缓收
/// (中点值从 0.25 变 0.15625)。
#[test]
fn slope_editing_changes_evaluation() {
let mut c = Curve::from_pairs(&[(0.0, 0.0), (1.0, 1.0)]);
assert_eq!(c.evaluate(0.25), 0.25);
// 显式编辑 slope(宿主/测试路径;suite 无 slope 入口,
// 但字段公开即契约的一部分)。
c.points[0].slope = 0.0;
c.points[1].slope = 0.0;
assert_eq!(c.evaluate(0.25), 0.15625);
assert_eq!(c.evaluate(0.5), 0.5);
assert!(close(c.evaluate(0.25), 0.15625, 1e-12));
}
/// 空曲线与单点曲线:恒等 / 常数退化。
#[test]
fn degenerate_curves() {
let c = Curve::empty();
assert!(c.is_empty());
assert_eq!(c.evaluate(0.3), 0.3);
assert_eq!(c.evaluate(5.0), 5.0);
let c = Curve::from_pairs(&[(0.5, 0.25)]);
assert_eq!(c.evaluate(0.0), 0.25);
assert_eq!(c.evaluate(100.0), 0.25);
}
/// clear:DeleteAllControlPoints 的模型侧语义。
#[test]
fn clear_empties_curve() {
let mut c = Curve::from_pairs(&[(0.0, 0.0), (1.0, 1.0)]);
c.clear();
assert!(c.is_empty());
assert_eq!(c.evaluate(0.5), 0.5);
}
/// JSON 往返:恒等曲线(默认值)序列化形状逐字 + 解析回等值模型。
#[test]
fn json_roundtrip_identity() {
let curves = vec![Curve::identity(0.0, 1.0)];
let json = curves_to_json(&curves);
assert_eq!(
json,
r#"{"curves":[[{"key":0,"value":0,"slope":1},{"key":1,"value":1,"slope":1}]]}"#
);
let back = curves_from_json(&json).expect("应可解析");
assert_eq!(back, curves);
}
/// JSON 往返:多维 + 非平凡形状 + 显式编辑 slope(slope 也是载荷
/// 的一部分,逐位保留)。
#[test]
fn json_roundtrip_multidim_and_slope() {
let mut c = Curve::from_pairs(&[(0.0, 0.0), (0.5, 0.25), (1.0, 1.0)]);
c.points[1].slope = 0.0; // 显式编辑(字段公开即契约)
let curves = vec![c.clone(), Curve::identity(0.0, 255.0)];
let json = curves_to_json(&curves);
let back = curves_from_json(&json).expect("应可解析");
assert_eq!(back.len(), 2);
assert_eq!(back, curves);
assert_eq!(back[0].points[1].slope, 0.0);
assert_eq!(back[1].points[1].key, 255.0);
// 求值不受序列化影响。
assert_eq!(back[0].evaluate(0.5), 0.25);
}
/// JSON 往返:特殊值(NaN/±Inf,slope 与值均可)与空曲线/空集。
#[test]
fn json_roundtrip_special_and_empty() {
let curves = vec![Curve {
points: vec![
ControlPoint {
key: 0.0,
value: f64::NAN,
slope: 0.0,
},
ControlPoint {
key: 1.0,
value: f64::INFINITY,
slope: f64::NEG_INFINITY,
},
],
}];
let json = curves_to_json(&curves);
assert_eq!(
json,
r#"{"curves":[[{"key":0,"value":null,"slope":0},{"key":1,"value":"inf","slope":"-inf"}]]}"#
);
let back = curves_from_json(&json).expect("应可解析");
assert!(back[0].points[0].value.is_nan());
assert_eq!(back[0].points[1].value, f64::INFINITY);
assert_eq!(back[0].points[1].slope, f64::NEG_INFINITY);
// 空曲线(DeleteAll 后)与空集。
let curves = vec![Curve::empty(), Curve::empty()];
let json = curves_to_json(&curves);
assert_eq!(json, r#"{"curves":[[],[]]}"#);
assert_eq!(curves_from_json(&json).unwrap(), curves);
assert_eq!(curves_from_json(r#"{"curves":[]}"#).unwrap(), Vec::<Curve>::new());
}
/// JSON 解析:容忍空白与字段乱序;结构不符 → None(静默路径)。
#[test]
fn json_parser_tolerances() {
let curves = vec![Curve::from_pairs(&[(0.0, 0.0), (1.0, 1.0)])];
// 空白 + 字段乱序。
let spaced = r#"{ "curves" : [ [ { "slope" : 1 , "key" : 0 , "value" : 0 } , { "key" : 1 , "value" : 1 , "slope" : 1 } ] ] }"#;
assert_eq!(curves_from_json(spaced).unwrap(), curves);
// 结构不符 → None。
for bad in [
"",
"{}",
r#"{"curves"}"#,
r#"{"curve":[]}"#,
r#"{"curves":[{"key":0}]}"#,
r#"{"curves":[[{"key":"x"}]]}"#,
r#"{"curves":[[{"key":0}]]"#,
r#"{"curves":[[{"key":0,"value":0,"slope":0}]]}junk"#,
] {
assert!(curves_from_json(bad).is_none(), "应拒绝:{bad}");
}
// 缺 slope 字段 → 0(宽容)。
let no_slope = r#"{"curves":[[{"key":0,"value":0}]]}"#;
let back = curves_from_json(no_slope).unwrap();
assert_eq!(back[0].points[0].slope, 0.0);
}
}
+174
View File
@@ -0,0 +1,174 @@
// 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/>.
//! 进度上报(Progress suite 的宿主侧)。
//!
//! 对应 C++ 的 `PluginProgressReporter`。进度/取消经 facade 注册的
//! 回调出 crate(M9 的 facade 回调模式)。取消是粘滞的:一旦回调
//! 答 false,本报告器的 [`is_cancelled`](image effect suite 的
//! abort 查询)持续为真。
//!
//! ## app 注入点(阶段 6a)
//!
//! facade C 回调之外,app 可经 [`set_reporter_factory`] 注册一个
//! 工厂:渲染未装 C 回调时,Progress suite 的 progressStart 携
//! (label, message) 从工厂现造一个 [`UiProgressReporter`](如进度
//! 对话框),progressUpdate 转发给它,返回 false 即取消。对应 C++
//! `PluginProgressDialogReporter` 的创建路径。
use std::ffi::c_int;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
/// 进度 UI 报告器(app 实现:对话框、状态栏等)。`update` 返回
/// false 表示用户请求取消(映射 kOfxStatReplyNo)。
pub trait UiProgressReporter: Send {
/// 上报进度(0.0..=1.0);false = 取消。
fn update(&mut self, progress: f64) -> bool;
/// progressEnd 通知(默认 no-op;app 可据此关闭进度 UI / 把完成
/// 事件转发过 IPC——worker 侧的进度回传依赖它)。
fn end(&mut self) {}
}
/// 报告器工厂:progressStart 携 (label, message) 调用,现造一个
/// [`UiProgressReporter`]。
pub type ReporterFactory =
Arc<dyn Fn(&str, &str) -> Box<dyn UiProgressReporter> + Send + Sync>;
static REPORTER_FACTORY: OnceLock<Mutex<Option<ReporterFactory>>> = OnceLock::new();
fn factory_slot() -> &'static Mutex<Option<ReporterFactory>> {
REPORTER_FACTORY.get_or_init(|| Mutex::new(None))
}
/// 注册/清除进度 UI 工厂(app 接线点;覆盖式)。
pub fn set_reporter_factory(factory: Option<ReporterFactory>) {
*factory_slot().lock().unwrap_or_else(|e| e.into_inner()) = factory;
}
pub(crate) fn reporter_factory() -> Option<ReporterFactory> {
factory_slot()
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
/// 是否已注册 UI 工厂(render 路径据此决定是否装静默报告器)。
pub fn has_reporter_factory() -> bool {
reporter_factory().is_some()
}
/// 进度回调:签名与 `include/plugin/instance.h` 的
/// `oakplugin_progress_fn` 逐字一致——`(progress, userdata)`,
/// 返回非 0 表示应中止(骨架声明为 `(userdata, progress) -> bool`,
/// 与头文件不符,以此为准)。
pub type ProgressFn = unsafe extern "C" fn(progress: f64, userdata: *mut std::ffi::c_void) -> c_int;
/// 进度上报器。render 路径持有一份,Progress suite 的
/// progressStart/Update/End 转发到这里。
pub struct ProgressReporter {
callback: Option<ProgressFn>,
userdata: usize,
/// UI 报告器(progressStart 经 [`reporter_factory`] 现造;
/// C 回调优先,无回调时才用)。
ui: Mutex<Option<Box<dyn UiProgressReporter>>>,
/// 取消标志(粘滞;update 返回 false 时置位)。
cancelled: AtomicBool,
}
impl ProgressReporter {
/// 无回调(渲染静默进行;progressStart 仍可能经工厂装上 UI
/// 报告器)。
pub fn silent() -> Self {
Self {
callback: None,
userdata: 0,
ui: Mutex::new(None),
cancelled: AtomicBool::new(false),
}
}
/// 带回调。
///
/// # Safety
/// `userdata` 的生命周期由注册方保证。
pub unsafe fn new(callback: ProgressFn, userdata: *mut std::ffi::c_void) -> Self {
Self {
callback: Some(callback),
// usize 存(裸指针破坏 Send 推导;值语义不变)。
userdata: userdata as usize,
ui: Mutex::new(None),
cancelled: AtomicBool::new(false),
}
}
/// progressStart 钩子:无 C 回调且工厂已注册时,现造 UI 报告器
/// (已装过则不重复造——progressStart 可嵌套括号)。
pub(crate) fn install_ui(&self, label: &str, message: &str) {
if self.callback.is_some() {
return;
}
let mut slot = self.ui.lock().unwrap_or_else(|e| e.into_inner());
if slot.is_some() {
return;
}
if let Some(factory) = reporter_factory() {
*slot = Some(factory(label, message));
}
}
/// 报告进度;返回 false 表示应取消(映射
/// kOfxStatReplyNo/action 失败由调用点决定)。
pub fn update(&self, progress: f64) -> bool {
match self.callback {
Some(cb) => {
// 头文件契约:非 0 = 中止。
let abort = unsafe { cb(progress, self.userdata as *mut std::ffi::c_void) } != 0;
if abort {
self.cancelled.store(true, Ordering::Relaxed);
}
!abort
}
None => {
let mut slot = self.ui.lock().unwrap_or_else(|e| e.into_inner());
match slot.as_mut() {
Some(ui) => {
let keep_going = ui.update(progress);
if !keep_going {
self.cancelled.store(true, Ordering::Relaxed);
}
keep_going
}
None => true,
}
}
}
}
/// 本次渲染是否已被取消(image effect suite 的 abort 透传)。
pub(crate) fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::Relaxed)
}
/// progressEnd 钩子:转发给 UI 报告器(无报告器时 no-op)。
pub(crate) fn end_ui(&self) {
let mut slot = self.ui.lock().unwrap_or_else(|e| e.into_inner());
if let Some(ui) = slot.as_mut() {
ui.end();
}
}
}
+172
View File
@@ -0,0 +1,172 @@
// 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/>.
//! OFX 属性集(Property Suite 的宿主侧存储)。
//!
//! 每个 OFX 对象(host/plugin/descriptor/instance/clip/image/param)
//! 都挂一个 [`PropertySet`]。属性是多维数组,按类型存取。
//! 参照:HS: ofxhProperty.cpp(GetSuite 的读写语义:越界返回
//! kOfxStatErrBadIndex,类型不符返回 kOfxStatErrBadHandle)。
use std::sync::Mutex;
use crate::error::{Error, Result};
/// 属性值(单元素)。字符串以 OFX 的 `char*` 语义持有(host 拥有,
/// 插件借用)。
#[derive(Clone, Debug)]
pub enum Value {
/// 32 位整型。
Int(i32),
/// 双精度。
Double(f64),
/// UTF-8 字符串(OFX 侧为 NUL 结尾 char*)。
String(std::ffi::CString),
/// 不透明指针(如 OfxImageEffectHandle 互指)。
Pointer(*mut std::ffi::c_void),
}
// 裸指针默认禁 Send/Sync;但属性集语义把指针当作**不透明令牌**:
// 跨线程只搬运/比较值,解引用永远是 suite 层的 unsafe 责任(OFX
// multithread suite 本就要求插件线程可读写宿主图像缓冲——指针的
// 跨线程传递是规范语义,而非逃逸)。Mutex 包裹后属性集整体可共享。
// 与 Rust 安全模型不冲突:安全代码只能拿到 `&Value`,无法解引用指针。
unsafe impl Send for Value {}
unsafe impl Sync for Value {}
/// 一个属性:名字 + 多维值数组。
#[derive(Clone, Debug)]
pub struct Property {
/// OFX 属性名(kOfxProp*;拥有型——协商期的动态名
/// "OfxImageClipPropComponents_<clip>" 需要,`&'static str`
/// 无法表达)。
pub name: String,
/// 元素数组;维度 = len。
pub values: Vec<Value>,
}
/// 属性集。线程安全(内部 Mutex);OFX 对象的 `*Handle` 即指向它的
/// 包装。
pub struct PropertySet {
props: Mutex<Vec<Property>>,
}
/// 深拷贝(持锁克隆内部数组;createInstance 时描述符属性 → 实例
/// 属性需要)。
impl Clone for PropertySet {
fn clone(&self) -> Self {
let props = lock(&self.props);
Self {
props: Mutex::new(props.clone()),
}
}
}
impl PropertySet {
/// 空集。
pub fn new() -> Self {
Self {
props: Mutex::new(Vec::new()),
}
}
/// 定义(或整体替换)一个属性。已存在同名属性时替换其值数组。
///
/// 对应 C++ `Set::addProperty` 的替换语义(HS: ofxhPropertySuite.cpp:462)
/// 与 `PropertyTemplate::setValueN` 的整体写数组语义;属性不存在时
/// 新建(维度和值都取自 `values`)。
pub fn define(&self, name: &str, values: Vec<Value>) {
let mut props = lock(&self.props);
if let Some(p) = props.iter_mut().find(|p| p.name == name) {
p.values = values;
} else {
props.push(Property {
name: name.to_string(),
values,
});
}
}
/// 单元素便捷定义。
pub fn set_one(&self, name: &str, value: Value) {
self.define(name, vec![value]);
}
/// 读取第 `index` 个元素;属性不存在或越界返回 `None`。
///
/// 越界对应 C++ 的 kOfxStatErrBadIndex
/// (HS: ofxhPropertySuite.cpp:257 `getValueRaw`),此处以 Option 表达。
pub fn get(&self, name: &str, index: usize) -> Option<Value> {
let props = lock(&self.props);
props
.iter()
.find(|p| p.name == name)
.and_then(|p| p.values.get(index).cloned())
}
/// 覆盖第 `index` 个元素的值(不改变维度);失败返回
/// [`crate::error::Error::NotFound`]。
///
/// 维度固定是刻意为之:与 C++ `setValue` 的自动扩容不同,这里
/// 扩容只能经 [`PropertySet::define`] 显式进行(维度语义由定义方
/// 掌控,避免插件意外撑大数组)。
pub fn set_at(&self, name: &str, index: usize, value: Value) -> Result<()> {
let mut props = lock(&self.props);
let p = props
.iter_mut()
.find(|p| p.name == name)
.ok_or(Error::NotFound)?;
let slot = p.values.get_mut(index).ok_or(Error::NotFound)?;
*slot = value;
Ok(())
}
/// 维度(属性不存在为 0)。
pub fn dimension(&self, name: &str) -> usize {
lock(&self.props)
.iter()
.find(|p| p.name == name)
.map_or(0, |p| p.values.len())
}
/// 删除属性;不存在为 no-op。
pub fn remove(&self, name: &str) {
lock(&self.props).retain(|p| p.name != name);
}
/// 遍历快照(dump/快照测试用)。
pub fn snapshot(&self) -> Vec<Property> {
lock(&self.props).clone()
}
/// suite 层专用:持锁访问原始存储。
///
/// 属性 suite 需要"先类型检查再按索引读写、返回内驻字符串指针"
/// 等跨多次读写的一致性语义(逐条对照 HS: ofxhProperty.cpp),
/// 公开 API 无法在不重复加锁的前提下表达;此入口把 `Vec<Property>`
/// 在单一临界区内交给 suite 实现。仅本 crate 可见。
pub(crate) fn with_locked<R>(&self, f: impl FnOnce(&mut Vec<Property>) -> R) -> R {
let mut props = lock(&self.props);
f(&mut props)
}
}
/// 取锁。毒锁(本 crate 代码在持锁时 panic)时接管其内部状态继续
/// 使用——属性集的数据本身总是完好的,宁可继续也不让一次 panic
/// 级联成后续所有 FFI 调用失败。
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
+238
View File
@@ -0,0 +1,238 @@
// 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/>.
//! oakrender 桥(single-lib unification):纹理/帧值类型与渲染调用面。
//!
//! oakrender 的 C ABI 已删除(单库化):纹理是
//! [`oak_render::texture::Texture`](value enum,无句柄),CPU 帧是
//! [`oak_render::texture::Frame`]。本 crate 的 render 驱动与 GL suite
//! 直接持值类型:
//!
//! - [`Texture`] = [`oak_render::texture::Texture`](值别名;
//! clone 即引用语义,drop 自动释放后端 token——原 `texture_free`/
//! `frame_free` 调用面随值模型删除);
//! - [`Frame`] = [`oak_render::texture::Frame`](值别名);
//! - [`Renderer`] = `Arc<dyn oak_render::backend::GpuContextLike>`
//! (渲染器即 oakrender 后端上下文,facade 经
//! [`oak_render::backend::GpuContext::create`] 创建);
//! - [`VideoParams`] 直接别名 oakrender 的
//! [`oak_render::frame::VideoParamsPod`](同布局 POD);
//! - 像素格式常量直接别名 [`oak_core::PixelFormat`]。
//!
//! 保留桩(GPU 相关、wgpu 模型无直接 Rust 等价物):
//! [`texture_id`]——oakrender 纹理(wgpu/CPU)没有 OpenGL 纹理名,
//! 恒 0。**GL 模式的真实 GL 纹理名来自 [`crate::gl_bridge`]**(方案 B
//! 已落地):render 驱动为输出帧建 GL 纹理 + FBO,GL suite 的
//! `OpenGLTextureIndex` 属性据此返回真实名;use_opengl 决策改用
//! [`crate::gl_bridge::gl_available`] 作"目标纹理有有效 GL 名"的门。
/// `oakrender_video_params` POD — single-lib unification: aliases the
/// oakrender crate's struct (identical layout;
/// include/render/renderer.h:78).
pub type VideoParams = oak_render::frame::VideoParamsPod;
/// olive::PixelFormat::Format 的 f32 值。
pub const PIXEL_FORMAT_F32: i32 = oak_core::PixelFormat::F32 as i32;
/// olive::PixelFormat::Format 的 u8 值。
pub const PIXEL_FORMAT_U8: i32 = oak_core::PixelFormat::U8 as i32;
/// oakrender 渲染器(后端上下文;Arc 共享,GPU 纹理据此 upload/
/// download/blit——无需独立渲染器句柄)。
pub type Renderer = std::sync::Arc<dyn oak_render::backend::GpuContextLike>;
/// oakrender 纹理(值型;GPU 或 CPU 包装)。
pub type Texture = oak_render::texture::Texture;
/// oakrender CPU 帧(值型)。
pub type Frame = oak_render::texture::Frame;
// ---- 桥调用面(值型实现;原 CHandle 桩随单库化重写)----------------------
/// 纹理是否占位(dummy:透明黑、从未上传)。
pub fn texture_is_dummy(texture: &Texture) -> bool {
texture.is_dummy()
}
/// 纹理的 CPU 帧:GPU 纹理经后端下载,CPU 纹理克隆
/// (原 `texture_get_frame` 的 out 参数形态改为值返回;错误即旧
/// "纹理无 CPU 帧" 失败路径)。
pub fn texture_get_frame(texture: &Texture) -> crate::error::Result<Frame> {
texture.to_frame().map_err(|e| {
crate::error::Error::Failed(format!("纹理 readback 失败:{e}"))
})
}
/// 纹理的视频参数(尺寸 + 像素格式;原 `texture_get_params` 的
/// out 参数形态改为值返回)。
pub fn texture_get_params(texture: &Texture) -> VideoParams {
let (w, h) = texture.size();
let mut p = VideoParams::default();
p.width = w;
p.height = h;
p.format = texture.format() as i32;
p
}
/// 从视频参数与像素数据构造 CPU 纹理(原 `texture_create` 的
/// renderer+参数+像素形态改为值形态):按 `linesize` 行跨度做行优先
/// 拷贝(0 = 紧凑行),F32/RGBA 4 通道为管线常规。GPU 上传由后端
/// 延迟(wrapped frame 语义,`Texture::wrap_frame`)。
pub fn texture_create(
params: &VideoParams,
pixels: &[u8],
linesize: i32,
) -> crate::error::Result<Texture> {
use crate::error::Error;
let mut frame = Frame::new();
frame.set_video_params(*params);
let w = frame.width.max(0) as usize;
let h = frame.height.max(0) as usize;
if w == 0 || h == 0 {
return Err(Error::Invalid);
}
let bpc = frame.bytes_per_channel();
if bpc == 0 {
return Err(Error::Invalid);
}
// 行跨度推导通道数(RGB 3 通道等非常规分量)。
if linesize > 0 && w > 0 && (linesize as usize) % (w * bpc) == 0 {
frame.channels = (linesize as usize / (w * bpc)) as i32;
}
let tight = frame.linesize_bytes();
let row = if linesize > 0 { linesize as usize } else { tight };
if pixels.len() < row.saturating_mul(h) {
return Err(Error::Invalid);
}
frame.data = vec![0u8; tight * h];
for y in 0..h {
let s = y * row;
let d = y * tight;
frame.data[d..d + tight].copy_from_slice(&pixels[s..s + tight]);
}
Ok(Texture::wrap_frame(frame))
}
/// oakrender 纹理在 GL 命名空间中的纹理名。oakrender 纹理(wgpu
/// Metal / CPU 帧)没有 OpenGL 纹理名,恒 0。
///
/// **GL 模式的真实纹理名不由本函数提供**:宿主自建的离屏 GL 纹理
/// (输出帧 + FBO 挂载、输入 clip 上传)由 [`crate::gl_bridge`] 产生,
/// 经 GL suite 的 `OpenGLTextureIndex` 属性直接写出;use_opengl 决策
/// 用 [`crate::gl_bridge::gl_available`] 当"目标纹理有有效 GL 名"的
/// 门(桥能为目标帧建出真实 GL 纹理 ⟺ 可用)。评估历史见
/// [`crate::gl_bridge`] 模块文档。
pub fn texture_id(_texture: &Texture) -> i32 {
0
}
/// 渲染器是否为 OpenGL 后端([`oak_render::backend::BackendKind::Gl`];
/// 原 `renderer_is_open_gl` 的句柄形态改为后端上下文 kind 查询)。
pub fn renderer_is_open_gl(renderer: &Renderer) -> bool {
renderer.kind() == oak_render::backend::BackendKind::Gl
}
#[cfg(test)]
mod tests {
use super::*;
/// 测试渲染器:最小 GpuContextLike 假实现(无 GPU 适配器需求)。
struct FakeGpu;
impl oak_render::backend::GpuContextLike for FakeGpu {
fn kind(&self) -> oak_render::backend::BackendKind {
oak_render::backend::BackendKind::Cpu
}
fn destroy_texture(&self, _token: u64) {}
fn upload(&self, _token: u64, _frame: &Frame) -> oak_render::error::Result<()> {
Ok(())
}
fn download(&self, _token: u64) -> oak_render::error::Result<Frame> {
Ok(Frame::new())
}
fn blit(
&self,
_src: u64,
_dst: u64,
_processor: Option<&oak_render::color::ColorProcessor>,
) -> oak_render::error::Result<()> {
Ok(())
}
}
/// 纹理创建:参数 + 行跨度感知拷贝往返(含 RGB 3 通道推导)。
#[test]
fn texture_create_linesize_aware() {
let mut params = VideoParams::default();
params.width = 3;
params.height = 2;
params.format = PIXEL_FORMAT_F32;
// 紧凑 3×2 RGBA F32:3*4*4 = 48 B/行。
let tight = 3 * 4 * 4;
let mut pixels = vec![0u8; tight * 2];
for (i, b) in pixels.iter_mut().enumerate() {
*b = (i % 251) as u8;
}
let tex = texture_create(&params, &pixels, 0).expect("紧凑行应可创建");
assert!(!texture_is_dummy(&tex));
let frame = texture_get_frame(&tex).expect("CPU 帧应可读");
assert_eq!(frame.width, 3);
assert_eq!(frame.height, 2);
assert_eq!(frame.channels, 4);
assert_eq!(frame.linesize_bytes(), tight);
assert_eq!(frame.data, pixels);
// 行跨度变体(每行 4 字节填充)。
let row = tight + 4;
let mut padded = vec![0u8; row * 2];
for y in 0..2 {
padded[y * row..y * row + tight].copy_from_slice(&pixels[y * tight..(y + 1) * tight]);
}
let tex = texture_create(&params, &padded, row as i32).expect("带填充行应可创建");
let frame = texture_get_frame(&tex).unwrap();
assert_eq!(frame.data, pixels, "填充行应剥离为紧凑存储");
// 像素不足 → Invalid。
assert!(texture_create(&params, &padded[..row * 2 - 1], row as i32).is_err());
// 无效尺寸 → Invalid。
let mut bad = params;
bad.width = 0;
assert!(texture_create(&bad, &pixels, 0).is_err());
}
/// 纹理参数查询与 dummy 语义。
#[test]
fn texture_params_and_dummy() {
let dummy = Texture::dummy();
assert!(texture_is_dummy(&dummy));
let p = texture_get_params(&dummy);
assert_eq!((p.width, p.height), (0, 0));
let mut params = VideoParams::default();
params.width = 8;
params.height = 4;
params.format = PIXEL_FORMAT_F32;
let tex = texture_create(&params, &[0u8; 8 * 4 * 4 * 4], 0).unwrap();
let p = texture_get_params(&tex);
assert_eq!((p.width, p.height), (8, 4));
assert_eq!(p.format, PIXEL_FORMAT_F32);
}
/// 渲染器 kind 查询与 GL 判断;texture_id 桩恒 0(无 GL 命名空间)。
#[test]
fn renderer_kind_and_gl_id_stub() {
let r: Renderer = std::sync::Arc::new(FakeGpu);
assert!(!renderer_is_open_gl(&r));
let dummy = Texture::dummy();
assert_eq!(texture_id(&dummy), 0, "wgpu 无 GL 纹理名:桩恒 0");
}
}
+572
View File
@@ -0,0 +1,572 @@
// 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/>.
//! render 驱动:`src/render/src/plugin/pluginrenderer.cpp`
//! `PluginRenderer::render_plugin`(1857 行 C++ 的一部分)的渲染流程
//! 语义收编(M11 §4)。
//!
//! 目标:oakrender 的 PluginJob 语义全部收编进本模块(单库化后
//! 原 `oakplugin_instance_render_job` C ABI 已删除,facade 直接构造
//! [`RenderJob`] 调 [`render_frame`]),本模块承载全部 OFX 宿主
//! 渲染流程。逐段对照的 C++ 行号已注释。
//!
//! ## 流程(render_frame,对应 render_plugin)
//!
//! 1. 实例锁(pluginrenderer.cpp:1436-1444)+ 取消检查;
//! 2. use_opengl 决策(pluginrenderer.cpp:1446-1457):插件描述符
//! kOfxImageEffectPropOpenGLRenderSupported ∈ {true, needed} 且
//! 渲染器是 OpenGL 且目标纹理有 GL id;
//! 3. 输入纹理收集(pluginrenderer.cpp:1518-1552):effect_input_id
//! 匹配 → job.src;否则按 clip 名的纹理表;SimpleSource 回退;
//! 4. getClipPreferences(pluginrenderer.cpp:1554-1594);
//! 5. RoI/RoD 设定(pluginrenderer.cpp:1596-1607):region_of_interest
//! = 目标尺寸(规范坐标);输出 clip 的 RoD 与输出纹理挂接;
//! 6. 输入 clip 的 RoD 与格式(pluginrenderer.cpp:1627-1665;Phase 2
//! 全链路 F32 → 无转换);
//! 7. getRegionOfInterest(pluginrenderer.cpp:1666-1680):RoI 为
//! 建议值,任何失败按默认整帧继续(C++ 对 BadHandle 即如此;
//! Phase 2 其余状态同样继续——RoI 仅影响上游渲染范围,本管线
//! 输入由 oakrender 整帧提供);
//! 8. 输出 clip 格式(pluginrenderer.cpp:1686-1697);
//! 9. **isIdentity 短路**(ofxRendering "Identity Effects"):
//! isIdentity 命中 → 直接把所引输入 clip 在透传时间的帧拷入
//! 输出(不调 render action);
//! 10. 参数覆盖(pluginrenderer.cpp:132-290 apply_param_overrides);
//! 11. render action:CPU 路径经 [`crate::instance::Instance::render`]
//! (输出装配:图像 → 目标纹理帧,行跨度感知);GL 路径经
//! [`crate::instance::Instance::render_gl`] + [`crate::gl_bridge`]
//! (方案 B:宿主建离屏上下文,插件画进 FBO 附着的输出 GL 纹理,
//! render 返回后 glReadPixels 回读装配——输出格式与 CPU 路径一致;
//! GL 失败回退 CPU)。
//!
//! ## begin/end 序列括号
//!
//! ofxRendering 文档:"All calls to the render action are bracketed by
//! a pair of begin/end sequence render actions"。oakrender 对同一实例
//! 的一批帧先 [`begin_sequence`] 后 [`end_sequence`],中间逐帧
//! [`render_frame`]。
use crate::image::Image;
use crate::instance::{Instance, OfxRangeD, OfxRectD, RenderScale};
use crate::property::Value;
use crate::render::{self, Renderer, Texture};
/// 一帧渲染任务的输入(oakrender PluginJob 的 Rust 侧视图)。
pub struct RenderJob {
/// 帧时间(秒)。
pub time: f64,
/// 目标纹理(输出;oakrender 侧创建并经值传入)。
pub dst: Texture,
/// 主输入纹理(effect_input_id / SimpleSource;无则 None)。
pub src: Option<Texture>,
/// effect 输入 clip 名(job.src 的落点;C++ `node->get_effect_input_id()`)。
pub effect_input_id: Option<String>,
/// 其余输入 clip 的纹理表(clip 名 → 纹理)。
pub inputs: Vec<(String, Texture)>,
/// 参数覆盖(参数名 → oaknode_value POD;对应 NodeValueRow)。
pub values: Vec<(String, crate::node::Value)>,
/// GL 渲染器(None → CPU 路径;Some → 视 use_opengl 决策)。
pub renderer: Option<Renderer>,
/// 渲染前是否清空目标(信息性——C++ render_plugin 亦不处理,
/// 由上层渲染器负责;见插件渲染器注释)。
pub clear_destination: bool,
/// 交互式渲染标记(信息性;Phase 2 的 render in args 恒 0,见
/// [`crate::instance::Instance::render`])。
pub interactive: bool,
}
impl Default for RenderJob {
fn default() -> Self {
Self {
time: 0.0,
dst: Texture::dummy(),
src: None,
effect_input_id: None,
inputs: Vec::new(),
values: Vec::new(),
renderer: None,
clear_destination: false,
interactive: false,
}
}
}
/// beginSequenceRender 括号(ofxRendering:"bracketed by a pair of
/// begin/end sequence render actions";ofxGPURender.h 的 GL 模式下该
/// action 的 in args 也带 kOfxImageEffectPropOpenGLEnabled)。
/// `gl` 非空时按 GL 模式调用。
pub fn begin_sequence(
inst: &Instance,
range: OfxRangeD,
gl: Option<Renderer>,
) -> crate::error::Result<()> {
if gl.is_some() {
// GL 模式:ofxGPURender.h "OpenGL Current Context" 要求
// BeginSequenceRender 期间上下文 current(插件可能在此分配 GL
// 资源)。acquire 覆盖整个 action;返回即清 current。
let _guard = crate::gl_bridge::acquire()?;
inst.begin_sequence_render_gl(range)
} else {
inst.begin_sequence_render(range)
}
}
/// endSequenceRender 括号(与 [`begin_sequence`] 配对)。
pub fn end_sequence(
inst: &Instance,
range: OfxRangeD,
gl: Option<Renderer>,
) -> crate::error::Result<()> {
if gl.is_some() {
let _guard = crate::gl_bridge::acquire()?;
inst.end_sequence_render_gl(range)
} else {
inst.end_sequence_render(range)
}
}
/// 渲染一帧(`render_plugin` 的 Rust 移植;逐段行号对照见模块文档)。
///
/// 返回装配完成的输出纹理与各输入 clip 的 RoI(clip 名 → 矩形;
/// 值型纹理下输出写入 `job.dst` 的本地副本并随返回值交付——CPU
/// 纹理的 `to_frame` 是拷贝,就地写不回只读的 `job.dst`)。宿主不
/// 据 RoI 裁剪输入——输入由 oakrender 整帧提供,与 C++ 渲染器行为
/// 一致。
pub fn render_frame(
inst: &Instance,
job: &RenderJob,
) -> crate::error::Result<(Texture, Vec<(String, OfxRectD)>)> {
use crate::error::Error;
// 1. 实例锁(pluginrenderer.cpp:1436-1444:OlivePluginInstance 非
// 线程安全,并发 setInputTexture/renderAction 会毁内部状态)。
let _lock = inst.render_lock.lock().unwrap_or_else(|e| e.into_inner());
// 取消检查必须在任何插件调用之前(shutdown 后入口已卸载)。
if inst.cancel.load(std::sync::atomic::Ordering::Relaxed) {
return Err(Error::Failed("已取消".into()));
}
// 2. use_opengl(pluginrenderer.cpp:1446-1457):插件声明 GL 支持
// 且渲染器是 OpenGL 且像素深度协商可行(管线 F32 满足插件
// kOfxOpenGLPropPixelDepth 声明)且目标纹理有有效 GL 名(= 桥能为
// 目标帧建出真实 GL 纹理 ⟺ 离屏上下文可用,[`crate::gl_bridge`])。
// 任一不满足 → 回退 CPU 路径(GL 分支在下方真正渲染)。
let use_opengl = match job.renderer.as_ref() {
Some(r) if render::renderer_is_open_gl(r) => {
let plugin_gl = plugin_supports_opengl(inst);
let depth_ok =
crate::suites::gl_render::pick_gl_pixel_depth(&inst.plugin.descriptor.props)
.is_some();
let gl_name_ok = crate::gl_bridge::gl_available();
plugin_gl && depth_ok && gl_name_ok
}
_ => false,
};
// 目标帧与参数(F32 校验;输出装配的依据)。dst 取本地副本:
// 值型纹理下输出装配写回副本,随返回值交付(job.dst 只读)。
let (dst_params, w, h) = read_dst(&job.dst)?;
let mut dst = job.dst.clone();
let par = pixel_aspect(&dst_params);
// 规范坐标的 RoI/RoD(pluginrenderer.cpp:1595-1603:x2 = 宽 × PAR)。
let region_of_interest = OfxRectD {
x1: 0.0,
y1: 0.0,
x2: w * par,
y2: h,
};
// 3. 输入纹理收集(pluginrenderer.cpp:1518-1552)。
for clip in &inst.clips {
if clip.name == "Output" {
continue;
}
if let Some(tex) = pick_input(&clip.name, job) {
if usable(&tex) {
clip.set_input_texture(Some(tex), job.time);
}
}
}
// 4. getClipPreferences(pluginrenderer.cpp:1554-1594)。
let prefs = inst.get_clip_preferences()?;
let components = match prefs.output_components.as_str() {
"OfxImageComponentRGBA" => crate::image::Components::Rgba,
"OfxImageComponentRGB" => crate::image::Components::Rgb,
"OfxImageComponentAlpha" => crate::image::Components::Alpha,
_ => return Err(Error::Failed("协商分量未知".into())),
};
if prefs.output_bit_depth != "OfxBitDepthFloat" {
return Err(Error::Failed("Phase 2 仅支持 F32 输出".into()));
}
// 5. 输出 clip:RoD + 输出纹理挂接(pluginrenderer.cpp:1603-1606)。
let output_clip = inst
.clips
.iter()
.find(|c| c.name == "Output")
.ok_or_else(|| Error::Failed("实例无 Output clip".into()))?;
output_clip.set_region_of_definition(region_of_interest, job.time);
output_clip.set_output_texture(Some(dst.clone()), job.time);
// 6. 输入 clip:RoD 与格式(pluginrenderer.cpp:1627-1665;Phase 2
// 全链路 F32 → 格式选择恒等,无转换路径)。
for clip in &inst.clips {
if clip.name == "Output" {
continue;
}
if pick_input(&clip.name, job).map_or(false, |t| usable(&t)) {
clip.set_region_of_definition(region_of_interest, job.time);
clip.set_video_params(render::PIXEL_FORMAT_F32, 4);
}
}
// 7. getRegionOfInterest(pluginrenderer.cpp:1666-1680)。RoI 为
// 建议值:失败按默认整帧继续(C++ 对 BadHandle 如此;本管线
// 输入整帧提供,RoI 只作记录)。
let rois = inst
.get_regions_of_interest(job.time, RenderScale { x: 1.0, y: 1.0 }, region_of_interest)
.unwrap_or_else(|_| inst.clips.iter().map(|_| region_of_interest).collect());
// 8. 输出 clip 格式(pluginrenderer.cpp:1686-1697)。
output_clip.set_video_params(render::PIXEL_FORMAT_F32, components.channel_count() as i32);
// 渲染窗口(像素坐标;pluginrenderer.cpp:1699-1704)。
let render_window = OfxRectD {
x1: 0.0,
y1: 0.0,
x2: w,
y2: h,
};
// 9. isIdentity 短路(ofxRendering "Identity Effects"):插件声明
// 本帧等价于某输入 clip → 直接透传该 clip 在透传时间的帧。
if let Some((t, clip_name)) = inst.is_identity(job.time)? {
passthrough(inst, &clip_name, t, &mut dst)?;
return Ok((dst, zip_rois(inst, &rois)));
}
// 10. 参数覆盖(pluginrenderer.cpp:1729-1731 + 132-290)。
apply_param_overrides(inst, &job.values);
// 11. render action。
if !use_opengl {
let output = std::sync::Arc::new(Image::allocate(
crate::image::BitDepth::Float,
components,
OfxRectD {
x1: 0.0,
y1: 0.0,
x2: w,
y2: h,
},
));
inst.render(
job.time,
RenderScale { x: 1.0, y: 1.0 },
render_window,
output.clone(),
)?;
// 输出装配(pluginrenderer.cpp:1762-1834 的 CPU 路径)。
write_output_frame(&mut dst, &output)?;
} else {
// GL 路径(方案 B,见 [`crate::gl_bridge`]):宿主自建离屏
// 上下文,为输出帧建 GL 纹理 + FBO(插件直接画进附着的输出
// 纹理,等价 C++ attach_output_texture),render 返回后
// glReadPixels 回读装帧(pluginrenderer.cpp:1784-1834 的 GL
// 分支 + 本实现的回读装配)。GL 失败回退 CPU(对齐现有失败
// 语义;最终失败仍上抛)。
match render_gl_frame(
inst,
job,
RenderScale { x: 1.0, y: 1.0 },
render_window,
w,
h,
&dst_params,
) {
Ok(image) => write_output_frame(&mut dst, &image)?,
Err(gl_err) => {
eprintln!("[PLUGIN] GL 渲染失败,回退 CPU:{gl_err}");
let output = std::sync::Arc::new(Image::allocate(
crate::image::BitDepth::Float,
components,
OfxRectD {
x1: 0.0,
y1: 0.0,
x2: w,
y2: h,
},
));
inst.render(
job.time,
RenderScale { x: 1.0, y: 1.0 },
render_window,
output.clone(),
)?;
write_output_frame(&mut dst, &output)?;
}
}
}
Ok((dst, zip_rois(inst, &rois)))
}
/// GL 渲染一帧(render_frame 的 GL 分支主体;返回回读装配完成的
/// F32 RGBA 图像)。
///
/// 流程:acquire 离屏上下文(本线程 current,全局串行)→ 建输出 GL
/// 纹理(尺寸 = 目标帧,格式按 `dst_params`)→ FBO 挂载并绑定 →
/// 视口 → [`Instance::render_gl`](插件画进附着纹理;真实纹理名经
/// GlCtx 注入,clipLoadTexture(Output) 返回它)→ glReadPixels 回读
/// 装配(垂直翻转 + 格式转换)→ 清理 FBO/纹理。任何一步失败返回
/// Err,调用方回退 CPU。
fn render_gl_frame(
inst: &Instance,
job: &RenderJob,
scale: RenderScale,
window: OfxRectD,
w: f64,
h: f64,
dst_params: &render::VideoParams,
) -> crate::error::Result<std::sync::Arc<Image>> {
use crate::error::Error;
// 离屏上下文(进程级共享;本线程 current 直到 guard drop)。
let _guard = crate::gl_bridge::acquire()?;
let (wpx, hpx) = (w as i32, h as i32);
// 输出 GL 纹理 + FBO 挂载(GL_RGBA32F/GL_RGBA8 按目标帧格式)。
let gl_tex = crate::gl_bridge::create_output_texture(wpx, hpx, dst_params)?;
let fbo = crate::gl_bridge::create_fbo(gl_tex, wpx, hpx)?;
crate::gl_bridge::bind_fbo(fbo);
crate::gl_bridge::set_viewport(wpx, hpx);
// render action(OpenGLEnabled=1;输出纹理真实名经 GlCtx 注入)。
let render_res = inst.render_gl(
job.time,
scale,
window,
job.renderer.clone().unwrap(),
job.dst.clone(),
Some(gl_tex),
);
// 回读前防御性重绑 FBO + 视口(规范下插件不解除输出绑定,但个别
// 插件可能改绑/改视口——重绑保证 glReadPixels 读的是输出纹理)。
crate::gl_bridge::bind_fbo(fbo);
crate::gl_bridge::set_viewport(wpx, hpx);
// 回读(FBO 仍绑定、输出 GL 纹理仍存活)。
let readback = crate::gl_bridge::read_pixels_to_image(wpx, hpx, dst_params);
// 清理(guard drop 时清 current 并放锁)。
crate::gl_bridge::delete_fbo(fbo);
crate::gl_bridge::delete_gl_texture(gl_tex);
render_res?;
readback.map_err(|e| Error::Failed(format!("GL 回读失败:{e}")))
}
/// 把输入 clip 名与 RoI 列表配对(与 `clips` 顺序一致)。
fn zip_rois(inst: &Instance, rois: &[OfxRectD]) -> Vec<(String, OfxRectD)> {
inst.clips
.iter()
.enumerate()
.filter(|(_, c)| c.name != "Output")
.map(|(i, c)| (c.name.clone(), rois.get(i).copied().unwrap_or_default()))
.collect()
}
/// 读目标纹理的参数(F32 校验)。返回 (参数, 宽, 高)。
fn read_dst(dst: &Texture) -> crate::error::Result<(render::VideoParams, f64, f64)> {
use crate::error::Error;
let params = render::texture_get_params(dst);
if params.format != render::PIXEL_FORMAT_F32 {
return Err(Error::Failed(format!(
"输出帧格式 {} 非 F32(Phase 2 约束)",
params.format
)));
}
let (w, h) = (params.width as f64, params.height as f64);
if w <= 0.0 || h <= 0.0 {
return Err(Error::Invalid);
}
Ok((params, w, h))
}
/// 目标参数的像素比(缺失 1.0)。
fn pixel_aspect(params: &render::VideoParams) -> f64 {
if params.pixel_aspect_den != 0 {
params.pixel_aspect_num as f64 / params.pixel_aspect_den as f64
} else {
1.0
}
}
/// 插件描述符是否声明 GL 渲染支持(ofxGPURender.h:397-408:
/// "true"/"needed")。
fn plugin_supports_opengl(inst: &Instance) -> bool {
inst.plugin
.descriptor
.props
.get(crate::host::PROP_GL_RENDER_SUPPORTED, 0)
.map(|v| match v {
Value::String(s) => {
let s = s.to_string_lossy();
s == "true" || s == "needed"
}
_ => false,
})
.unwrap_or(false)
}
/// 输入纹理是否可用(非占位;pluginrenderer.cpp:1504-1513 的
/// is_usable_input——Phase 2 只看非 dummy,帧/Renderer 由 oakrender
/// 保证)。
fn usable(tex: &Texture) -> bool {
!tex.is_dummy()
}
/// 按 C++ pluginrenderer.cpp:1527-1543 的规则选输入纹理。
fn pick_input(clip_name: &str, job: &RenderJob) -> Option<Texture> {
if job.effect_input_id.as_deref() == Some(clip_name) {
if let Some(src) = &job.src {
return Some(src.clone());
}
}
for (name, tex) in &job.inputs {
if name == clip_name {
return Some(tex.clone());
}
}
// SimpleSource 回退(pluginrenderer.cpp:1534-1543:
// kOfxImageEffectSimpleSourceClipName 取 k_texture_input,再回退
// job.src)。
if clip_name == "Source" {
return job.src.clone();
}
None
}
/// isIdentity 透传:把所引输入 clip 在 `t` 的帧拷入输出(CPU 拷贝;
/// 目标帧 F32 校验)。
fn passthrough(
inst: &Instance,
clip_name: &str,
t: f64,
dst: &mut Texture,
) -> crate::error::Result<()> {
use crate::error::Error;
let clip = inst
.clips
.iter()
.find(|c| c.name == clip_name)
.ok_or_else(|| Error::Failed(format!("isIdentity 引用未知 clip {clip_name}")))?;
let image = clip.fetch_image(t, RenderScale { x: 1.0, y: 1.0 }, None)?;
write_output_frame(dst, &image)
}
/// 参数覆盖(pluginrenderer.cpp:132-290 `apply_param_overrides` 的
/// Rust 移植):把每帧的节点值注入实例参数。字符串族(String/
/// StrChoice)经专用路径(set_param_string),不在此表的 oaknode
/// POD 表达范围内 → 跳过(与 C++ 的 k_file/k_text/k_font/k_str_combo
/// 走专用桥一致)。
fn apply_param_overrides(inst: &Instance, values: &[(String, crate::node::Value)]) {
for (key, v) in values {
let Some(p) = inst.params.find(key) else {
continue;
};
let Some(mut pv) = crate::param::param_value_from_node(v, &p.def.ofx_type) else {
continue;
};
// Double 标量的 NaN/Inf 清洗 + Min/Max 钳制
// (pluginrenderer.cpp:155-177:坏值回退默认并告警,再按
// kOfxParamPropMin/Max 钳制;多维 Double 族 C++ 无此检查)。
if p.def.ofx_type == crate::param::TYPE_DOUBLE {
if let crate::param::ParamValue::Double(d, 1) = &mut pv {
if d[0].is_nan() || d[0].is_infinite() {
eprintln!(
"[PLUGIN] NaN/Inf in double param {key} replacing with default"
);
d[0] = prop_double(&p.def.props, crate::param::P_DEFAULT, 0);
}
if let Some(Value::Double(min)) = p.def.props.get(crate::param::P_MIN, 0) {
if d[0] < min {
d[0] = min;
}
}
if let Some(Value::Double(max)) = p.def.props.get(crate::param::P_MAX, 0) {
if d[0] > max {
d[0] = max;
}
}
}
}
p.set_ofx(pv);
}
}
/// 读属性的 Double 值(缺失 0.0;Int 提升)。
fn prop_double(props: &crate::property::PropertySet, name: &str, index: usize) -> f64 {
match props.get(name, index) {
Some(Value::Double(v)) => v,
Some(Value::Int(v)) => v as f64,
_ => 0.0,
}
}
/// 把 CPU 图像写入目标纹理(行优先、行跨度感知;F32 校验)。
/// Phase 2 输出装配的公共落点(CPU render 路径与 isIdentity 透传
/// 共用)。GPU 目标纹理经后端 upload 回写(`Texture::Gpu` 分支)。
pub(crate) fn write_output_frame(dst: &mut Texture, image: &Image) -> crate::error::Result<()> {
use crate::error::Error;
// CPU 纹理就地写入;GPU 纹理经下载帧改写后 upload 回写。
let mut frame = render::texture_get_frame(dst)?;
let params = frame.video_params();
if params.format != render::PIXEL_FORMAT_F32 {
return Err(Error::Failed("输出帧格式非 F32(Phase 2 约束)".into()));
}
let (w, h) = (params.width as usize, params.height as usize);
let tight = w * image.components().channel_count() * 4;
if tight != image.row_bytes() || tight * h != image.pixels().len() {
return Err(Error::Failed("图像尺寸与输出帧不一致".into()));
}
let dst_ptr = frame.data_mut();
if dst_ptr.is_null() {
return Err(Error::Failed("输出帧无数据".into()));
}
let row = frame.linesize_bytes();
let row = if row > 0 { row } else { tight };
let dst_bytes = unsafe { std::slice::from_raw_parts_mut(dst_ptr, row * h) };
let pixels = image.pixels();
for y in 0..h {
let d = y * row;
let s = y * tight;
dst_bytes[d..d + tight].copy_from_slice(&pixels[s..s + tight]);
}
match dst {
// 就地写回(值型 CPU 纹理:to_frame 是拷贝,必须写回本体)。
Texture::Cpu(f) => {
f.data = frame.data;
}
// GPU 目标纹理:拷贝只落在下载帧上,经后端 upload 回写。
Texture::Gpu { token, ctx, .. } => {
ctx.upload(*token, &frame)
.map_err(|e| Error::Failed(format!("输出纹理上传失败:{e}")))?;
}
}
Ok(())
}
+795
View File
@@ -0,0 +1,795 @@
// 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/>.
//! OfxDrawSuiteV1(OFX 1.5,vendored ofxDrawSuite.h):宿主绘制套件。
//!
//! 插件在 `kOfxInteractActionDraw` 内经 `kOfxInteractPropDrawContext`
//! 取到绘制上下文(本模块的 [`DrawContext`]),再调 suite 函数画图:
//! getColour / setColour / setLineWidth / setLineStipple / draw /
//! drawText。
//!
//! ## 上下文模型
//!
//! - [`DrawContext`] 在每次 draw action 前由宿主创建、经存活表
//! [`LIVE_CONTEXTS`] 注册(句柄 = 堆地址;对应 [`crate::suites::tag`]
//! 的句柄纪律),draw 返回后摘除。插件只在 draw action 内持有上下文
//! ——ofxDrawSuite.h 各函数文档注明 "failure, e.g. if function is
//! called outside kOfxInteractActionDraw" → 存活表查不到即
//! kOfxStatFailed。
//! - 状态(colour / lineWidth / stipple / viewport / pixelScale)保存在
//! [`DrawContext`],draw action 之间不共享。
//! - GL 命令要求上下文 current:宿主在调 `kOfxInteractActionDraw` 前经
//! [`crate::gl_bridge::acquire`] 保持 current(draw action 全期)。
//!
//! ## 绘制实现(真实 GL)
//!
//! gl_bridge 的 CGL 上下文是 **3.2 core profile**(无固定管线,
//! glBegin 不可用)——本套件的 draw 用最小着色器 + VAO/VBO 真实渲染:
//! 正交投影把 canonical 坐标映射到 NDC(canonical 宽 = viewport /
//! pixelScale),非不透明色按 "over" 合成(ofxDrawSuite.h setColour
//! 文档要求)。非 macOS 无 GL 桥 → kOfxStatFailed。
//!
//! ## drawText
//!
//! 本宿主无字体光栅化器(GL 内画字形需要字库/曲线上采样,超出 Phase
//! 1 范围),如实返回 kOfxStatErrUnsupported,不假装画了字。
use std::collections::HashMap;
use std::ffi::{c_char, c_float, c_int, c_void, CStr};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::{LazyLock, Mutex};
use crate::suites::status;
/// `OfxStandardColour`(ofxDrawSuite.h:37-46)枚举值。
pub mod std_colour {
/// kOfxStandardColourOverlayBackground。
pub const BACKGROUND: i32 = 0;
/// kOfxStandardColourOverlayActive。
pub const ACTIVE: i32 = 1;
/// kOfxStandardColourOverlaySelected。
pub const SELECTED: i32 = 2;
/// kOfxStandardColourOverlayDeselected。
pub const DESELECTED: i32 = 3;
/// kOfxStandardColourOverlayMarqueeFG。
pub const MARQUEE_FG: i32 = 4;
/// kOfxStandardColourOverlayMarqueeBG。
pub const MARQUEE_BG: i32 = 5;
/// kOfxStandardColourOverlayText。
pub const TEXT: i32 = 6;
}
/// `OfxDrawLineStipplePattern`(ofxDrawSuite.h:49-56)枚举值。
pub mod stipple {
/// kOfxDrawLineStipplePatternSolid。
pub const SOLID: i32 = 0;
/// kOfxDrawLineStipplePatternDot。
pub const DOT: i32 = 1;
/// kOfxDrawLineStipplePatternDash。
pub const DASH: i32 = 2;
/// kOfxDrawLineStipplePatternAltDash。
pub const ALT_DASH: i32 = 3;
/// kOfxDrawLineStipplePatternDotDash。
pub const DOT_DASH: i32 = 4;
}
/// `OfxDrawPrimitive`(ofxDrawSuite.h:60-68)枚举值。
pub mod primitive {
/// kOfxDrawPrimitiveLines(n 点画 n/2 条独立线段)。
pub const LINES: i32 = 0;
/// kOfxDrawPrimitiveLineStrip。
pub const LINE_STRIP: i32 = 1;
/// kOfxDrawPrimitiveLineLoop。
pub const LINE_LOOP: i32 = 2;
/// kOfxDrawPrimitiveRectangle(轴对齐实心矩形,2 对角点)。
pub const RECTANGLE: i32 = 3;
/// kOfxDrawPrimitivePolygon(实心 n 边形)。
pub const POLYGON: i32 = 4;
/// kOfxDrawPrimitiveEllipse(2 对角点包围盒内的轴对齐椭圆**线框**)。
pub const ELLIPSE: i32 = 5;
}
/// `OfxRGBAColourF`(ofxPixels.h):Draw suite 的颜色值类型。
#[repr(C)]
#[derive(Clone, Copy)]
pub struct OfxRGBAColourF {
/// 红。
pub r: f32,
/// 绿。
pub g: f32,
/// 蓝。
pub b: f32,
/// alpha。
pub a: f32,
}
/// `OfxPointD`(ofxCore.h:819):canonical 坐标点。
#[repr(C)]
#[derive(Clone, Copy)]
pub struct OfxPointD {
/// x。
pub x: f64,
/// y。
pub y: f64,
}
/// Draw suite 上下文:一次 draw action 期间插件的绘制状态。
///
/// 宿主在 [`crate::suites::interact::Interact::draw`] 内创建并注册,
/// draw 返回后摘除。`viewport`/`pixel_scale` 在创建时快照(canonical
/// → NDC 正交投影用);颜色/线宽/虚线样式由插件经 suite 函数写入。
pub struct DrawContext {
/// 当前绘制颜色(RGBA;setColour 写入,draw 时作为着色器 uniform)。
pub colour: [f32; 4],
/// 当前线宽(setLineWidth;GL 线绘制 glLineWidth)。
pub line_width: f32,
/// 当前虚线样式(setLineStipple;`stipple::*` 枚举)。
pub stipple: i32,
/// 视口尺寸(像素;创建时快照)。
pub viewport: (f64, f64),
/// canonical→屏幕像素比例(创建时快照)。
pub pixel_scale: (f64, f64),
}
impl DrawContext {
/// 新上下文(默认颜色不透明黑、线宽 1、实线)。
pub fn new(viewport: (f64, f64), pixel_scale: (f64, f64)) -> Self {
Self {
colour: [0.0, 0.0, 0.0, 1.0],
line_width: 1.0,
stipple: stipple::SOLID,
viewport,
pixel_scale,
}
}
}
/// 存活绘制上下文表:draw action 期间注册(地址 → 盒值)。
/// 插件只在 draw 内持有句柄,draw 返回即摘除(同
/// [`crate::suites::gl_render`] 的 LIVE_TEXTURES 模式)。
static LIVE_CONTEXTS: LazyLock<Mutex<HashMap<usize, Box<DrawContext>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
fn lock() -> std::sync::MutexGuard<'static, HashMap<usize, Box<DrawContext>>> {
LIVE_CONTEXTS.lock().unwrap_or_else(|e| e.into_inner())
}
/// 注册上下文并返回句柄(宿主 draw action 调用;句柄写入 inArgs 的
/// kOfxInteractPropDrawContext)。
pub(crate) fn make_context(viewport: (f64, f64), pixel_scale: (f64, f64)) -> *mut c_void {
let ctx = Box::new(DrawContext::new(viewport, pixel_scale));
let addr = &*ctx as *const DrawContext as usize;
lock().insert(addr, ctx);
addr as *mut c_void
}
/// 摘除上下文(draw action 返回后调用;后续 suite 调用 → Failed)。
pub(crate) fn drop_context(handle: *mut c_void) {
lock().remove(&(handle as usize));
}
/// 公共入口模板:panic 兜底。
fn caught(f: impl FnOnce() -> Result<(), c_int>) -> c_int {
catch_unwind(AssertUnwindSafe(f)).map_or_else(
|_| status::FAILED,
|r| r.map_or_else(|c| c, |()| status::OK),
)
}
/// 上下文句柄解析(存活表反查;draw action 外 → Failed,ofxDrawSuite.h
/// 的 "outside kOfxInteractActionDraw" 语义)。
fn resolve(handle: *mut c_void) -> Result<&'static DrawContext, c_int> {
if handle.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
let addr = handle as usize;
lock()
.get(&addr)
.map(|b| unsafe { &*(&**b as *const DrawContext) })
.ok_or(status::FAILED)
}
/// 可变访问(resolve 的写路径;draw 期单线程,存活保证同 resolve)。
fn resolve_mut(handle: *mut c_void) -> Result<(), c_int> {
resolve(handle).map(|_| ())
}
// ---- 宿主标准颜色板(getColour)----
/// 宿主标准颜色板:按 `OfxStandardColour` 枚举序(ofxDrawSuite.h:37-46)。
const PALETTE: [[f32; 4]; 7] = [
// BACKGROUND:宿主视口背景(本宿主 Phase 1 无合成背景,黑)。
[0.0, 0.0, 0.0, 1.0],
// ACTIVE:进行中/激活的 overlay 元素。
[1.0, 0.84, 0.0, 1.0],
// SELECTED:选中元素。
[0.0, 1.0, 0.0, 1.0],
// DESELECTED:未选中元素。
[1.0, 1.0, 1.0, 0.5],
// MARQUEE_FG:框选前景。
[1.0, 1.0, 1.0, 1.0],
// MARQUEE_BG:框选背景。
[0.0, 0.0, 0.0, 0.5],
// TEXT:overlay 文本。
[1.0, 1.0, 1.0, 1.0],
];
unsafe extern "C" fn get_colour(
ctx: *mut c_void,
std_colour: c_int,
out: *mut OfxRGBAColourF,
) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_VALUE);
}
let _ = resolve(ctx)?;
let c = PALETTE
.get(std_colour as usize)
.ok_or(status::ERR_VALUE)?;
unsafe {
*out = OfxRGBAColourF {
r: c[0],
g: c[1],
b: c[2],
a: c[3],
};
}
Ok(())
})
}
unsafe extern "C" fn set_colour(ctx: *mut c_void, colour: *const OfxRGBAColourF) -> c_int {
caught(|| {
if colour.is_null() {
return Err(status::ERR_VALUE);
}
let _ = resolve_mut(ctx)?;
let v = unsafe { &*colour };
let addr = ctx as usize;
let mut live = lock();
let slot = live.get_mut(&addr).expect("resolve 已保证存活");
slot.colour = [v.r, v.g, v.b, v.a];
Ok(())
})
}
unsafe extern "C" fn set_line_width(ctx: *mut c_void, width: c_float) -> c_int {
caught(|| {
let _ = resolve_mut(ctx)?;
let addr = ctx as usize;
let mut live = lock();
let slot = live.get_mut(&addr).expect("resolve 已保证存活");
slot.line_width = width;
Ok(())
})
}
unsafe extern "C" fn set_line_stipple(ctx: *mut c_void, pattern: c_int) -> c_int {
caught(|| {
if !(0..=stipple::DOT_DASH).contains(&pattern) {
return Err(status::ERR_VALUE);
}
let _ = resolve_mut(ctx)?;
let addr = ctx as usize;
let mut live = lock();
let slot = live.get_mut(&addr).expect("resolve 已保证存活");
slot.stipple = pattern;
Ok(())
})
}
unsafe extern "C" fn draw(
ctx: *mut c_void,
prim: c_int,
points: *const OfxPointD,
count: c_int,
) -> c_int {
caught(|| {
if !(0..=primitive::ELLIPSE).contains(&prim) {
return Err(status::ERR_VALUE);
}
if count < 0 || (count > 0 && points.is_null()) {
return Err(status::ERR_VALUE);
}
// 每原语的合法点数(ofxDrawSuite.h draw 文档)。
let valid = match prim {
primitive::LINES => count >= 2 && count % 2 == 0,
primitive::LINE_STRIP | primitive::LINE_LOOP => count >= 2,
primitive::RECTANGLE | primitive::ELLIPSE => count == 2,
primitive::POLYGON => count >= 3,
_ => false,
};
if !valid {
return Err(status::ERR_VALUE);
}
let c = resolve(ctx)?;
let pts: Vec<OfxPointD> = (0..count as usize)
.map(|i| unsafe { *points.add(i) })
.collect();
// 真实 GL 渲染(macOS 3.2 core;非 macOS stub → Failed)。
gl_imp::render(c, prim, &pts)
})
}
unsafe extern "C" fn draw_text(
ctx: *mut c_void,
text: *const c_char,
pos: *const OfxPointD,
_alignment: c_int,
) -> c_int {
caught(|| {
if text.is_null() || pos.is_null() {
return Err(status::ERR_VALUE);
}
let _ = resolve(ctx)?;
// 确认文本有效(UTF-8);随后如实拒绝(无字体光栅化器)。
let _ = unsafe { CStr::from_ptr(text) }
.to_str()
.map_err(|_| status::ERR_VALUE)?;
Err(status::ERR_UNSUPPORTED)
})
}
/// 函数表布局(与 SDK `OfxDrawSuiteV1` 逐字段一致;ofxDrawSuite.h:85-177)。
#[repr(C)]
pub struct DrawSuiteV1 {
/// getColour:宿主标准颜色板取色。
pub get_colour: unsafe extern "C" fn(*mut c_void, c_int, *mut OfxRGBAColourF) -> c_int,
/// setColour:设置后续绘制颜色。
pub set_colour: unsafe extern "C" fn(*mut c_void, *const OfxRGBAColourF) -> c_int,
/// setLineWidth:设置后续线宽。
pub set_line_width: unsafe extern "C" fn(*mut c_void, c_float) -> c_int,
/// setLineStipple:设置后续虚线样式。
pub set_line_stipple: unsafe extern "C" fn(*mut c_void, c_int) -> c_int,
/// draw:绘制原语(点数组,canonical 坐标)。
pub draw: unsafe extern "C" fn(*mut c_void, c_int, *const OfxPointD, c_int) -> c_int,
/// drawText:绘制文本(Phase 1 返回 kOfxStatErrUnsupported)。
pub draw_text: unsafe extern "C" fn(*mut c_void, *const c_char, *const OfxPointD, c_int) -> c_int,
}
/// 函数表实例。
pub fn suite_v1() -> &'static DrawSuiteV1 {
static SUITE: std::sync::OnceLock<DrawSuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| DrawSuiteV1 {
get_colour,
set_colour,
set_line_width,
set_line_stipple,
draw,
draw_text,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// 标准颜色板:getColour 按枚举取宿主色板(越界 → ErrValue)。
#[test]
fn get_colour_palette() {
let ctx = make_context((640.0, 480.0), (1.0, 1.0));
let mut out = OfxRGBAColourF { r: 0.0, g: 0.0, b: 0.0, a: 0.0 };
unsafe {
assert_eq!(get_colour(ctx, std_colour::ACTIVE, &mut out), status::OK);
}
assert_eq!((out.r, out.g, out.b, out.a), (1.0, 0.84, 0.0, 1.0));
// 越界枚举 → ErrValue。
unsafe {
assert_eq!(get_colour(ctx, 99, &mut out), status::ERR_VALUE);
assert_eq!(get_colour(ctx, -1, &mut out), status::ERR_VALUE);
// 空输出指针 → ErrValue。
assert_eq!(
get_colour(ctx, std_colour::BACKGROUND, std::ptr::null_mut()),
status::ERR_VALUE
);
}
drop_context(ctx);
}
/// setColour 真实写入状态:再 setLineWidth/setLineStipple 后从存活
/// 表读回(draw action 期插件视图)。
#[test]
fn set_colour_and_line_state() {
let ctx = make_context((100.0, 100.0), (2.0, 2.0));
let col = OfxRGBAColourF { r: 0.9, g: 0.1, b: 0.2, a: 1.0 };
unsafe {
assert_eq!(set_colour(ctx, &col), status::OK);
assert_eq!(set_line_width(ctx, 3.5), status::OK);
assert_eq!(set_line_stipple(ctx, stipple::DASH), status::OK);
assert_eq!(set_line_stipple(ctx, 99), status::ERR_VALUE);
}
let addr = ctx as usize;
let live = lock();
let c = live.get(&addr).unwrap();
assert_eq!(c.colour, [0.9, 0.1, 0.2, 1.0]);
assert_eq!(c.line_width, 3.5);
assert_eq!(c.stipple, stipple::DASH);
drop(live);
drop_context(ctx);
}
/// 摘除后调用 → Failed("outside kOfxInteractActionDraw" 语义)。
#[test]
fn draw_suite_outside_draw_fails() {
let ctx = make_context((10.0, 10.0), (1.0, 1.0));
drop_context(ctx);
let col = OfxRGBAColourF { r: 1.0, g: 0.0, b: 0.0, a: 1.0 };
let mut out = OfxRGBAColourF { r: 0.0, g: 0.0, b: 0.0, a: 0.0 };
let s = std::ffi::CString::new("x").unwrap();
let pos = OfxPointD { x: 0.0, y: 0.0 };
let pts = [OfxPointD { x: 0.0, y: 0.0 }, OfxPointD { x: 10.0, y: 10.0 }];
unsafe {
assert_eq!(set_colour(ctx, &col), status::FAILED);
assert_eq!(get_colour(ctx, std_colour::TEXT, &mut out), status::FAILED);
assert_eq!(set_line_width(ctx, 1.0), status::FAILED);
assert_eq!(set_line_stipple(ctx, stipple::SOLID), status::FAILED);
// 合法参数(避开空指针检查)→ 摘除后 resolve 失败 → Failed。
assert_eq!(draw(ctx, primitive::RECTANGLE, pts.as_ptr(), 2), status::FAILED);
// drawText 同样 Failed(先 resolve 失败)。
assert_eq!(draw_text(ctx, s.as_ptr(), &pos, 0), status::FAILED);
}
}
/// draw 原语参数校验(不触 GL):非法原语/点数 → ErrValue。
#[test]
fn draw_primitive_argument_validation() {
let ctx = make_context((10.0, 10.0), (1.0, 1.0));
let pts = [OfxPointD { x: 0.0, y: 0.0 }, OfxPointD { x: 10.0, y: 10.0 }];
unsafe {
// 非法原语枚举。
assert_eq!(draw(ctx, 99, pts.as_ptr(), 2), status::ERR_VALUE);
assert_eq!(draw(ctx, -1, pts.as_ptr(), 2), status::ERR_VALUE);
// 点数不合法:LINES 奇数点。
assert_eq!(draw(ctx, primitive::LINES, pts.as_ptr(), 3), status::ERR_VALUE);
// RECTANGLE 需恰好 2 点。
assert_eq!(draw(ctx, primitive::RECTANGLE, pts.as_ptr(), 3), status::ERR_VALUE);
// POLYGON 需 ≥3 点。
assert_eq!(draw(ctx, primitive::POLYGON, pts.as_ptr(), 2), status::ERR_VALUE);
// 空指针 + 正点数。
assert_eq!(draw(ctx, primitive::LINES, std::ptr::null(), 2), status::ERR_VALUE);
// 合法参数:环境相关的 GL 路径(无 current 上下文时宿主可能
// 失败)——参数校验已过即可,具体状态不在此断言。
let st = draw(ctx, primitive::RECTANGLE, pts.as_ptr(), 2);
assert!(
st == status::OK || st == status::FAILED,
"合法参数应 OK(有 GL)或 Failed(无 GL 上下文),got {st}"
);
}
drop_context(ctx);
}
/// drawText:有效参数 → Unsupported(如实拒绝);空指针 → ErrValue。
#[test]
fn draw_text_is_honest_unsupported() {
let ctx = make_context((10.0, 10.0), (1.0, 1.0));
let s = std::ffi::CString::new("hello").unwrap();
let pos = OfxPointD { x: 1.0, y: 2.0 };
unsafe {
assert_eq!(draw_text(ctx, s.as_ptr(), &pos, 0), status::ERR_UNSUPPORTED);
assert_eq!(draw_text(ctx, std::ptr::null(), &pos, 0), status::ERR_VALUE);
}
drop_context(ctx);
}
}
// ---- GL 绘制实现(平台分派)--------------------------------------------
#[cfg(target_os = "macos")]
mod gl_imp {
use super::{DrawContext, OfxPointD};
use crate::suites::status;
use std::ffi::c_void;
// ---- GL 常量(GL 规范值)----
const GL_FALSE: i32 = 0;
const GL_FLOAT: u32 = 0x1406;
const GL_ARRAY_BUFFER: u32 = 0x8892;
const GL_STATIC_DRAW: u32 = 0x88E4;
const GL_FRAGMENT_SHADER: u32 = 0x8B30;
const GL_VERTEX_SHADER: u32 = 0x8B31;
const GL_COMPILE_STATUS: u32 = 0x8B81;
const GL_LINK_STATUS: u32 = 0x8B82;
const GL_TRIANGLES: u32 = 0x0004;
const GL_LINES: u32 = 0x0001;
const GL_LINE_STRIP: u32 = 0x0003;
const GL_LINE_LOOP: u32 = 0x0002;
const GL_BLEND: u32 = 0x0BE2;
const GL_SRC_ALPHA: u32 = 0x0302;
const GL_ONE_MINUS_SRC_ALPHA: u32 = 0x0303;
const GL_NO_ERROR: u32 = 0;
// # Safety: 全部是 OpenGL.framework 导出函数;参数语义见各函数
// 注释。调用前提:GL 上下文 current(宿主 draw action 已 acquire)。
#[link(name = "OpenGL", kind = "framework")]
unsafe extern "C" {
fn glGenVertexArrays(n: i32, arrays: *mut u32);
fn glBindVertexArray(array: u32);
fn glGenBuffers(n: i32, buffers: *mut u32);
fn glBindBuffer(target: u32, buffer: u32);
fn glBufferData(target: u32, size: isize, data: *const c_void, usage: u32);
fn glCreateShader(type_: u32) -> u32;
fn glShaderSource(shader: u32, count: i32, string: *const *const i8, length: *const i32);
fn glCompileShader(shader: u32);
fn glGetShaderiv(shader: u32, pname: u32, params: *mut i32);
fn glDeleteShader(shader: u32);
fn glCreateProgram() -> u32;
fn glAttachShader(program: u32, shader: u32);
fn glLinkProgram(program: u32);
fn glGetProgramiv(program: u32, pname: u32, params: *mut i32);
fn glUseProgram(program: u32);
fn glGetAttribLocation(program: u32, name: *const i8) -> i32;
fn glVertexAttribPointer(
index: u32,
size: i32,
type_: u32,
normalized: u8,
stride: i32,
pointer: *const c_void,
);
fn glEnableVertexAttribArray(index: u32);
fn glGetUniformLocation(program: u32, name: *const i8) -> i32;
fn glUniformMatrix4fv(location: i32, count: i32, transpose: u8, value: *const f32);
fn glUniform4f(location: i32, x: f32, y: f32, z: f32, w: f32);
fn glDrawArrays(mode: u32, first: i32, count: i32);
fn glLineWidth(width: f32);
fn glEnable(cap: u32);
fn glBlendFunc(sfactor: u32, dfactor: u32);
fn glGetError() -> u32;
}
/// 顶点着色器(canonical 坐标 + 颜色 uniform;投影映射到 NDC)。
const VERT_SRC: &[u8] = b"#version 150\n\
in vec2 a_pos;\n\
uniform mat4 u_proj;\n\
uniform vec4 u_col;\n\
out vec4 v_col;\n\
void main() {\n\
v_col = u_col;\n\
gl_Position = u_proj * vec4(a_pos, 0.0, 1.0);\n\
}\n\0";
const FRAG_SRC: &[u8] = b"#version 150\n\
in vec4 v_col;\n\
out vec4 frag_color;\n\
void main() { frag_color = v_col; }\n\0";
fn compile_shader(kind: u32, src: &[u8]) -> Result<u32, i32> {
// SAFETY: glCreateShader/glShaderSource/glCompileShader 均为当前
// 上下文的合法调用;src 是 NUL 结尾串(b"...\0")。
let sh = unsafe { glCreateShader(kind) };
if sh == 0 {
return Err(status::FAILED);
}
unsafe {
let ptr = src.as_ptr() as *const i8;
glShaderSource(sh, 1, &ptr, std::ptr::null());
glCompileShader(sh);
}
let mut ok: i32 = 0;
// SAFETY: glGetShaderiv 写 ok。
unsafe { glGetShaderiv(sh, GL_COMPILE_STATUS, &mut ok) };
if ok == GL_FALSE {
// SAFETY: sh 是本函数 glCreateShader 的产物。
unsafe { glDeleteShader(sh) };
return Err(status::FAILED);
}
Ok(sh)
}
/// 惰性资源组:(program, vao, vbo)。进程级缓存;VAO/VBO 固定复用,
/// 每次 draw 用 glBufferData 重灌顶点(避免逐次分配/泄漏)。
fn resources() -> Result<(u32, u32, u32), i32> {
static RES: std::sync::OnceLock<Result<(u32, u32, u32), i32>> = std::sync::OnceLock::new();
*RES.get_or_init(|| {
let vs = match compile_shader(GL_VERTEX_SHADER, VERT_SRC) {
Ok(s) => s,
Err(e) => return Err(e),
};
let fs = match compile_shader(GL_FRAGMENT_SHADER, FRAG_SRC) {
Ok(s) => s,
Err(e) => {
// SAFETY: vs 是本闭包编译成功的着色器。
unsafe { glDeleteShader(vs) };
return Err(e);
}
};
let prog = unsafe { glCreateProgram() };
if prog == 0 {
// SAFETY: vs/fs 均有效。
unsafe {
glDeleteShader(vs);
glDeleteShader(fs);
}
return Err(status::FAILED);
}
unsafe {
glAttachShader(prog, vs);
glAttachShader(prog, fs);
glLinkProgram(prog);
}
let mut ok: i32 = 0;
// SAFETY: glGetProgramiv 写 ok。
unsafe { glGetProgramiv(prog, GL_LINK_STATUS, &mut ok) };
// 链接后可删着色器对象(程序保留可执行版本)。
unsafe {
glDeleteShader(vs);
glDeleteShader(fs);
}
if ok == GL_FALSE {
return Err(status::FAILED);
}
// SAFETY: 生成并绑定固定 VAO/VBO(3.2 core)。
let mut vao: u32 = 0;
let mut vbo: u32 = 0;
unsafe {
glGenVertexArrays(1, &mut vao);
glBindVertexArray(vao);
glGenBuffers(1, &mut vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
}
Ok((prog, vao, vbo))
})
}
/// canonical→NDC 正交投影(列主序 4x4)。
fn ortho(cw: f64, ch: f64) -> [f32; 16] {
let (cw, ch) = (cw.max(1.0) as f32, ch.max(1.0) as f32);
[
2.0 / cw, 0.0, 0.0, 0.0,
0.0, 2.0 / ch, 0.0, 0.0,
0.0, 0.0, -1.0, 0.0,
-1.0, -1.0, 0.0, 1.0,
]
}
/// 按原语生成 GL 顶点(canonical 坐标;已按图元类型合法)。
fn vertices(prim: i32, pts: &[OfxPointD]) -> (u32, Vec<f32>) {
match prim {
super::primitive::LINES => (
GL_LINES,
pts.iter().flat_map(|p| [p.x as f32, p.y as f32]).collect(),
),
super::primitive::LINE_STRIP => (
GL_LINE_STRIP,
pts.iter().flat_map(|p| [p.x as f32, p.y as f32]).collect(),
),
super::primitive::LINE_LOOP => (
GL_LINE_LOOP,
pts.iter().flat_map(|p| [p.x as f32, p.y as f32]).collect(),
),
super::primitive::RECTANGLE => {
let (x1, y1) = (pts[0].x as f32, pts[0].y as f32);
let (x2, y2) = (pts[1].x as f32, pts[1].y as f32);
// 两个三角形组成实心矩形(对角点定义)。
(
GL_TRIANGLES,
vec![
x1, y1, x2, y1, x1, y2,
x1, y2, x2, y1, x2, y2,
],
)
}
super::primitive::POLYGON => {
// 三角扇:0,i,i+1(凸多边形约定)。
let mut v = Vec::new();
for i in 1..pts.len() - 1 {
v.extend_from_slice(&[
pts[0].x as f32, pts[0].y as f32,
pts[i].x as f32, pts[i].y as f32,
pts[i + 1].x as f32, pts[i + 1].y as f32,
]);
}
(GL_TRIANGLES, v)
}
super::primitive::ELLIPSE => {
// 椭圆**线框**(文档),包围盒内 64 段线环。
let (cx, cy) = ((pts[0].x + pts[1].x) / 2.0, (pts[0].y + pts[1].y) / 2.0);
let (rx, ry) = (
(pts[1].x - pts[0].x).abs() / 2.0,
(pts[1].y - pts[0].y).abs() / 2.0,
);
let n = 64;
let mut v = Vec::with_capacity(n * 2);
for i in 0..n {
let a = std::f64::consts::TAU * i as f64 / n as f64;
v.push((cx + rx * a.cos()) as f32);
v.push((cy + ry * a.sin()) as f32);
}
(GL_LINE_LOOP, v)
}
_ => (GL_TRIANGLES, Vec::new()),
}
}
/// 真实渲染:绑定固定 VAO/VBO、重灌顶点、设置 uniform、绘制。
/// 要求 GL 上下文 current(宿主 draw action 已 acquire);无 current
/// 上下文时不发任何 GL 命令(macOS 无 current 调 GL 是未定义行为,
/// 直接失败)。
pub fn render(ctx: &DrawContext, prim: i32, pts: &[OfxPointD]) -> Result<(), i32> {
if !crate::gl_bridge::is_current() {
return Err(status::FAILED);
}
let (prog, vao, vbo) = resources().map_err(|_| status::FAILED)?;
let (mode, verts) = vertices(prim, pts);
if verts.is_empty() {
return Err(status::ERR_VALUE);
}
// 合成:非不透明色 "over"(ofxDrawSuite.h setColour 文档)。
if ctx.colour[3] < 1.0 {
// SAFETY: 开启混合并设因子(上下文 current)。
unsafe {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
}
// SAFETY: 以下 GL 调用均要求上下文 current(宿主已保证);对象
// 名来自 resources()(本进程唯一 GL 使用方)。
unsafe {
glUseProgram(prog);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(
GL_ARRAY_BUFFER,
(verts.len() * 4) as isize,
verts.as_ptr() as *const c_void,
GL_STATIC_DRAW,
);
let a_pos = glGetAttribLocation(prog, b"a_pos\0".as_ptr() as *const i8);
if a_pos < 0 {
return Err(status::FAILED);
}
glVertexAttribPointer(a_pos as u32, 2, GL_FLOAT, 0, 0, std::ptr::null());
glEnableVertexAttribArray(a_pos as u32);
let u_proj = glGetUniformLocation(prog, b"u_proj\0".as_ptr() as *const i8);
let u_col = glGetUniformLocation(prog, b"u_col\0".as_ptr() as *const i8);
let cw = ctx.viewport.0 / ctx.pixel_scale.0.max(1e-6);
let ch = ctx.viewport.1 / ctx.pixel_scale.1.max(1e-6);
let m = ortho(cw, ch);
glUniformMatrix4fv(u_proj, 1, 0, m.as_ptr());
glUniform4f(u_col, ctx.colour[0], ctx.colour[1], ctx.colour[2], ctx.colour[3]);
if ctx.line_width > 0.0 {
glLineWidth(ctx.line_width);
}
glDrawArrays(mode, 0, (verts.len() / 2) as i32);
// 解除绑定(对象保留复用)。
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUseProgram(0);
}
let err = unsafe { glGetError() };
if err != GL_NO_ERROR {
return Err(status::FAILED);
}
Ok(())
}
}
/// 非 macOS:Draw suite 的 GL 绘制 stub(无 GL 桥 → Failed)。
#[cfg(not(target_os = "macos"))]
mod gl_imp {
use super::{DrawContext, OfxPointD};
use crate::suites::status;
pub fn render(_ctx: &DrawContext, _prim: i32, _pts: &[OfxPointD]) -> Result<(), i32> {
Err(status::FAILED)
}
}
+546
View File
@@ -0,0 +1,546 @@
// 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/>.
//! OfxImageEffectOpenGLRenderSuiteV1(M11 第 2 期):clipLoadTexture /
//! clipFreeTexture / flushResources。
//!
//! 语义对照 ofxGPURender.h(vendored,OpenGL Render Suite 一节)与
//! HostSupport 插件侧实现(HS: ofxhImageEffect.cpp:2296-2367):
//!
//! - `clipLoadTexture(clip, time, format, region, *texture)`:把 clip
//! 在 `time` 的图像加载为 GL 纹理。纹理句柄是**属性集**(标签 0),
//! 含 ofxGPURender.h 规定的 12 个属性(OpenGLTextureIndex/
//! OpenGLTextureTarget/PixelDepth/Components/PreMultiplication/
//! RenderScale/PixelAspectRatio/Bounds/RegionOfDefinition/RowBytes/
//! Field/UniqueIdentifier);宿主侧存强引用([`LIVE_TEXTURES`]),
//! clipFreeTexture 摘除即释放(对应 HS 的 get/release 配对)。
//! **OpenGLTextureIndex 是真实 GL 纹理名**(GL 模式,见
//! [`crate::gl_bridge`] 方案 B):Output clip 是宿主为输出帧建的
//! GL 纹理(经 GlCtx 注入,render 驱动负责建/FBO 挂载/回读/删除);
//! 输入 clip 是本 suite 在 GL 渲染期经桥上传图像得到的 GL 纹理
//! (clipFreeTexture 删除)。0 = CPU 回退(无 GL 名,插件按规范回退)。
//! - Output clip:`format` 忽略,宿主返回已附着的输出纹理句柄——
//! 绑定渲染目标的动作(ofxGPURender.h "the host must bind the
//! resulting texture as the current color buffer")由调用方约定:
//! GL render 驱动在进入 render_gl 前已把输出 GL 纹理挂进 FBO 并
//! 绑定(等价 C++ 的 `PluginRenderer::attach_output_texture`)。
//! clipFreeTexture 对 Output 只释放句柄、不删纹理(宿主还要回读它,
//! 回读后由 render 驱动删除)。
//! - 输入纹理在 GL 模式经 [`crate::gl_bridge::create_input_texture`]
//! 上传(CPU 帧 → GL 纹理);CPU 模式(无 GL 上下文)维持
//! [`crate::render`] 的 CPU 纹理。纹理格式:全链路 F32 约束下,
//! 像素深度按 clip 协商结果(恒 F32);`format` 参数
//! (kOfxImageEffectGLFormat*)若请求的分量与协商分量不符,Phase 2
//! 不做转换 → Failed(规范要求 "host ensures it gives the requested
//! format"——宁可显式失败也不静默给错格式)。ofxGPURender.h 注明
//! "宿主无需按 Clip Preferences 把图像重映射到插件请求的位深",
//! 插件以纹理句柄的 PixelDepth/Components 为准。
//! - `flushResources`:宿主在 render 之间不缓存 GPU 资源(纹理随
//! clipFreeTexture 立即释放)→ 无可释放 → kOfxStatReplyDefault
//! (规范:"nothing the host could do")。
//! - GL 上下文规则(ofxGPURender.h "OpenGL Current Context"):宿主
//! 只在 Render/BeginSequenceRender/EndSequenceRender/Attach/Detach
//! 期间要求上下文 current;本实现的约定是 render 驱动一次 acquire
//! 整个 GL render action([`crate::gl_bridge::acquire`]),本 suite
//! 回调期间上下文恒 current,经 [`crate::suites::gl_ctx`] TLS 取
//! 渲染器句柄。
use std::collections::HashMap;
use std::ffi::{c_char, c_double, c_int, c_void, CStr, CString};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Mutex;
use crate::clip::ClipInstance;
use crate::image::Image;
use crate::property::{PropertySet, Value};
use crate::suites::{status, tag};
// ---- GL 常量(ofxGPURender.h;GLFormat 字符串为 ofxOpenGLRender.h
// OpenFX 1.4 的规范名,vendored 头文件是 stub 未收录,按规范定义)----
/// kOfxImageEffectPropOpenGLTextureIndex(ofxGPURender.h:135)。
pub(crate) const GL_TEXTURE_INDEX: &str = "OfxImageEffectPropOpenGLTextureIndex";
/// kOfxImageEffectPropOpenGLTextureTarget(ofxGPURender.h:152)。
pub(crate) const GL_TEXTURE_TARGET: &str = "OfxImageEffectPropOpenGLTextureTarget";
/// kOfxImageEffectGLFormatRGBA(ofxOpenGLRender.h 1.4)。
pub(crate) const GL_FORMAT_RGBA: &str = "OfxImageEffectGLFormatRGBA";
/// kOfxImageEffectGLFormatRGB。
pub(crate) const GL_FORMAT_RGB: &str = "OfxImageEffectGLFormatRGB";
/// kOfxImageEffectGLFormatAlpha。
pub(crate) const GL_FORMAT_ALPHA: &str = "OfxImageEffectGLFormatAlpha";
/// kOfxImageEffectGLFormatLuminance。
pub(crate) const GL_FORMAT_LUMINANCE: &str = "OfxImageEffectGLFormatLuminance";
/// kOfxImageEffectGLFormatLuminanceAlpha。
pub(crate) const GL_FORMAT_LUMINANCE_ALPHA: &str = "OfxImageEffectGLFormatLuminanceAlpha";
/// GL_TEXTURE_2D 的 GLenum 值(0x0DE1;纹理句柄的 OpenGLTextureTarget
/// 属性。GL 规范值,非 OFX 宏)。
pub(crate) const GL_TEXTURE_2D: i32 = 0x0DE1;
/// kOfxImageEffectPropPreMultiplication 的非预乘默认值。
pub(crate) const PREMULT_NONE: &str = "OfxImagePreMultipliedNone";
/// GL 像素深度协商(ofxGPURender.h:65-89 kOfxOpenGLPropPixelDepth):
/// 插件描述符声明的 GL 渲染支持位深列表(可选)。
///
/// 返回 Some(实际位深) 表示 GL 模式可行,None 表示管线无法满足
/// 插件声明 → 宿主应回退 CPU 渲染(ofxGPURender.h "the host will
/// try to provide buffers/textures in one of the supported formats";
/// Phase 2 全链路 F32,无法提供其他位深):
/// - 列表缺失/为空 → Some(Float)(宿主自选,规范默认);
/// - 列表含 Float → Some(Float);
/// - 列表存在且不含 Float → None(管线约束;GL 模式不可行)。
pub(crate) fn pick_gl_pixel_depth(
plugin_props: &crate::property::PropertySet,
) -> Option<&'static str> {
use crate::property::Value;
let dim = plugin_props.dimension(crate::host::PROP_GL_PIXEL_DEPTH);
if dim == 0 {
return Some("OfxBitDepthFloat");
}
for i in 0..dim {
if let Some(Value::String(s)) = plugin_props.get(crate::host::PROP_GL_PIXEL_DEPTH, i) {
if s.to_string_lossy() == "OfxBitDepthFloat" {
return Some("OfxBitDepthFloat");
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::property::{PropertySet, Value};
fn cs(s: &str) -> CString {
CString::new(s).unwrap()
}
/// GL 像素深度协商矩阵(ofxGPURender.h kOfxOpenGLPropPixelDepth):
/// 未声明/含 Float → 管线 F32 可行;声明且不含 Float → None
/// (GL 模式不可行,回退 CPU)。
#[test]
fn pick_gl_pixel_depth_matrix() {
let props = PropertySet::new();
assert_eq!(pick_gl_pixel_depth(&props), Some("OfxBitDepthFloat"));
let props2 = PropertySet::new();
props2.define(
crate::host::PROP_GL_PIXEL_DEPTH,
vec![
Value::String(cs("OfxBitDepthHalf")),
Value::String(cs("OfxBitDepthByte")),
],
);
assert_eq!(pick_gl_pixel_depth(&props2), None);
let props3 = PropertySet::new();
props3.define(
crate::host::PROP_GL_PIXEL_DEPTH,
vec![
Value::String(cs("OfxBitDepthByte")),
Value::String(cs("OfxBitDepthFloat")),
],
);
assert_eq!(pick_gl_pixel_depth(&props3), Some("OfxBitDepthFloat"));
let props4 = PropertySet::new();
props4.define(
crate::host::PROP_GL_PIXEL_DEPTH,
vec![Value::String(cs("OfxBitDepthFloat"))],
);
assert_eq!(pick_gl_pixel_depth(&props4), Some("OfxBitDepthFloat"));
}
}
// ---- 存活纹理表 -----------------------------------------------------------
/// 存活 GL 纹理表:clipLoadTexture 产出(props 地址 → 属性集 +
/// 纹理值 + 是否输出 clip + 真实 GL 纹理名[可选]);clipFreeTexture
/// 摘除即释放——对应 HS 的 get/release 配对
/// (HS: ofxhImageEffect.cpp:2336-2351)。纹理是 oakrender 值(drop
/// 自动释放后端 token;原 `texture_free` 调用面随值模型删除)。
///
/// `gl_texture`:GL 模式下输入 clip 经 [`crate::gl_bridge`] 建的真实
/// GL 纹理名(输出 clip 恒 None——宿主自建并负责生命周期,见
/// [`crate::gl_bridge`] 模块文档);摘除时经
/// [`delete_gl_texture_if_gl`] 删除。
///
/// 属性集必须**装箱**(Box 稳定堆地址):纹理句柄指向它,函数返回后
/// 必须仍存活;栈上临时变量会悬垂(phase-2 实现初版的 bug)。
static LIVE_TEXTURES: std::sync::LazyLock<
Mutex<HashMap<usize, (Box<PropertySet>, crate::render::Texture, bool, Option<i32>)>>,
> = std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
/// 登记纹理(clipLoadTexture 内部;`props` 装箱后取地址为句柄基址)。
/// `gl_texture`:真实 GL 纹理名(输入 clip GL 模式;无则 None)。
fn register(
props: Box<PropertySet>,
texture: crate::render::Texture,
is_output: bool,
gl_texture: Option<i32>,
) -> usize {
let addr = &*props as *const PropertySet as usize;
LIVE_TEXTURES
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(addr, (props, texture, is_output, gl_texture));
addr
}
/// 删除 GL 纹理(上下文 current 时;否则留给下次 GL 渲染前的兜底——
/// 正常路径 clipFreeTexture/purge 都在 GL render 期,上下文必 current)。
fn delete_gl_texture_if_gl(name: i32) {
if crate::suites::gl_ctx().is_some() {
crate::gl_bridge::delete_gl_texture(name);
}
}
/// 释放全部残留输入纹理(GL render action 返回后的安全网:规范要求
/// 插件在 action 返回前 clipFreeTexture 全部句柄;遗漏的输入纹理在
/// 此释放,输出纹理保留——宿主还要读它)。GL 输入纹理同步删除
/// (上下文 current;render_gl 在清 GlCtx TLS 前调用本函数)。
pub(crate) fn purge_leftovers() {
let mut live = LIVE_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
let dropped: Vec<Option<i32>> = live
.iter()
.filter(|(_, (_, _, is_output, _))| !*is_output)
.map(|(_, (_, _, _, gl))| *gl)
.collect();
live.retain(|_, (_, _, is_output, _)| *is_output);
drop(live);
for gl in dropped {
if let Some(gl) = gl {
delete_gl_texture_if_gl(gl);
}
}
}
/// 公共入口模板:panic 兜底。
fn caught(f: impl FnOnce() -> Result<(), c_int>) -> c_int {
catch_unwind(AssertUnwindSafe(f)).map_or_else(
|_| status::FAILED,
|r| r.map_or_else(|c| c, |()| status::OK),
)
}
/// clip 句柄解析(实例期)。
fn resolve_clip(handle: *mut c_void) -> Result<&'static ClipInstance, c_int> {
if handle.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
unsafe {
match tag::kind(handle) {
tag::CLIP => Ok(&*(tag::strip(handle) as *const ClipInstance)),
_ => Err(status::ERR_BAD_HANDLE),
}
}
}
fn cs(s: &str) -> CString {
CString::new(s).unwrap()
}
/// 把矩形写成 Int×4 属性(Bounds/ROD 用;OFX 图像属性是像素坐标)。
fn rect_props(props: &PropertySet, name: &str, rect: crate::instance::OfxRectD) {
let b = |v: f64| Value::Int(v.round() as i32);
props.define(name, vec![b(rect.x1), b(rect.y1), b(rect.x2), b(rect.y2)]);
}
/// 从 clip 属性读字符串(缺失返回默认)。
fn clip_string(clip: &ClipInstance, name: &str, default: &str) -> String {
clip.props
.get(name, 0)
.map(|v| match v {
Value::String(s) => s.to_string_lossy().into_owned(),
_ => default.to_string(),
})
.unwrap_or_else(|| default.to_string())
}
/// 构造纹理属性集(ofxGPURender.h 规定的属性;输入与输出共用,
/// 只是数据来源不同)。`OpenGLTextureIndex` 为真实 GL 纹理名
/// (`texture_index`;0 = 无 GL 名——CPU 回退下插件按规范回退,纹理
/// 内容仍可经 clipGetImage 取用)。
#[allow(clippy::too_many_arguments)]
fn make_texture_props(
width: f64,
height: f64,
components: crate::image::Components,
depth: &str,
premult: &str,
par: f64,
scale: crate::instance::RenderScale,
row_bytes: i32,
texture_index: i32,
) -> PropertySet {
let props = PropertySet::new();
props.set_one(GL_TEXTURE_INDEX, Value::Int(texture_index));
props.set_one(GL_TEXTURE_TARGET, Value::Int(GL_TEXTURE_2D));
props.set_one(
crate::image::K_IMAGE_EFFECT_PROP_PIXEL_DEPTH,
Value::String(cs(depth)),
);
props.set_one(
crate::image::K_IMAGE_EFFECT_PROP_COMPONENTS,
Value::String(cs(components.to_ofx())),
);
props.set_one(
"OfxImageEffectPropPreMultiplication",
Value::String(cs(premult)),
);
props.define(
crate::host::PROP_RENDER_SCALE,
vec![Value::Double(scale.x), Value::Double(scale.y)],
);
props.set_one("OfxImagePropPixelAspectRatio", Value::Double(par));
let bounds = crate::instance::OfxRectD {
x1: 0.0,
y1: 0.0,
x2: width,
y2: height,
};
rect_props(&props, crate::image::K_IMAGE_PROP_BOUNDS, bounds);
rect_props(&props, crate::image::K_IMAGE_PROP_ROD, bounds);
props.set_one(crate::image::K_IMAGE_PROP_ROW_BYTES, Value::Int(row_bytes));
props.set_one("OfxImagePropField", Value::String(cs("OfxImageFieldNone")));
props.set_one(
crate::image::K_IMAGE_PROP_UNIQUE_ID,
Value::String(crate::image::unique_identifier()),
);
props
}
/// 纹理请求格式 → 期望分量(NULL/未知 → None = 宿主自选)。
fn format_components(format: Option<&str>) -> Option<crate::image::Components> {
match format {
Some(GL_FORMAT_RGBA) | None => Some(crate::image::Components::Rgba),
Some(GL_FORMAT_RGB) => Some(crate::image::Components::Rgb),
Some(GL_FORMAT_ALPHA) => Some(crate::image::Components::Alpha),
// Luminance 族:Phase 2 不建模(无对应 Components),宿主
// 按 RGBA 上传并如实上报——格式核对走 None 分支。
Some(GL_FORMAT_LUMINANCE) | Some(GL_FORMAT_LUMINANCE_ALPHA) => None,
Some(_) => None,
}
}
/// clipLoadTexture:把 clip 在 `time` 的图像加载为 GL 纹理。
///
/// `format` 为请求的纹理格式(kOfxImageEffectGLFormat*;NULL = 宿主
/// 按插件的 kOfxOpenGLPropPixelDepth 决定——Phase 2 全链路 F32)。
/// `region`(规范坐标,可空)会裁剪到 clip 的 RoD——Phase 2 仅支持
/// 整帧(NULL);子区域请求返回 Failed(插件按规范继续,视作黑底)。
unsafe extern "C" fn clip_load_texture(
clip: *mut c_void,
time: c_double,
format: *const c_char,
region: *const c_void,
out: *mut *mut c_void,
) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
unsafe { *out = std::ptr::null_mut() };
let c = resolve_clip(clip)?;
// GL 上下文(TLS):仅 GL 渲染期存在(ofxGPURender.h 的
// "OpenGL Current Context" 规则)。
let gl = crate::suites::gl_ctx().ok_or(status::ERR_MISSING_HOST_FEATURE)?;
let scale = crate::suites::render_ctx()
.map(|ctx| ctx.scale)
.unwrap_or(crate::instance::RenderScale { x: 1.0, y: 1.0 });
if c.name == "Output" {
// Output:返回已附着的输出纹理(format 忽略;渲染目标
// 绑定由调用方契约保证——等价 C++ attach_output_texture)。
let tex = gl.output_texture.clone();
let (w, h) = texture_size(&tex);
if w <= 0.0 || h <= 0.0 {
return Err(status::ERR_BAD_HANDLE);
}
// OpenGLTextureIndex = 宿主为输出帧建的真实 GL 纹理名
// (render 驱动 GL 分支经 GlCtx 注入;0 = CPU 回退)。
let index = gl.output_gl_texture.unwrap_or(0);
let props = make_texture_props(
w,
h,
crate::image::Components::Rgba,
gl.gl_pixel_depth,
&clip_string(c, "OfxImageEffectPropPreMultiplication", PREMULT_NONE),
clip_par(c),
scale,
(w as i32) * 4 * 4,
index,
);
let addr = register(Box::new(props), tex, true, None);
unsafe { *out = tag::make(addr as *const PropertySet, tag::PROPERTY_SET) };
return Ok(());
}
// 输入 clip:Phase 2 仅支持整帧(fetch_image 的 phase-1 约束)。
if !region.is_null() {
return Err(status::FAILED);
}
let format = if format.is_null() {
None
} else {
unsafe { CStr::from_ptr(format) }.to_str().ok()
};
let image = c
.fetch_image(time, scale, None)
.map_err(|_| status::FAILED)?;
let components = image.components();
// 明确请求了不同分量 → Phase 2 不转换 → Failed(规范要求
// 满足请求格式;静默给错格式比显式失败更糟)。
if let Some(expected) = format_components(format) {
if expected != components {
return Err(status::FAILED);
}
}
let premult = clip_string(c, "OfxImageEffectPropPreMultiplication", PREMULT_NONE);
let (w, h) = (image_width(&image), image_height(&image));
if w <= 0.0 || h <= 0.0 {
return Err(status::FAILED);
}
// GL 模式:把输入图像上传成真实 GL 纹理(RGBA32F;上下文
// current——render 驱动已 acquire),OpenGLTextureIndex 返回
// 真实名;GL 上传失败 → 显式 Failed(插件按规范继续)。非 GL
// 上下文(本函数仅在 GL 渲染期可达,此分支是 CPU 纹理兜底):
// 仍建 CPU 纹理、索引 0。
let gl_tex = crate::gl_bridge::create_input_texture(
w as i32,
h as i32,
image.pixels(),
)
.ok();
let params = crate::render::VideoParams {
width: w as i32,
height: h as i32,
format: crate::render::PIXEL_FORMAT_F32,
..Default::default()
};
let tex = crate::render::texture_create(&params, image.pixels(), image.row_bytes() as i32)
.map_err(|_| status::ERR_MEMORY)?;
let props = make_texture_props(
w,
h,
components,
gl.gl_pixel_depth,
&premult,
clip_par(c),
scale,
image.row_bytes() as i32,
gl_tex.unwrap_or(0),
);
let addr = register(Box::new(props), tex, false, gl_tex);
unsafe { *out = tag::make(addr as *const PropertySet, tag::PROPERTY_SET) };
Ok(())
})
}
/// 纹理尺寸(经 [`crate::render::texture_get_params`];失败回退 0,0)。
fn texture_size(tex: &crate::render::Texture) -> (f64, f64) {
let p = crate::render::texture_get_params(tex);
if p.width > 0 {
(p.width as f64, p.height as f64)
} else {
(0.0, 0.0)
}
}
fn image_width(image: &Image) -> f64 {
(image.bounds().x2 - image.bounds().x1).round()
}
fn image_height(image: &Image) -> f64 {
(image.bounds().y2 - image.bounds().y1).round()
}
/// clip 的协商像素比。
fn clip_par(c: &ClipInstance) -> f64 {
c.props
.get("OfxImagePropPixelAspectRatio", 0)
.and_then(|v| match v {
Value::Double(d) => Some(d),
_ => None,
})
.unwrap_or(1.0)
}
/// clipFreeTexture:释放纹理(输入 clip 删除纹理值并释放真实 GL
/// 纹理;Output 只释放句柄不删纹理——宿主还要读它)。纹理是值:
/// 摘除表条目即 drop(原 `texture_free` 调用面随值模型删除)。
unsafe extern "C" fn clip_free_texture(texture_handle: *mut c_void) -> c_int {
caught(|| {
if texture_handle.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
let addr = tag::strip(texture_handle) as usize;
let entry = {
let mut live = LIVE_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
live.remove(&addr)
};
match entry {
Some((_props, _texture, _is_output, gl_tex)) => {
// 输入 clip 的真实 GL 纹理随释放删除(上下文 current)。
if let Some(gl) = gl_tex {
delete_gl_texture_if_gl(gl);
}
Ok(())
}
None => Err(status::ERR_BAD_HANDLE),
}
})
}
/// flushResources:宿主不缓存 GPU 资源 → REPLY_DEFAULT(规范语义
/// "nothing the host could do")。
unsafe extern "C" fn flush_resources() -> c_int {
status::REPLY_DEFAULT
}
/// 函数表布局(与 SDK `OfxImageEffectOpenGLRenderSuiteV1` 逐字段
/// 一致;ofxGPURender.h:181-310)。
#[repr(C)]
pub struct GlRenderSuiteV1 {
/// clipLoadTexture。
pub clip_load_texture: unsafe extern "C" fn(
*mut c_void,
c_double,
*const c_char,
*const c_void,
*mut *mut c_void,
) -> c_int,
/// clipFreeTexture。
pub clip_free_texture: unsafe extern "C" fn(*mut c_void) -> c_int,
/// flushResources。
pub flush_resources: unsafe extern "C" fn() -> c_int,
}
/// 函数表实例。
pub fn suite_v1() -> &'static GlRenderSuiteV1 {
static SUITE: std::sync::OnceLock<GlRenderSuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| GlRenderSuiteV1 {
clip_load_texture: clip_load_texture,
clip_free_texture: clip_free_texture,
flush_resources: flush_resources,
})
}
@@ -0,0 +1,630 @@
// 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/>.
//! OfxImageEffectSuite v1:clip/image 操作。
//!
//! 语义对照 HS: ofxhImageEffect.cpp:
//! - clipGetImage 返回图像 **属性集** handle(HS:2038 `getPropHandle`),
//! 图像存活由宿主表托管(get → 插入强引用,clipReleaseImage → 摘除
//! 释放;对应 HS 的引用计数配对,HS:2044);
//! - clipGetRegionOfDefinition:读 clip 实例属性里的
//! kOfxImageEffectPropRegionOfDefinition(协商时宿主写入);非法
//! RoD → kOfxStatFailed(HS:2143-2147);
//! - abort:实例期 → 当前渲染的进度取消状态(HS:2154-2170;
//! HS 默认返回 0,本实现按规范返回 REPLY_YES/REPLY_NO);
//! - imageMemory*:账本同 memory suite(HS 的 lock 是"锁住防重分配"
//! 语义,第 1 期账本不需要 → OK no-op,见 memory.rs 文档)。
//!
//! `// TODO(clip)`:clipGetImage 依赖 [`crate::clip::ClipInstance::fetch_image`]
//! (oakrender 帧访问随单库化改为本地桩,见 [`crate::render`]),代码已齐、运行时待 clip.rs。
use std::collections::HashMap;
use std::ffi::{c_char, c_double, c_int, c_void, CStr};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Mutex;
use crate::clip::ClipInstance;
use crate::descriptor::{ClipDescriptor, EffectDescriptor};
use crate::image::Image;
use crate::instance::{Instance, OfxRectD, RenderScale};
use crate::property::PropertySet;
use crate::suites::{status, tag};
/// 函数表布局(与 SDK `OfxImageEffectSuiteV1` 逐字段一致;常用子集
/// 注释,完整字段以 SDK 为准)。
#[repr(C)]
pub struct ImageEffectSuiteV1 {
/// getPropertySet:取 effect/clip/image 的属性集。
pub get_property_set: unsafe extern "C" fn(*mut c_void, *mut *mut c_void) -> c_int,
/// getParamSet:取实例参数集。
pub get_param_set: unsafe extern "C" fn(*mut c_void, *mut *mut c_void) -> c_int,
/// clipDefine(describe 期间):定义 clip。
pub clip_define: unsafe extern "C" fn(*mut c_void, *const c_char, *mut *mut c_void) -> c_int,
/// clipGetHandle:按名取 clip。
pub clip_get_handle: unsafe extern "C" fn(
*mut c_void,
*const c_char,
*mut *mut c_void,
*mut *mut c_void,
) -> c_int,
/// clipGetPropertySet
pub clip_get_property_set: unsafe extern "C" fn(*mut c_void, *mut *mut c_void) -> c_int,
/// clipGetImage:取图像(host 侧增加引用,必须与
/// clipReleaseImage 配对)。
pub clip_get_image:
unsafe extern "C" fn(*mut c_void, c_double, *const c_void, *mut *mut c_void) -> c_int,
/// clipReleaseImage
pub clip_release_image: unsafe extern "C" fn(*mut c_void) -> c_int,
/// clipGetRegionOfDefinition
pub clip_get_region_of_definition:
unsafe extern "C" fn(*mut c_void, c_double, *mut c_void) -> c_int,
/// abort:查询是否应中止(进度取消透传)。
pub abort: unsafe extern "C" fn(*mut c_void) -> c_int,
/// imageMemoryAlloc / imageMemoryFree / imageMemoryLock /
/// imageMemoryUnlock:图像内存管理(账本同 memory suite)。
pub image_memory_alloc: unsafe extern "C" fn(*mut c_void, c_int, *mut *mut c_void) -> c_int,
/// imageMemoryFree
pub image_memory_free: unsafe extern "C" fn(*mut c_void) -> c_int,
/// imageMemoryLock
pub image_memory_lock: unsafe extern "C" fn(*mut c_void, *mut *mut c_void) -> c_int,
/// imageMemoryUnlock
pub image_memory_unlock: unsafe extern "C" fn(*mut c_void) -> c_int,
}
/// 存活图像表:clipGetImage 产出(props 地址 → 强引用;唯一持有者,
/// clipReleaseImage 摘除即释放——对应 HS 的 get/release 配对)。
static LIVE_IMAGES: std::sync::LazyLock<Mutex<HashMap<usize, std::sync::Arc<Image>>>> =
std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
/// 公共入口模板:panic 兜底。
#[track_caller]
fn caught(f: impl FnOnce() -> Result<(), c_int>) -> c_int {
let caller = std::panic::Location::caller();
let code = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_or_else(
|_| status::FAILED,
|r| r.map_or_else(|c| c, |()| status::OK),
);
if code != status::OK && std::env::var_os("OAK_OFX_TRACE").is_some() {
eprintln!("[ofx] image-effect suite error {code} at {caller}");
}
code
}
/// 属性名(空指针/非 UTF-8 → ErrValue)。
unsafe fn c_name<'a>(name: *const c_char) -> Result<&'a str, c_int> {
if name.is_null() {
return Err(status::ERR_VALUE);
}
unsafe { CStr::from_ptr(name) }
.to_str()
.map_err(|_| status::ERR_VALUE)
}
/// effect 句柄解析(describe 期 → 描述符;实例期 → 实例)。
enum EffectRef<'a> {
Descriptor(&'a mut EffectDescriptor),
Instance(&'a Instance),
}
fn resolve_effect(handle: *mut c_void) -> Result<EffectRef<'static>, c_int> {
if handle.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
// 两者 props 均在偏移 0(句柄约定)。
unsafe {
match tag::kind(handle) {
tag::DESCRIPTOR => Ok(EffectRef::Descriptor(
&mut *(tag::strip(handle) as *mut EffectDescriptor),
)),
tag::INSTANCE => Ok(EffectRef::Instance(
&*(tag::strip(handle) as *const Instance),
)),
_ => Err(status::ERR_BAD_HANDLE),
}
}
}
/// clip 句柄解析(实例期;describe 期 ClipDescriptor 只在属性
/// suite 里用,不走这里)。
fn resolve_clip(handle: *mut c_void) -> Result<&'static ClipInstance, c_int> {
if handle.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
unsafe {
match tag::kind(handle) {
tag::CLIP => Ok(&*(tag::strip(handle) as *const ClipInstance)),
_ => Err(status::ERR_BAD_HANDLE),
}
}
}
/// getPropertySet:effect 属性集 = handle 本体(props 在偏移 0;
/// HS:1886-1898 返回 `getProps().getHandle()`,同址)。
unsafe extern "C" fn get_property_set(effect: *mut c_void, out: *mut *mut c_void) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
let _ = resolve_effect(effect)?;
unsafe { *out = effect };
Ok(())
})
}
/// getParamSet:param-set 即 effect 本体(HS:1901-1931 描述符/实例
/// 各自返回其 param set;本设计两者合一)。
unsafe extern "C" fn get_param_set(effect: *mut c_void, out: *mut *mut c_void) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
let _ = resolve_effect(effect)?;
unsafe { *out = effect };
Ok(())
})
}
/// clipDefine(describe 期):定义 clip 并返回其属性集 handle。
/// 重复名 → 整体替换(HS: `defineClip` 的 map 覆盖语义,
/// ofxhImageEffect.cpp:265-271;旧句柄随之失效,与 HS 一致)。
unsafe extern "C" fn clip_define(
effect: *mut c_void,
name: *const c_char,
out: *mut *mut c_void,
) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
unsafe { *out = std::ptr::null_mut() };
let n = unsafe { c_name(name)? };
let desc = match resolve_effect(effect)? {
EffectRef::Descriptor(d) => d,
EffectRef::Instance(_) => return Err(status::ERR_BAD_HANDLE),
};
let clip = ClipDescriptor::new(n);
// 重复定义:替换原 Box(HS map 覆盖语义)。
if let Some(existing) = desc.clips.iter_mut().find(|c| c.name == n) {
*existing = Box::new(clip);
} else {
desc.clips.push(Box::new(clip));
}
// 地址取自已入盒的对象(栈上临时变量在移动后失效)。
let clip = desc
.clips
.iter()
.find(|c| c.name == n)
.expect("just stored");
let addr = &clip.props as *const _ as usize;
unsafe { *out = tag::make(addr as *const PropertySet, tag::CLIP) };
Ok(())
})
}
/// clipGetHandle(实例期):按名取 clip 及其属性集。未找到 →
/// BadHandle(HS:2067-2070)。
unsafe extern "C" fn clip_get_handle(
effect: *mut c_void,
name: *const c_char,
clip: *mut *mut c_void,
property_set: *mut *mut c_void,
) -> c_int {
caught(|| {
if clip.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
unsafe { *clip = std::ptr::null_mut() };
let n = unsafe { c_name(name)? };
let handle = match resolve_effect(effect)? {
EffectRef::Instance(i) => {
let c = i
.clips
.iter()
.find(|c| c.name == n)
.ok_or(status::ERR_BAD_HANDLE)?;
let addr = &c.props as *const _ as usize;
tag::make(addr as *const PropertySet, tag::CLIP)
}
EffectRef::Descriptor(_) => return Err(status::ERR_BAD_HANDLE),
};
unsafe { *clip = handle };
if !property_set.is_null() {
// props 在偏移 0:clip handle 与 props handle 同值。
unsafe { *property_set = handle };
}
Ok(())
})
}
/// clipGetPropertySet:clip 属性集 = clip handle 本体。
unsafe extern "C" fn clip_get_property_set(clip: *mut c_void, out: *mut *mut c_void) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
let _ = resolve_clip(clip)?;
unsafe { *out = clip };
Ok(())
})
}
/// clipGetImage:抓取输入图像并登记到存活表,返回图像属性集 handle
/// (HS:2003-2049;`getImage` 失败 → Failed)。
///
/// `// TODO(clip)`:fetch_image 待 clip 迁移到
/// `oak_render::texture::Texture` 值模型(当前帧访问为本地桩)。
unsafe extern "C" fn clip_get_image(
clip: *mut c_void,
time: c_double,
region: *const c_void,
out: *mut *mut c_void,
) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
unsafe { *out = std::ptr::null_mut() };
let c = resolve_clip(clip)?;
// Output clip:返回当前渲染的输出图像(render 驱动经 TLS
// 设置;对应 HS 渲染期输出图像挂在 Output clip 上)。
if c.name == "Output" {
if let Some(image) = crate::suites::current_output() {
let addr = &image.props as *const _ as usize;
LIVE_IMAGES
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(addr, image);
unsafe { *out = tag::make(addr as *const PropertySet, tag::IMAGE) };
return Ok(());
}
return Err(status::FAILED);
}
// 区域(可空):像素坐标的可选 bounds。
let region = if region.is_null() {
None
} else {
Some(unsafe { *(region as *const OfxRectD) })
};
// 渲染比例取自当前渲染上下文(HS 的 clip 在 render 期从
// in_args 拿到 scale;本设计经 TLS,见 suites::RenderCtx)。
let scale = crate::suites::render_ctx()
.map(|ctx| ctx.scale)
.unwrap_or(RenderScale { x: 1.0, y: 1.0 });
let image = c
.fetch_image(time, scale, region)
.map_err(|_| status::FAILED)?;
let image = std::sync::Arc::new(image);
let addr = &image.props as *const _ as usize;
LIVE_IMAGES
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(addr, image);
unsafe { *out = tag::make(addr as *const PropertySet, tag::IMAGE) };
Ok(())
})
}
/// clipReleaseImage:摘除存活表强引用(图像随之释放;HS:2053-2068
/// 的 releaseReference 配对)。
unsafe extern "C" fn clip_release_image(image: *mut c_void) -> c_int {
caught(|| {
if image.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
if tag::kind(image) != tag::IMAGE {
return Err(status::ERR_BAD_HANDLE);
}
let addr = tag::strip(image) as usize;
let mut live = LIVE_IMAGES.lock().unwrap_or_else(|e| e.into_inner());
match live.remove(&addr) {
Some(_) => Ok(()),
None => Err(status::ERR_BAD_HANDLE),
}
})
}
/// clipGetRegionOfDefinition:读 clip 实例属性的协商 RoD;缺失/非法
/// → Failed(HS:2111-2150;非法判断 x2<x1 || y2<y1 → Failed)。
unsafe extern "C" fn clip_get_region_of_definition(
clip: *mut c_void,
_time: c_double,
bounds: *mut c_void,
) -> c_int {
caught(|| {
if bounds.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
let c = resolve_clip(clip)?;
let rod = read_rod(&c.props).ok_or(status::FAILED)?;
if rod.x2 < rod.x1 || rod.y2 < rod.y1 {
return Err(status::FAILED);
}
unsafe { *(bounds as *mut OfxRectD) = rod };
Ok(())
})
}
/// 从 clip 属性读协商 RoD(kOfxImageEffectPropRegionOfDefinition,
/// Double×4;协商时宿主写入)。
fn read_rod(props: &PropertySet) -> Option<OfxRectD> {
let v = props.get("OfxImageEffectPropRegionOfDefinition", 0)?;
let Value::Double(x1) = v else { return None };
let Value::Double(y1) = props.get("OfxImageEffectPropRegionOfDefinition", 1)? else {
return None;
};
let Value::Double(x2) = props.get("OfxImageEffectPropRegionOfDefinition", 2)? else {
return None;
};
let Value::Double(y2) = props.get("OfxImageEffectPropRegionOfDefinition", 3)? else {
return None;
};
Some(OfxRectD { x1, y1, x2, y2 })
}
/// abort:实例期 → 当前渲染进度是否已取消(HS:2154-2170 的
/// `instance->abort()`;HS 默认 0,本实现按规范返回 REPLY_YES/NO)。
/// 取消状态是成功应答而非错误码,不能走 caught 的 Err 通道。
unsafe extern "C" fn abort(effect: *mut c_void) -> c_int {
catch_unwind(AssertUnwindSafe(|| {
match resolve_effect(effect)? {
EffectRef::Instance(_) => {}
EffectRef::Descriptor(_) => return Err(status::ERR_BAD_HANDLE),
}
Ok(())
}))
.map_or_else(
|_| status::FAILED,
|r| match r {
Ok(()) => {
if crate::suites::progress::is_cancelled() {
status::REPLY_YES
} else {
status::REPLY_NO
}
}
Err(c) => c,
},
)
}
/// imageMemoryAlloc:账本同 memory suite(HS:2174-2212;失败 →
/// ErrMemory)。`handle` 忽略。
unsafe extern "C" fn image_memory_alloc(
_handle: *mut c_void,
byte_size: c_int,
out: *mut *mut c_void,
) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_VALUE);
}
match crate::suites::memory::alloc(byte_size as usize) {
Some(ptr) => {
unsafe { *out = ptr as *mut c_void };
Ok(())
}
None => Err(status::ERR_MEMORY),
}
})
}
/// imageMemoryFree:账本销账;未知指针 → BadHandle(SDK 契约)。
unsafe extern "C" fn image_memory_free(memory: *mut c_void) -> c_int {
caught(|| {
if crate::suites::memory::free(memory as *mut u8) {
Ok(())
} else {
Err(status::ERR_BAD_HANDLE)
}
})
}
/// imageMemoryLock/Unlock:HS 语义是"锁住防重分配"(ofxhMemory.cpp
/// lock/unlock 计数),第 1 期账本不建模 → OK no-op(文档见
/// memory.rs)。
unsafe extern "C" fn image_memory_lock(memory: *mut c_void, out: *mut *mut c_void) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_VALUE);
}
// 账本里的地址即数据指针(分配即就绪,无 HS 的延迟分配)。
unsafe { *out = memory };
Ok(())
})
}
unsafe extern "C" fn image_memory_unlock(_memory: *mut c_void) -> c_int {
caught(|| Ok(()))
}
use crate::property::Value;
/// 静态函数表实例。
pub fn suite_v1() -> &'static ImageEffectSuiteV1 {
static SUITE: std::sync::OnceLock<ImageEffectSuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| ImageEffectSuiteV1 {
get_property_set: get_property_set,
get_param_set: get_param_set,
clip_define: clip_define,
clip_get_handle: clip_get_handle,
clip_get_property_set: clip_get_property_set,
clip_get_image: clip_get_image,
clip_release_image: clip_release_image,
clip_get_region_of_definition: clip_get_region_of_definition,
abort: abort,
image_memory_alloc: image_memory_alloc,
image_memory_free: image_memory_free,
image_memory_lock: image_memory_lock,
image_memory_unlock: image_memory_unlock,
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CString;
use crate::descriptor::EffectDescriptor;
use crate::property::PropertySet;
fn cs(s: &str) -> CString {
CString::new(s).unwrap()
}
fn descriptor_handle(d: &EffectDescriptor) -> *mut c_void {
tag::make(&d.props as *const PropertySet, tag::DESCRIPTOR)
}
/// describe 期:clipDefine 建 clip、属性 suite 读写其属性、
/// 重复定义整体替换(HS map 覆盖)。
#[test]
fn describe_clip_define_and_props() {
let mut desc = EffectDescriptor::new();
let s = suite_v1();
let h = descriptor_handle(&desc);
let mut clip: *mut c_void = std::ptr::null_mut();
let name = cs("Source");
unsafe {
assert_eq!((s.clip_define)(h, name.as_ptr(), &mut clip), 0);
}
assert_eq!(tag::kind(clip), tag::CLIP);
// 属性 suite 直接读写 clip handle(props 在偏移 0)。
let ps = crate::suites::property::suite_v1();
let label_prop = cs(crate::param::PROP_LABEL);
let optional_prop = cs(crate::descriptor::CLIP_OPTIONAL);
let label = cs("SourceLabel");
unsafe {
assert_eq!(
(ps.set_string)(clip, label_prop.as_ptr(), 0, label.as_ptr()),
0
);
}
let mut out: *mut c_char = std::ptr::null_mut();
unsafe {
assert_eq!((ps.get_string)(clip, label_prop.as_ptr(), 0, &mut out), 0);
assert_eq!(CStr::from_ptr(out).to_bytes(), b"SourceLabel");
// 可选性标记:插件写 Optional=1。
assert_eq!((ps.set_int)(clip, optional_prop.as_ptr(), 0, 1), 0);
}
// getPropertySet / getParamSet:返回 effect 本体 handle。
let mut props: *mut c_void = std::ptr::null_mut();
unsafe {
assert_eq!((s.get_property_set)(h, &mut props), 0);
assert_eq!(props, h);
assert_eq!((s.get_param_set)(h, &mut props), 0);
assert_eq!(props, h);
}
// 重复 clipDefine:替换(旧句柄失效,HS 一致)。
let mut clip2: *mut c_void = std::ptr::null_mut();
unsafe {
assert_eq!((s.clip_define)(h, name.as_ptr(), &mut clip2), 0);
}
assert_ne!(clip, clip2);
assert_eq!(desc.clips.len(), 1);
// 空 out / 空 handle → BadHandle。
unsafe {
assert_eq!(
(s.clip_define)(h, name.as_ptr(), std::ptr::null_mut()),
status::ERR_BAD_HANDLE
);
assert_eq!(
(s.clip_define)(std::ptr::null_mut(), name.as_ptr(), &mut clip2),
status::ERR_BAD_HANDLE
);
}
}
/// abort:describe 期 → BadHandle;实例期 → REPLY_NO(未取消)。
#[test]
fn abort_requires_instance() {
let desc = EffectDescriptor::new();
let s = suite_v1();
let dh = descriptor_handle(&desc);
unsafe {
assert_eq!((s.abort)(dh), status::ERR_BAD_HANDLE);
assert_eq!((s.abort)(std::ptr::null_mut()), status::ERR_BAD_HANDLE);
}
// 实例期:未取消 → REPLY_NO。
let inst = std::sync::Arc::new(crate::instance::Instance {
props: PropertySet::new(),
plugin: std::sync::Arc::new(crate::host::Plugin {
identifier: "t".into(),
version: (1, 0),
bundle_path: std::path::PathBuf::new(),
contexts: vec![],
descriptor: EffectDescriptor::new(),
lib: std::ptr::null_mut(),
entry: dummy_entry,
ofx_plugin: std::ptr::null_mut(),
unloaded: std::sync::atomic::AtomicBool::new(false),
}),
context: "OfxImageEffectContextFilter".into(),
params: crate::param::ParamSetInstance { params: vec![] },
clips: vec![],
node_identity: std::sync::atomic::AtomicUsize::new(0),
destroyed: std::sync::atomic::AtomicBool::new(false),
sequence_range: std::sync::Mutex::new(None),
progress_cb: std::sync::Mutex::new(None),
cancel: std::sync::atomic::AtomicBool::new(false),
edit: std::sync::Mutex::new(crate::instance::EditTransaction::new()),
render_lock: std::sync::Mutex::new(()),
interact: std::sync::Mutex::new(None),
});
let ih = tag::make(&inst.props as *const PropertySet, tag::INSTANCE);
unsafe {
assert_eq!((s.abort)(ih), status::REPLY_NO);
}
}
unsafe extern "C" fn dummy_entry(
_: *const c_char,
_: *const c_void,
_: *mut c_void,
_: *mut c_void,
) -> c_int {
status::OK
}
/// imageMemoryAlloc/Free 走 memory 账本。
#[test]
fn image_memory_ledger() {
let s = suite_v1();
let mut mem: *mut c_void = std::ptr::null_mut();
unsafe {
assert_eq!(
(s.image_memory_alloc)(std::ptr::null_mut(), 1024, &mut mem),
0
);
assert!(!mem.is_null());
// lock 返回数据指针(第 1 期 = 句柄本身)。
let mut ptr: *mut c_void = std::ptr::null_mut();
assert_eq!((s.image_memory_lock)(mem, &mut ptr), 0);
assert_eq!(ptr, mem);
assert_eq!((s.image_memory_unlock)(mem), 0);
// 未知指针 free → BadHandle。
assert_eq!(
(s.image_memory_free)(0xdeadbeef as *mut c_void),
status::ERR_BAD_HANDLE
);
assert_eq!((s.image_memory_free)(mem), 0);
}
}
}
+819
View File
@@ -0,0 +1,819 @@
// 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/>.
//! OfxInteractSuiteV1 + [`Interact`] 宿主对象。
//!
//! Interact 是插件自定义 UI 的宿主侧对象(主进程 UI 事件宿主):与
//! worker 进程里的渲染实例并存(OFX 允许同一插件多实例),经
//! [`crate::instance::Instance::new_interact`] 创建、绑定到效果实例。
//!
//! ## 生命周期
//!
//! ```text
//! new_interact → kOfxActionNewInteract(创建;插件拒绝 → None)
//! describe → kOfxActionDescribe(kOfxActionDescribeInteract)
//! create_instance→ kOfxActionCreateInstance(kOfxActionCreateInstanceInteract)
//! draw/pen/key/idle → kOfxInteractAction*(宿主→插件)
//! destroy → kOfxActionDestroyInstance(kOfxActionDestroyInstanceInteract;
//! Instance 销毁时自动连带)
//! ```
//!
//! 所有 action 走 `Interact::call` → 插件入口(overlay interact V2/V1
//! 入口,未声明则插件 main entry;任务契约:new_interact 向插件入口
//! 发 kOfxActionNewInteract)。返回值(OfxStatus)如实透传。
//!
//! ## 语义(ofxInteract.h)
//!
//! - pen/key action 的返回:kOfxStatOK = 插件已处理该事件,宿主不应再
//! 把事件传给视图中其他交互对象;kOfxStatReplyDefault = 插件未处理,
//! 宿主可自行处置。
//! - pen 坐标:调用方给 viewport 像素;inArgs 另带 canonical 坐标
//! (kOfxInteractPropPenPosition,= viewport 像素 / pixelScale)与
//! pixelScale、pressure(两态笔按 ofxInteract.h 映射 0/1)。
//! - key:kOfxPropKeySym(ofxKeySyms.h 关键码)+ kOfxPropKeyString
//! (UTF-8;无 UTF8 编码的键为空串)。
//! - draw:宿主在调用前经 [`crate::gl_bridge::acquire`] 保持 GL current
//! 整个 action(插件发原生 GL 命令或经 Draw suite,ofxInteract.h
//! "the openGL context for this interact has been set");inArgs 带
//! viewport/pixelScale/time/backgroundImage/backgroundColour/
//! drawContext。
use std::ffi::{c_int, c_void, CString};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crate::host::{EntryPoint, Plugin};
use crate::property::{PropertySet, Value};
use crate::suites::{status, tag};
fn cs(s: &str) -> CString {
CString::new(s).unwrap()
}
/// Interact 实例。`Arc<Interact>` 管理生命周期(app 侧持句柄 +
/// [`crate::instance::Instance`] 的 interact 字段)。
///
/// `#[repr(C)]` + props 在偏移 0(句柄约定:interact handle =
/// `&props` | INTERACT 标签;property suite 剥标签后直读属性集)。
#[repr(C)]
pub struct Interact {
/// interact 实例级属性集(偏移 0,句柄约定)。
pub props: PropertySet,
/// 所属插件。
pub plugin: Arc<Plugin>,
/// interact 的入口(overlay interact V2/V1 入口,未声明则插件
/// main entry)。interact 的所有 action 都发到这里。
pub entry: EntryPoint,
/// 效果实例句柄(tagged INSTANCE;interact action inArgs 的
/// kOfxPropEffectInstance)。不透明令牌,不解引用。
pub effect_handle: *mut c_void,
/// 插件经 interactSwapBuffers 请求的缓冲交换(app 侧轮询后清零)。
pub swap_requested: AtomicBool,
/// 插件经 interactRedraw 请求的重绘(app 侧轮询后清零)。
pub redraw_requested: AtomicBool,
/// destroy 是否已通知(幂等门;Instance 销毁连带触发)。
pub destroyed: AtomicBool,
}
// SAFETY: effect_handle 是不透明令牌(同 [`crate::property::Value::Pointer`],
// 从不在此对象上解引用);entry 是函数指针,调用永远发生在宿主控制的
// action 分发点;其余字段(Arc/Mutex/AtomicBool/PropertySet)均线程安全。
// Interact 经 Instance.interact 字段跨线程可达,因此 Send/Sync 成立。
unsafe impl Send for Interact {}
unsafe impl Sync for Interact {}
impl Interact {
/// 构造(宿主内部;[`crate::instance::Instance::new_interact`] 调)。
/// `effect_handle` 为 tagged INSTANCE 句柄(不透明令牌)。
pub(crate) fn new(
plugin: Arc<Plugin>,
entry: EntryPoint,
effect_handle: *mut c_void,
) -> Arc<Interact> {
let i = Arc::new(Interact {
props: PropertySet::new(),
plugin,
entry,
effect_handle,
swap_requested: AtomicBool::new(false),
redraw_requested: AtomicBool::new(false),
destroyed: AtomicBool::new(false),
});
init_interact_props(&i.props);
i
}
/// interact handle(tagged INTERACT)。
pub(crate) fn handle(&self) -> *mut c_void {
tag::make(&self.props as *const PropertySet, tag::INTERACT)
}
/// 向插件入口发一个 interact action。
///
/// # Safety
/// handle 与 action 匹配(Interact 生命周期由宿主控制;destroy 后
/// 不再调用)。
pub(crate) fn call(&self, action: &str, in_args: &PropertySet, out_args: &PropertySet) -> i32 {
unsafe {
self.plugin.call_entry(self.entry, action, self.handle(), in_args, out_args)
}
}
/// 取 effect 实例句柄(inArgs 的 kOfxPropEffectInstance)。
fn effect_instance_prop(&self) -> Value {
Value::Pointer(self.effect_handle)
}
/// 当前 pixelScale(interact props,默认 1,1)。
fn pixel_scale(&self) -> (f64, f64) {
read_double2(&self.props, crate::host::PROP_INTERACT_PIXEL_SCALE)
.unwrap_or((1.0, 1.0))
}
/// describe(kOfxActionDescribe == kOfxActionDescribeInteract,
/// ofxInteract.h:171)。inArgs/outArgs 冗余为 NULL。
pub fn describe(&self) -> i32 {
let empty = PropertySet::new();
self.call(crate::host::ACTION_DESCRIBE, &empty, &empty)
}
/// createInstance(kOfxActionCreateInstance ==
/// kOfxActionCreateInstanceInteract,ofxInteract.h:198)。
/// draw/pen/key 的前置(ofxInteract.h 各 action 的 \pre)。
pub fn create_instance(&self) -> i32 {
let empty = PropertySet::new();
self.call(crate::host::ACTION_CREATE_INSTANCE, &empty, &empty)
}
/// draw action(ofxInteract.h:265)。宿主在调用前
/// [`crate::gl_bridge::acquire`] 保持 GL current 整个 action;inArgs
/// 带 kOfxInteractPropPixelScale/ViewportSize/BackgroundColour/
/// BackgroundImage/Time/RenderScale/DrawContext + kOfxPropEffectInstance。
///
/// `background_image`:宿主持有的背景图像句柄(本宿主 Phase 1 无
/// 合成背景,传 None 即空——任务契约"可空")。
///
/// 返回值:插件的 OfxStatus 如实透传;GL 上下文不可用(非 macOS /
/// 无上下文)时返回 kOfxStatErrMissingHostFeature(宿主侧失败,未
/// 触达插件)。
pub fn draw(
&self,
viewport_size: (f64, f64),
pixel_scale: (f64, f64),
time: f64,
background_image: Option<*mut c_void>,
) -> i32 {
// 1. GL current 整个 draw action(插件发原生 GL 命令或经 Draw
// suite;失败即无法绘制 → 不触达插件)。
let _guard = match crate::gl_bridge::acquire() {
Ok(g) => g,
Err(_) => return status::ERR_MISSING_HOST_FEATURE,
};
// 2. Draw suite 上下文(存活注册;draw 返回后摘除)。
let draw_ctx = crate::suites::draw::make_context(viewport_size, pixel_scale);
let in_args = PropertySet::new();
in_args.define(
crate::host::PROP_INTERACT_PIXEL_SCALE,
vec![Value::Double(pixel_scale.0), Value::Double(pixel_scale.1)],
);
in_args.define(
crate::host::PROP_INTERACT_VIEWPORT_SIZE,
vec![Value::Double(viewport_size.0), Value::Double(viewport_size.1)],
);
in_args.set_one(
crate::host::PROP_INTERACT_BACKGROUND_IMAGE,
Value::Pointer(background_image.unwrap_or(std::ptr::null_mut())),
);
in_args.define(
crate::host::PROP_INTERACT_BACKGROUND_COLOUR,
vec![Value::Double(0.0), Value::Double(0.0), Value::Double(0.0)],
);
in_args.set_one(crate::host::PROP_TIME, Value::Double(time));
in_args.define(
crate::host::PROP_RENDER_SCALE,
vec![Value::Double(1.0), Value::Double(1.0)],
);
in_args.set_one(crate::host::PROP_INTERACT_DRAW_CONTEXT, Value::Pointer(draw_ctx));
in_args.set_one(crate::host::PROP_EFFECT_INSTANCE, self.effect_instance_prop());
// 3. interact 实例属性同步(kOfxInteractPropPixelScale 等是实例
// 属性集上只读的"当前状态",ofxInteract.h:58)。
self.props.define(
crate::host::PROP_INTERACT_PIXEL_SCALE,
vec![Value::Double(pixel_scale.0), Value::Double(pixel_scale.1)],
);
self.props.define(
crate::host::PROP_INTERACT_VIEWPORT_SIZE,
vec![Value::Double(viewport_size.0), Value::Double(viewport_size.1)],
);
self.props.set_one(
crate::host::PROP_INTERACT_BACKGROUND_IMAGE,
Value::Pointer(background_image.unwrap_or(std::ptr::null_mut())),
);
let out = PropertySet::new();
let st = self.call(crate::host::ACTION_INTERACT_DRAW, &in_args, &out);
crate::suites::draw::drop_context(draw_ctx);
st
}
/// 装配 pen 类 action 的 inArgs(PenMotion/PenDown/PenUp 共用,
/// ofxInteract.h:274-321)。
fn pen_in_args(&self, pen_viewport: (f64, f64), pressure: f64, time: f64) -> PropertySet {
let (ps_x, ps_y) = self.pixel_scale();
// canonical = viewport 像素 / pixelScale(pixelScale 是
// canonical→屏幕像素的换算比例)。
let in_args = PropertySet::new();
in_args.set_one(crate::host::PROP_EFFECT_INSTANCE, self.effect_instance_prop());
in_args.define(
crate::host::PROP_INTERACT_PIXEL_SCALE,
vec![Value::Double(ps_x), Value::Double(ps_y)],
);
in_args.define(
crate::host::PROP_INTERACT_BACKGROUND_COLOUR,
vec![Value::Double(0.0), Value::Double(0.0), Value::Double(0.0)],
);
in_args.set_one(crate::host::PROP_TIME, Value::Double(time));
in_args.define(
crate::host::PROP_RENDER_SCALE,
vec![Value::Double(1.0), Value::Double(1.0)],
);
in_args.define(
crate::host::PROP_INTERACT_PEN_POSITION,
vec![
Value::Double(pen_viewport.0 / ps_x.max(1e-9)),
Value::Double(pen_viewport.1 / ps_y.max(1e-9)),
],
);
in_args.define(
crate::host::PROP_INTERACT_PEN_VIEWPORT_POSITION,
vec![
Value::Int(pen_viewport.0.round() as i32),
Value::Int(pen_viewport.1.round() as i32),
],
);
in_args.set_one(crate::host::PROP_INTERACT_PEN_PRESSURE, Value::Double(pressure));
in_args
}
/// pen_motion(ofxInteract.h:302)。`pen_viewport` 为视口像素坐标;
/// `pen_down` 表示笔是否按下(两态笔按 ofxInteract.h:114 映射压力
/// 1.0/0.0)。
pub fn pen_motion(&self, pen_viewport: (f64, f64), pen_down: bool, time: f64) -> i32 {
let pressure = if pen_down { 1.0 } else { 0.0 };
let in_args = self.pen_in_args(pen_viewport, pressure, time);
let out = PropertySet::new();
self.call(crate::host::ACTION_INTERACT_PEN_MOTION, &in_args, &out)
}
/// pen_down(ofxInteract.h:340)。压力 1.0。
pub fn pen_down(&self, pen_viewport: (f64, f64), time: f64) -> i32 {
let in_args = self.pen_in_args(pen_viewport, 1.0, time);
let out = PropertySet::new();
self.call(crate::host::ACTION_INTERACT_PEN_DOWN, &in_args, &out)
}
/// pen_up(ofxInteract.h:376)。压力 0.0。
pub fn pen_up(&self, pen_viewport: (f64, f64), time: f64) -> i32 {
let in_args = self.pen_in_args(pen_viewport, 0.0, time);
let out = PropertySet::new();
self.call(crate::host::ACTION_INTERACT_PEN_UP, &in_args, &out)
}
/// 装配 key 类 action 的 inArgs(KeyDown/KeyUp 共用,
/// ofxInteract.h:384-442)。
fn key_in_args(&self, key_sym: i32, key_string: &str, time: f64) -> PropertySet {
let in_args = PropertySet::new();
in_args.set_one(crate::host::PROP_EFFECT_INSTANCE, self.effect_instance_prop());
in_args.set_one(crate::host::PROP_KEY_SYM, Value::Int(key_sym));
in_args.set_one(crate::host::PROP_KEY_STRING, Value::String(cs(key_string)));
in_args.set_one(crate::host::PROP_TIME, Value::Double(time));
in_args.define(
crate::host::PROP_RENDER_SCALE,
vec![Value::Double(1.0), Value::Double(1.0)],
);
in_args
}
/// key_down(ofxInteract.h:410)。`key_sym` 为 ofxKeySyms.h 关键码;
/// `key_string` 为 UTF-8 字符(无 UTF8 编码的键为空串)。
pub fn key_down(&self, key_sym: i32, key_string: &str, time: f64) -> i32 {
let in_args = self.key_in_args(key_sym, key_string, time);
let out = PropertySet::new();
self.call(crate::host::ACTION_INTERACT_KEY_DOWN, &in_args, &out)
}
/// key_up(ofxInteract.h:443)。
pub fn key_up(&self, key_sym: i32, key_string: &str, time: f64) -> i32 {
let in_args = self.key_in_args(key_sym, key_string, time);
let out = PropertySet::new();
self.call(crate::host::ACTION_INTERACT_KEY_UP, &in_args, &out)
}
/// idle(宿主空闲泵;任务契约的 kOfxInteractActionIdle,属本宿主
/// 扩展)。插件未实现时返回 kOfxStatReplyDefault。
pub fn idle(&self) -> i32 {
let empty = PropertySet::new();
self.call(crate::host::ACTION_INTERACT_IDLE, &empty, &empty)
}
/// gain_focus(ofxInteract.h:501):pen/key 事件的前置
/// (ofxInteract.h 各 action 的 \pre 要求 interact 已获焦点)。
pub fn gain_focus(&self, time: f64) -> i32 {
let in_args = self.pen_in_args((0.0, 0.0), 0.0, time);
let out = PropertySet::new();
self.call(crate::host::ACTION_INTERACT_GAIN_FOCUS, &in_args, &out)
}
/// lose_focus(ofxInteract.h:526)。
pub fn lose_focus(&self, time: f64) -> i32 {
let in_args = self.pen_in_args((0.0, 0.0), 0.0, time);
let out = PropertySet::new();
self.call(crate::host::ACTION_INTERACT_LOSE_FOCUS, &in_args, &out)
}
/// destroy(kOfxActionDestroyInstance == kOfxActionDestroyInstanceInteract,
/// ofxInteract.h:227)。幂等:只通知一次。返回状态忽略(析构不可
/// 回滚,ofxInteract.h "what is returned is moot")。
pub fn destroy(&self) {
if self
.destroyed
.swap(true, Ordering::Relaxed)
{
return;
}
let empty = PropertySet::new();
self.call(crate::host::ACTION_DESTROY_INSTANCE, &empty, &empty);
}
}
/// interact 实例属性表(ofxInteract.h 的 PropertiesInteract 子集)。
fn init_interact_props(props: &PropertySet) {
props.define(
crate::host::PROP_INTERACT_PIXEL_SCALE,
vec![Value::Double(1.0), Value::Double(1.0)],
);
props.define(
crate::host::PROP_INTERACT_VIEWPORT_SIZE,
vec![Value::Double(0.0), Value::Double(0.0)],
);
props.set_one(
crate::host::PROP_INTERACT_BACKGROUND_IMAGE,
Value::Pointer(std::ptr::null_mut()),
);
props.define(
crate::host::PROP_INTERACT_SUGGESTED_COLOUR,
vec![Value::Double(1.0), Value::Double(1.0), Value::Double(1.0)],
);
props.define(crate::host::PROP_INTERACT_SLAVE_TO_PARAM, vec![]);
props.define(
crate::host::PROP_INTERACT_BACKGROUND_COLOUR,
vec![Value::Double(0.0), Value::Double(0.0), Value::Double(0.0)],
);
// 帧缓冲位深:离屏 FBO 是 RGBA32F → 每分量 32 bit,含 alpha。
props.set_one(crate::host::PROP_INTERACT_BIT_DEPTH, Value::Int(32));
props.set_one(crate::host::PROP_INTERACT_HAS_ALPHA, Value::Int(1));
}
/// 从属性集读 Double×2(缺失/类型不符 → None)。
fn read_double2(props: &PropertySet, name: &str) -> Option<(f64, f64)> {
let x = match props.get(name, 0)? {
Value::Double(d) => d,
_ => return None,
};
let y = match props.get(name, 1)? {
Value::Double(d) => d,
_ => return None,
};
Some((x, y))
}
// ---- OfxInteractSuiteV1(ofxInteract.h:534-544)------------------------
/// interact 句柄解析(tag INTERACT)。
fn resolve_interact(handle: *mut c_void) -> Result<&'static Interact, c_int> {
if handle.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
unsafe {
if tag::kind(handle) != tag::INTERACT {
return Err(status::ERR_BAD_HANDLE);
}
// Interact 的 props 在偏移 0:剥标签后的地址即 &Interact。
Ok(&*(tag::strip(handle) as *const Interact))
}
}
/// 公共入口模板:panic 兜底。
fn caught(f: impl FnOnce() -> Result<(), c_int>) -> c_int {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_or_else(
|_| status::FAILED,
|r| r.map_or_else(|c| c, |()| status::OK),
)
}
/// interactSwapBuffers:插件请求宿主交换 GL 缓冲(宿主 UI 视图中)。
/// 本宿主无 UI 视图,把请求记入 `swap_requested`(app 侧轮询后清零)并
/// 返回 OK——宿主服务真实生效(请求被记录、可被 UI 消费)。
unsafe extern "C" fn interact_swap_buffers(handle: *mut c_void) -> c_int {
caught(|| {
let i = resolve_interact(handle)?;
i.swap_requested.store(true, Ordering::Relaxed);
Ok(())
})
}
/// interactRedraw:插件请求宿主重绘 interact 视图。同上记入
/// `redraw_requested`(app 侧轮询)。
unsafe extern "C" fn interact_redraw(handle: *mut c_void) -> c_int {
caught(|| {
let i = resolve_interact(handle)?;
i.redraw_requested.store(true, Ordering::Relaxed);
Ok(())
})
}
/// interactGetPropertySet:返回 interact 的属性集句柄(tagged INTERACT)。
unsafe extern "C" fn interact_get_property_set(
handle: *mut c_void,
property: *mut *mut c_void,
) -> c_int {
caught(|| {
if property.is_null() {
return Err(status::ERR_VALUE);
}
let i = resolve_interact(handle)?;
unsafe { *property = tag::make(&i.props as *const PropertySet, tag::INTERACT) };
Ok(())
})
}
/// 函数表布局(与 SDK `OfxInteractSuiteV1` 逐字段一致;ofxInteract.h:534)。
#[repr(C)]
pub struct InteractSuiteV1 {
/// interactSwapBuffers。
pub interact_swap_buffers: unsafe extern "C" fn(*mut c_void) -> c_int,
/// interactRedraw。
pub interact_redraw: unsafe extern "C" fn(*mut c_void) -> c_int,
/// interactGetPropertySet。
pub interact_get_property_set: unsafe extern "C" fn(*mut c_void, *mut *mut c_void) -> c_int,
}
/// 函数表实例。
pub fn suite_v1() -> &'static InteractSuiteV1 {
static SUITE: std::sync::OnceLock<InteractSuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| InteractSuiteV1 {
interact_swap_buffers,
interact_redraw,
interact_get_property_set,
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::{c_char, CStr};
use std::sync::Mutex;
fn cs(s: &str) -> CString {
CString::new(s).unwrap()
}
/// interact 属性表:PixelScale/ViewportSize/SuggestedColour/
/// SlaveToParam/BitDepth/HasAlpha 等按头文件预置,经 property suite
/// 可读写。
#[test]
fn interact_props_initialized() {
let props = PropertySet::new();
init_interact_props(&props);
// Value 无 PartialEq(指针/CString 成员),用 matches! 断言。
assert!(
matches!(
props.get(crate::host::PROP_INTERACT_PIXEL_SCALE, 0),
Some(Value::Double(1.0))
),
"PixelScale[0] 应为 1.0"
);
assert_eq!(props.dimension(crate::host::PROP_INTERACT_PIXEL_SCALE), 2);
assert!(
matches!(
props.get(crate::host::PROP_INTERACT_SUGGESTED_COLOUR, 2),
Some(Value::Double(1.0))
),
"SuggestedColour[2] 应为 1.0"
);
assert_eq!(props.dimension(crate::host::PROP_INTERACT_SLAVE_TO_PARAM), 0);
assert!(
matches!(
props.get(crate::host::PROP_INTERACT_BIT_DEPTH, 0),
Some(Value::Int(32))
),
"BitDepth 应为 32"
);
assert!(
matches!(
props.get(crate::host::PROP_INTERACT_HAS_ALPHA, 0),
Some(Value::Int(1))
),
"HasAlpha 应为 1"
);
}
/// read_double2 帮助函数。
#[test]
fn read_double2_helper() {
let props = PropertySet::new();
props.define("P", vec![Value::Double(2.0), Value::Double(3.0)]);
assert_eq!(read_double2(&props, "P"), Some((2.0, 3.0)));
assert_eq!(read_double2(&props, "Q"), None);
}
/// 空指针/错标签 → ErrBadHandle(interact suite 的句柄校验)。
#[test]
fn interact_suite_handle_validation() {
unsafe {
assert_eq!(interact_swap_buffers(std::ptr::null_mut()), status::ERR_BAD_HANDLE);
assert_eq!(interact_redraw(std::ptr::null_mut()), status::ERR_BAD_HANDLE);
let mut out: *mut c_void = std::ptr::null_mut();
assert_eq!(
interact_get_property_set(std::ptr::null_mut(), &mut out),
status::ERR_BAD_HANDLE
);
// 错标签:裸 PropertySet(标签 0)当 interact 用。
let props = PropertySet::new();
let raw = &props as *const PropertySet as *mut c_void;
assert_eq!(interact_swap_buffers(raw), status::ERR_BAD_HANDLE);
}
}
/// interact suite 服务端:swap/redraw 请求被记录(app 侧轮询面),
/// getPropertySet 返回 interact 属性集句柄。
#[test]
fn interact_suite_requests_are_recorded() {
// 用假插件构造 Interact(不进插件入口——只测 suite 服务端)。
let plugin = crate::host::Plugin {
identifier: "fake".into(),
version: (1, 0),
bundle_path: std::path::PathBuf::from("fake"),
contexts: Vec::new(),
descriptor: crate::descriptor::EffectDescriptor::new(),
lib: std::ptr::null_mut(),
entry: dummy_entry,
ofx_plugin: std::ptr::null_mut(),
unloaded: std::sync::atomic::AtomicBool::new(false),
};
let interact = Interact::new(Arc::new(plugin), dummy_entry, std::ptr::null_mut());
let handle = interact.handle();
unsafe {
assert_eq!(interact_swap_buffers(handle), status::OK);
assert_eq!(interact_redraw(handle), status::OK);
}
assert!(interact.swap_requested.load(Ordering::Relaxed));
assert!(interact.redraw_requested.load(Ordering::Relaxed));
let mut props_handle: *mut c_void = std::ptr::null_mut();
unsafe {
assert_eq!(interact_get_property_set(handle, &mut props_handle), status::OK);
}
assert_eq!(tag::kind(props_handle), tag::INTERACT);
assert_eq!(
tag::strip(props_handle) as usize,
&interact.props as *const PropertySet as usize
);
// property suite 可直读 interact 属性集(句柄约定打通)。
let addr = tag::strip(props_handle);
let set: &PropertySet = unsafe { &*addr };
assert!(
matches!(
set.get(crate::host::PROP_INTERACT_BIT_DEPTH, 0),
Some(Value::Int(32))
),
"经 interact 句柄的 property suite 应读到 BitDepth=32"
);
// 摘除引用计数:Arc 释放(interact 已无引用)。
drop(interact);
}
/// 假入口:所有 action 返回 ReplyDefault(不触达真实插件)。
unsafe extern "C" fn dummy_entry(
_action: *const c_char,
_handle: *const c_void,
_in: *mut c_void,
_out: *mut c_void,
) -> c_int {
status::REPLY_DEFAULT
}
/// call 面透传:entry 收到 action 与 tagged handle(假插件记录)。
#[test]
fn interact_call_dispatches_to_entry() {
static CALLED_ACTION: Mutex<Vec<String>> = Mutex::new(Vec::new());
unsafe extern "C" fn recording_entry(
action: *const c_char,
handle: *const c_void,
_in: *mut c_void,
_out: *mut c_void,
) -> c_int {
CALLED_ACTION
.lock()
.unwrap()
.push(unsafe { CStr::from_ptr(action) }.to_string_lossy().into_owned());
// handle 必须是 tagged INTERACT。
assert_eq!(tag::kind(handle as *mut c_void), tag::INTERACT);
status::OK
}
let plugin = crate::host::Plugin {
identifier: "fake".into(),
version: (1, 0),
bundle_path: std::path::PathBuf::from("fake"),
contexts: Vec::new(),
descriptor: crate::descriptor::EffectDescriptor::new(),
lib: std::ptr::null_mut(),
entry: recording_entry,
ofx_plugin: std::ptr::null_mut(),
unloaded: std::sync::atomic::AtomicBool::new(false),
};
let interact = Interact::new(Arc::new(plugin), recording_entry, std::ptr::null_mut());
assert_eq!(interact.describe(), status::OK);
assert_eq!(interact.create_instance(), status::OK);
assert_eq!(interact.pen_motion((10.0, 20.0), true, 5.0), status::OK);
assert_eq!(interact.pen_down((10.0, 20.0), 5.0), status::OK);
assert_eq!(interact.pen_up((10.0, 20.0), 5.0), status::OK);
assert_eq!(interact.key_down(crate::host::KEY_A, "a", 5.0), status::OK);
assert_eq!(interact.key_up(crate::host::KEY_A, "a", 5.0), status::OK);
assert_eq!(interact.idle(), status::OK);
interact.destroy();
let calls = CALLED_ACTION.lock().unwrap().clone();
let want = [
crate::host::ACTION_DESCRIBE,
crate::host::ACTION_CREATE_INSTANCE,
crate::host::ACTION_INTERACT_PEN_MOTION,
crate::host::ACTION_INTERACT_PEN_DOWN,
crate::host::ACTION_INTERACT_PEN_UP,
crate::host::ACTION_INTERACT_KEY_DOWN,
crate::host::ACTION_INTERACT_KEY_UP,
crate::host::ACTION_INTERACT_IDLE,
crate::host::ACTION_DESTROY_INSTANCE,
];
assert_eq!(calls, want, "interact action 序列应按序透传到入口");
}
/// pen 事件的真实参数:inArgs 的 canonical 位置/视口位置/压力按
/// pixelScale 换算(假插件读取记录)。
#[test]
fn pen_in_args_canonical_conversion() {
// 记录 pen_motion 的 inArgs 关键属性。
static CAPTURED: Mutex<Option<(f64, f64, f64)>> = Mutex::new(None);
unsafe extern "C" fn capture_entry(
_action: *const c_char,
_handle: *const c_void,
in_args: *mut c_void,
_out: *mut c_void,
) -> c_int {
if in_args.is_null() {
return status::OK;
}
let set = unsafe { &*(in_args as *const PropertySet) };
// 视口位置(Int×2)与 canonical 位置(Double×2)与压力。
let vx = match set.get(crate::host::PROP_INTERACT_PEN_VIEWPORT_POSITION, 0) {
Some(Value::Int(i)) => i,
_ => 0,
};
let px = match set.get(crate::host::PROP_INTERACT_PEN_POSITION, 0) {
Some(Value::Double(d)) => d,
_ => 0.0,
};
let pressure = match set.get(crate::host::PROP_INTERACT_PEN_PRESSURE, 0) {
Some(Value::Double(d)) => d,
_ => 0.0,
};
*CAPTURED.lock().unwrap() = Some((vx as f64, px, pressure));
status::OK
}
let plugin = crate::host::Plugin {
identifier: "fake".into(),
version: (1, 0),
bundle_path: std::path::PathBuf::from("fake"),
contexts: Vec::new(),
descriptor: crate::descriptor::EffectDescriptor::new(),
lib: std::ptr::null_mut(),
entry: capture_entry,
ofx_plugin: std::ptr::null_mut(),
unloaded: std::sync::atomic::AtomicBool::new(false),
};
let interact = Interact::new(Arc::new(plugin), capture_entry, std::ptr::null_mut());
// 设 pixelScale=2 → canonical = viewport/2。
interact.props.define(
crate::host::PROP_INTERACT_PIXEL_SCALE,
vec![Value::Double(2.0), Value::Double(2.0)],
);
assert_eq!(interact.pen_motion((10.0, 20.0), true, 0.0), status::OK);
let (vx, px, pressure) = CAPTURED.lock().unwrap().take().unwrap();
assert_eq!(vx, 10.0);
assert_eq!(px, 5.0);
assert_eq!(pressure, 1.0);
// pen_up 压力 0。
assert_eq!(interact.pen_up((10.0, 20.0), 0.0), status::OK);
let (_, _, pressure) = CAPTURED.lock().unwrap().take().unwrap();
assert_eq!(pressure, 0.0);
}
/// key 事件真实参数:keySym/keyString 进 inArgs。
#[test]
fn key_in_args_carry_sym_and_string() {
static CAPTURED: Mutex<Option<(i32, String)>> = Mutex::new(None);
unsafe extern "C" fn capture_entry(
_action: *const c_char,
_handle: *const c_void,
in_args: *mut c_void,
_out: *mut c_void,
) -> c_int {
let set = unsafe { &*(in_args as *const PropertySet) };
let sym = match set.get(crate::host::PROP_KEY_SYM, 0) {
Some(Value::Int(i)) => i,
_ => 0,
};
let s = match set.get(crate::host::PROP_KEY_STRING, 0) {
Some(Value::String(c)) => c.to_string_lossy().into_owned(),
_ => String::new(),
};
*CAPTURED.lock().unwrap() = Some((sym, s));
status::OK
}
let plugin = crate::host::Plugin {
identifier: "fake".into(),
version: (1, 0),
bundle_path: std::path::PathBuf::from("fake"),
contexts: Vec::new(),
descriptor: crate::descriptor::EffectDescriptor::new(),
lib: std::ptr::null_mut(),
entry: capture_entry,
ofx_plugin: std::ptr::null_mut(),
unloaded: std::sync::atomic::AtomicBool::new(false),
};
let interact = Interact::new(Arc::new(plugin), capture_entry, std::ptr::null_mut());
assert_eq!(interact.key_down(crate::host::KEY_RETURN, "", 1.0), status::OK);
let (sym, s) = CAPTURED.lock().unwrap().take().unwrap();
assert_eq!(sym, crate::host::KEY_RETURN);
assert_eq!(s, "");
assert_eq!(interact.key_up(crate::host::KEY_A, "a", 1.0), status::OK);
let (sym, s) = CAPTURED.lock().unwrap().take().unwrap();
assert_eq!(sym, crate::host::KEY_A);
assert_eq!(s, "a");
}
/// destroy 幂等:只发一次。
#[test]
fn destroy_is_idempotent() {
static COUNT: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
unsafe extern "C" fn counting_entry(
action: *const c_char,
_handle: *const c_void,
_in: *mut c_void,
_out: *mut c_void,
) -> c_int {
let a = unsafe { CStr::from_ptr(action) }.to_string_lossy();
if a == crate::host::ACTION_DESTROY_INSTANCE {
COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
status::OK
}
let plugin = crate::host::Plugin {
identifier: "fake".into(),
version: (1, 0),
bundle_path: std::path::PathBuf::from("fake"),
contexts: Vec::new(),
descriptor: crate::descriptor::EffectDescriptor::new(),
lib: std::ptr::null_mut(),
entry: counting_entry,
ofx_plugin: std::ptr::null_mut(),
unloaded: std::sync::atomic::AtomicBool::new(false),
};
let interact = Interact::new(Arc::new(plugin), counting_entry, std::ptr::null_mut());
interact.destroy();
interact.destroy();
assert_eq!(COUNT.load(std::sync::atomic::Ordering::Relaxed), 1);
}
}
+152
View File
@@ -0,0 +1,152 @@
// 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/>.
//! OfxMemorySuite v1:宿主代分配内存。
//!
//! 语义参照 HS: ofxhHost.cpp:26-42(裸 malloc/free 语义:失败 →
//! kOfxStatErrMemory,free 恒 OK)——但本 crate 按骨架声明增加
//! **宿主级账本**:分配记录进账本,destroyInstance 时兜底回收
//! (泄漏防线;插件正常应自行 free)。未知指针 free →
//! kOfxStatErrBadHandle(SDK ofxMemory.h:51 的契约)。
//! image_effect suite 的 imageMemory* 与此共用账本。
use std::alloc::Layout;
use std::sync::Mutex;
use crate::suites::status;
/// 对齐:malloc 保证 max_align_t(本平台 16 字节);插件会把缓冲当
/// float*/SIMD 用,16 字节是安全下限。
const ALIGN: usize = 16;
/// 一个已分配块:地址 + 布局(回收时按记录布局 dealloc)。
/// 地址以 `usize` 存(不透明令牌,避免裸指针破坏 `static` 的
/// Send/Sync 推导;账本只做 alloc/dealloc 配对,从不解引用)。
struct Block {
ptr: usize,
layout: Layout,
}
/// 宿主级账本(进程单例;memory suite 无宿主指针参数,全局即可)。
static LEDGER: Mutex<Vec<Block>> = Mutex::new(Vec::new());
/// 取锁(毒锁接管:一次持锁 panic 不级联)。
fn lock() -> std::sync::MutexGuard<'static, Vec<Block>> {
LEDGER.lock().unwrap_or_else(|e| e.into_inner())
}
/// 分配并记账。返回裸指针;失败(OOM/布局非法)返回 `None`。
pub(crate) fn alloc(size: usize) -> Option<*mut u8> {
// 零尺寸分配:Layout 要求非零,取 1 字节兜底(free 按同布局回收)。
let layout = Layout::from_size_align(size.max(1), ALIGN).ok()?;
let ptr = unsafe { std::alloc::alloc(layout) };
if ptr.is_null() {
return None;
}
lock().push(Block {
ptr: ptr as usize,
layout,
});
Some(ptr)
}
/// 按指针释放并销账。未知指针返回 `false`(suite 层映射
/// kOfxStatErrBadHandle);`NULL` 按 C 语义 no-op 返回 `true`。
pub(crate) fn free(ptr: *mut u8) -> bool {
if ptr.is_null() {
return true;
}
let mut ledger = lock();
let pos = ledger.iter().position(|b| b.ptr == ptr as usize);
match pos {
Some(i) => {
let b = ledger.remove(i);
unsafe { std::alloc::dealloc(b.ptr as *mut u8, b.layout) };
true
}
None => false,
}
}
/// 兜底回收全部在账块(destroyInstance 的泄漏防线)。返回回收块数
/// (泄漏断言用)。
pub(crate) fn sweep_leaked() -> usize {
let mut ledger = lock();
let n = ledger.len();
for b in ledger.drain(..) {
unsafe { std::alloc::dealloc(b.ptr as *mut u8, b.layout) };
}
n
}
/// 函数表布局(与 SDK `OfxMemorySuiteV1` 一致;`size_t` 在本平台
/// 与 `usize` 同宽,stable Rust 用 `usize` 表达——骨架的 `c_size_t`
/// 是不稳定特性,弃用)。
#[repr(C)]
pub struct MemorySuiteV1 {
/// memoryAlloc:分配 `size` 字节,写 `*out`。
pub alloc: unsafe extern "C" fn(*mut c_void, usize, *mut *mut c_void) -> c_int,
/// memoryFree:释放;NULL 是 no-op。
pub free: unsafe extern "C" fn(*mut c_void) -> c_int,
}
use std::ffi::{c_int, c_void};
/// memoryAlloc 实现:`handle` 忽略(HS 同,ofxhHost.cpp:27)。
///
/// `# Safety`:`out` 必须是可写指针(插件契约)。
unsafe extern "C" fn memory_alloc(
_handle: *mut c_void,
byte_size: usize,
out: *mut *mut c_void,
) -> c_int {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if out.is_null() {
return status::ERR_VALUE;
}
match alloc(byte_size) {
Some(ptr) => {
unsafe { *out = ptr as *mut c_void };
status::OK
}
// 与 HS 一致:分配失败 → kOfxStatErrMemory(ofxhHost.cpp:35)。
None => status::ERR_MEMORY,
}
}))
.unwrap_or(status::FAILED)
}
/// memoryFree 实现:未知指针 → kOfxStatErrBadHandle(SDK 契约);
/// NULL 按 C 语义 no-op → OK(HS 的 free(NULL) 行为,ofxhHost.cpp:40)。
unsafe extern "C" fn memory_free(data: *mut c_void) -> c_int {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if free(data as *mut u8) {
status::OK
} else {
status::ERR_BAD_HANDLE
}
}))
.unwrap_or(status::FAILED)
}
/// 静态函数表实例。
pub fn suite_v1() -> &'static MemorySuiteV1 {
static SUITE: std::sync::OnceLock<MemorySuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| MemorySuiteV1 {
alloc: memory_alloc,
free: memory_free,
})
}
+376
View File
@@ -0,0 +1,376 @@
// 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/>.
//! OfxMessageSuite v1/v2:插件消息 → 宿主日志。
//!
//! stable Rust 无法定义 C-variadic 函数(c_variadic 仍不稳定),
//! v1 的 `...` 与 v2 的 va_list 入口由 C shim 承载
//! (cbits/ofx_message_shim.c,build.rs 经 `cc` 编译,符号随
//! staticlib 进入 liboakplugin):C 侧 vsnprintf 成定长缓冲后转发
//! 到本模块的 `oak_ofx_message_impl`。
//!
//! 消息出口 = facade 注册的 `oakplugin_message_fn`
//! (include/plugin/host.h)。本模块按头文件契约建模。
//! (原 C ABI 出口层已随单库化删除;注册点由 facade 直接调用。)
use std::collections::HashMap;
use std::ffi::{c_char, c_int, c_void, CStr};
use crate::suites::status;
/// facade 消息回调(include/plugin/host.h `oakplugin_message_fn`):
/// `(type, message, userdata) -> OAKPLUGIN_MESSAGE_ANSWER_NO/YES`。
pub(crate) type MessageHandler =
unsafe extern "C" fn(*const c_char, *const c_char, *mut c_void) -> c_int;
/// 消息出口注册表(facade 写入,suite 读;userdata 以 usize 存,
/// 避免裸指针破坏 static 的 Send/Sync 推导)。
static HANDLER: std::sync::Mutex<(Option<MessageHandler>, usize)> =
std::sync::Mutex::new((None, 0));
// ---------------------------------------------------------------------------
// 持久消息计数(检查器效果卡的徽标数据源,阶段 6b)
// ---------------------------------------------------------------------------
//
// C++ 侧 `OlivePluginInstance::persistentErrors_` 按实例累计持久消息,
// 并 emit `node_->message_count_changed()`。这里以实例 handle(props
// 地址,见 [`crate::suites::tag`])为键累计计数;app 检查器经
// [`crate::node_factory::instance_from_id`] 拿实例后按 props 地址查询。
static PERSISTENT: std::sync::OnceLock<std::sync::Mutex<HashMap<usize, usize>>> =
std::sync::OnceLock::new();
fn persistent_slot() -> &'static std::sync::Mutex<HashMap<usize, usize>> {
PERSISTENT.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}
/// 实例 handle(props 地址)的持久消息数(未登记 → 0)。
pub fn persistent_message_count(handle: usize) -> usize {
persistent_slot()
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&handle)
.copied()
.unwrap_or(0)
}
/// 清空某实例的持久消息(实例释放/宿主关闭路径;未登记的键 no-op)。
pub fn clear_persistent_messages(handle: usize) {
persistent_slot()
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&handle);
}
/// 注册/注销消息出口(facade 调用;公开:测试直接注入捕获器)。
pub fn set_handler(f: Option<MessageHandler>, userdata: *mut c_void) {
let mut h = HANDLER.lock().unwrap_or_else(|e| e.into_inner());
*h = (f, userdata as usize);
}
/// 读取当前出口。
fn handler() -> (Option<MessageHandler>, *mut c_void) {
let h = HANDLER.lock().unwrap_or_else(|e| e.into_inner());
(h.0, h.1 as *mut c_void)
}
/// kOfxMessageQuestion(ofxMessage.h:61):无出口时答"否"。
const K_MESSAGE_QUESTION: &[u8] = b"OfxMessageQuestion";
/// 消息类型是否为 question。
fn is_question(type_: *const c_char) -> bool {
// 空指针已在调用点拦截;此处仍防御(CStr::from_ptr 的调用方义务)。
if type_.is_null() {
return false;
}
unsafe { CStr::from_ptr(type_) }.to_bytes() == K_MESSAGE_QUESTION
}
/// Rust 侧实现(C shim 转发至此;`#[no_mangle]` 保证符号名与 C 侧
/// 引用一致)。语义逐条对照 C++:
/// - type/message 为空 → kOfxStatFailed(olivehost.cpp:267,vmessage
/// 对 !type || !format 的处理;format 为空的 case 由 shim 以
/// NULL message 转发);
/// - 有出口 → 转发 `(type, message, userdata)`,返回按头文件契约
/// 映射为 REPLY_YES/REPLY_NO(olivehost.cpp:277-279 的 handler
/// 路径;非 question 消息插件忽略返回值);
/// - 无出口 → stderr 日志(镜像 olivehost.cpp:282 的 fprintf 默认),
/// question 答"否"(olivehost.cpp:283-284)。
///
/// `# Safety`:`type`/`message` 必须是有效 C 字符串(插件契约,
/// shim 已保证 message 非悬垂——指向其栈缓冲,调用期间有效)。
#[no_mangle]
pub unsafe extern "C" fn oak_ofx_message_impl(
_handle: *mut c_void,
type_: *const c_char,
_id: *const c_char,
message: *const c_char,
) -> c_int {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if type_.is_null() || message.is_null() {
return status::FAILED;
}
// 持久消息:按实例 handle(剥标签后的 props 地址)累计计数
// (徽标数据源;C++ persistentErrors_ 的等价物)。
if !_handle.is_null() {
let key = crate::suites::tag::strip(_handle) as usize;
let mut map = persistent_slot().lock().unwrap_or_else(|e| e.into_inner());
*map.entry(key).or_insert(0) += 1;
drop(map);
}
let (handler, userdata) = handler();
if let Some(h) = handler {
// 头文件契约:返回值 0/1 即答复 NO/YES。
let answer = unsafe { h(type_, message, userdata) };
return if answer != 0 {
status::REPLY_YES
} else {
status::REPLY_NO
};
}
// Headless 默认:stderr(C++ fprintf 的 Rust 等价物)。
eprintln!(
"OFX message: {}",
unsafe { CStr::from_ptr(message) }.to_string_lossy()
);
if is_question(type_) {
status::REPLY_NO
} else {
status::OK
}
}))
.unwrap_or(status::FAILED)
}
/// 函数表布局(OfxMessageSuiteV1)。
#[repr(C)]
pub struct MessageSuiteV1 {
/// message(变长参数版;入口在 C shim)
pub message: unsafe extern "C" fn(
*mut c_void,
*const c_char,
*const c_char,
*const c_char,
...
) -> c_int,
}
/// 函数表布局(OfxMessageSuiteV2:第 5 参为平台相关 `va_list`)。
///
/// 真实 ABI 是 C 的 va_list(Apple arm64 上是结构体按值传递);
/// 声明为不透明指针仅作占位——本表只被插件→C shim 调用,Rust 侧
/// 永不直接调用,指针类型不参与任何实际调用。
#[repr(C)]
pub struct MessageSuiteV2 {
/// message(va_list 版;入口在 C shim)
pub message: unsafe extern "C" fn(
*mut c_void,
*const c_char,
*const c_char,
*const c_char,
*mut c_void,
) -> c_int,
}
extern "C" {
/// C shim 的 v1 入口(cbits/ofx_message_shim.c)。
fn ofx_message_shim_v1(
handle: *mut c_void,
type_: *const c_char,
id: *const c_char,
format: *const c_char,
...
) -> c_int;
/// C shim 的 v2 入口(va_list 已由 C 侧消费,Rust 只见不透明值)。
fn ofx_message_shim_v2(
handle: *mut c_void,
type_: *const c_char,
id: *const c_char,
format: *const c_char,
args: *mut c_void,
) -> c_int;
}
/// 静态函数表实例(v1)。
pub fn suite_v1() -> &'static MessageSuiteV1 {
static SUITE: std::sync::OnceLock<MessageSuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| MessageSuiteV1 {
message: ofx_message_shim_v1,
})
}
/// 静态函数表实例(v2)。
pub fn suite_v2() -> &'static MessageSuiteV2 {
static SUITE: std::sync::OnceLock<MessageSuiteV2> = std::sync::OnceLock::new();
SUITE.get_or_init(|| MessageSuiteV2 {
message: ofx_message_shim_v2,
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CString;
/// 测试共享全局 HANDLER,cargo 默认并行执行——串行化契约用例。
static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// 捕获型出口:把 (type, message) 记进 userdata 指向的 Vec。
unsafe extern "C" fn capture(
type_: *const c_char,
message: *const c_char,
userdata: *mut c_void,
) -> c_int {
let v = unsafe { &mut *(userdata as *mut Vec<(String, String)>) };
v.push((
unsafe { CStr::from_ptr(type_) }
.to_string_lossy()
.into_owned(),
unsafe { CStr::from_ptr(message) }
.to_string_lossy()
.into_owned(),
));
1
}
/// v1 入口:`...` 在 C shim 侧 vsnprintf 后转发,格式化正确。
#[test]
fn shim_v1_formats_and_forwards() {
let _g = TEST_LOCK.lock().unwrap();
let mut captured: Vec<(String, String)> = Vec::new();
set_handler(Some(capture), &mut captured as *mut _ as *mut c_void);
let s = suite_v1();
let type_ = CString::new("OfxMessageError").unwrap();
let id = CString::new("test-id").unwrap();
let fmt = CString::new("value=%d name=%s").unwrap();
let name = CString::new("oak").unwrap();
let r = unsafe {
(s.message)(
std::ptr::null_mut(),
type_.as_ptr(),
id.as_ptr(),
fmt.as_ptr(),
42,
name.as_ptr(),
)
};
// 出口答 YES → REPLY_YES。
assert_eq!(r, status::REPLY_YES);
assert_eq!(captured.len(), 1);
assert_eq!(captured[0].0, "OfxMessageError");
assert_eq!(captured[0].1, "value=42 name=oak");
set_handler(None, std::ptr::null_mut());
}
/// v1 入口:NULL format → kOfxStatFailed(C++ olivehost.cpp:267)。
#[test]
fn shim_v1_null_format_fails() {
let _g = TEST_LOCK.lock().unwrap();
let s = suite_v1();
let type_ = CString::new("OfxMessageError").unwrap();
let id = CString::new("id").unwrap();
let r = unsafe {
(s.message)(
std::ptr::null_mut(),
type_.as_ptr(),
id.as_ptr(),
std::ptr::null(),
)
};
assert_eq!(r, status::FAILED);
}
/// v2 入口:表字段非空且指向 C shim 符号(va_list 路径无法从
/// Rust 构造 va_list 调用,链的其余部分与 v1 共用 forward)。
#[test]
fn shim_v2_table_entry_resolves() {
let _g = TEST_LOCK.lock().unwrap();
let s = suite_v2();
assert!(!std::ptr::eq(
s.message as *const (),
ofx_message_shim_v1 as *const ()
));
}
/// 无出口(headless 默认):非 question → OK;question → REPLY_NO。
#[test]
fn no_handler_headless_defaults() {
let _g = TEST_LOCK.lock().unwrap();
set_handler(None, std::ptr::null_mut());
let s = suite_v1();
let type_ = CString::new("OfxMessageError").unwrap();
let id = CString::new("id").unwrap();
let fmt = CString::new("hello %s").unwrap();
let arg = CString::new("x").unwrap();
let r = unsafe {
(s.message)(
std::ptr::null_mut(),
type_.as_ptr(),
id.as_ptr(),
fmt.as_ptr(),
arg.as_ptr(),
)
};
assert_eq!(r, status::OK);
let q = CString::new("OfxMessageQuestion").unwrap();
let r = unsafe {
(s.message)(
std::ptr::null_mut(),
q.as_ptr(),
id.as_ptr(),
fmt.as_ptr(),
arg.as_ptr(),
)
};
assert_eq!(r, status::REPLY_NO);
}
/// 持久消息按实例 handle 累计(徽标数据源);clear 摘除。
#[test]
fn persistent_messages_accumulate_per_handle() {
let _g = TEST_LOCK.lock().unwrap();
set_handler(None, std::ptr::null_mut());
let props = crate::property::PropertySet::new();
let handle = crate::suites::tag::make(&props, crate::suites::tag::INSTANCE);
let key = crate::suites::tag::strip(handle) as usize;
clear_persistent_messages(key);
let type_ = CString::new("OfxMessageError").unwrap();
let id = CString::new("id").unwrap();
let msg = CString::new("boom").unwrap();
unsafe {
oak_ofx_message_impl(handle, type_.as_ptr(), id.as_ptr(), msg.as_ptr());
oak_ofx_message_impl(handle, type_.as_ptr(), id.as_ptr(), msg.as_ptr());
}
assert_eq!(persistent_message_count(key), 2);
clear_persistent_messages(key);
assert_eq!(persistent_message_count(key), 0);
// 空 handle 不计数。
unsafe {
oak_ofx_message_impl(
std::ptr::null_mut(),
type_.as_ptr(),
id.as_ptr(),
msg.as_ptr(),
);
}
assert_eq!(persistent_message_count(key), 0);
}
}
+380
View File
@@ -0,0 +1,380 @@
// 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/>.
//! suite 层:插件调进来的 C 函数表(unsafe trampoline 集中区)。
//!
//! 每张 suite 是一个 `#[repr(C)]` 的函数表静态实例;插件经
//! [`fetch_suite`] 取得。所有入口的安全模式相同:
//!
//! 1. 解 handle(`RefBox`/`PropertySet` 指针),空指针 →
//! kOfxStatErrBadHandle;
//! 2. 调 safe Rust 实现;
//! 3. `catch_unwind` 兜底 → kOfxStatFailed。
//!
//! 参照:HS: ofxhImageEffect.cpp:2776(fetchSuite 分发表与版本协商)。
pub mod draw;
pub mod gl_render;
pub mod image_effect;
pub mod interact;
pub mod memory;
pub mod message;
pub mod multithread;
pub mod param;
pub mod parametric;
pub mod progress;
pub mod property;
pub mod timeline;
/// OFX 状态码(全表与 SDK ofxCore.h:895-953 逐字一致;插件对状态码
/// 做精确比较,任何偏差都是静默兼容性破坏)。
pub mod status {
/// kOfxStatOK:成功。
pub const OK: i32 = 0;
/// kOfxStatFailed:通用失败。
pub const FAILED: i32 = 1;
/// kOfxStatErrFatal:致命错误。
pub const ERR_FATAL: i32 = 2;
/// kOfxStatErrUnknown:未知对象/属性。
pub const ERR_UNKNOWN: i32 = 3;
/// kOfxStatErrMissingHostFeature:宿主缺功能。
pub const ERR_MISSING_HOST_FEATURE: i32 = 4;
/// kOfxStatErrUnsupported:不支持的操作。
pub const ERR_UNSUPPORTED: i32 = 5;
/// kOfxStatErrExists:对象已存在。
pub const ERR_EXISTS: i32 = 6;
/// kOfxStatErrFormat:格式错误。
pub const ERR_FORMAT: i32 = 7;
/// kOfxStatErrMemory:内存不足。
pub const ERR_MEMORY: i32 = 8;
/// kOfxStatErrBadHandle:非法 handle(含 NULL)。
pub const ERR_BAD_HANDLE: i32 = 9;
/// kOfxStatErrBadIndex:索引越界。
pub const ERR_BAD_INDEX: i32 = 10;
/// kOfxStatErrValue:非法值。
pub const ERR_VALUE: i32 = 11;
/// kOfxStatReplyYes。
pub const REPLY_YES: i32 = 12;
/// kOfxStatReplyNo。
pub const REPLY_NO: i32 = 13;
/// kOfxStatReplyDefault。
pub const REPLY_DEFAULT: i32 = 14;
}
/// 句柄约定:发给插件的每个 OFX 句柄 = 对象 `props` 字段地址 | 低
/// 3 位标签。
///
/// 前置条件(本 crate 内部纪律,宿主创建对象时遵守):
/// - 对象 `#[repr(C)]` 且 `props: PropertySet` 在**偏移 0**——句柄的
/// 地址就是属性集地址,与 C++ "基类在偏移 0"(HS 里
/// OfxPropertySetHandle 即 Property::Set*)同构,属性 suite 无需
/// 反查即可直接解引用;
/// - 对象堆上稳定:`Arc<RefBox<T>>` / 结构体内的 `Box<T>` 元素
/// (Vec 重分配只移动 Box 指针,不移动负载)。
///
/// 标签位编码:低 3 位(含 Mutex/Arc 的对象对齐 ≥8,低 3 位恒 0)。
pub mod tag {
/// 标签掩码(低 3 位)。
pub const MASK: usize = 0b111;
/// 裸属性集(宿主内部直用 / 测试直传 `&props`)。
pub const PROPERTY_SET: usize = 0;
/// [`crate::descriptor::EffectDescriptor`](describe 期 effect/
/// param-set handle)。
pub const DESCRIPTOR: usize = 1;
/// [`crate::instance::Instance`](实例期 effect/param-set handle)。
pub const INSTANCE: usize = 2;
/// [`crate::param::ParamDef`](describe 期 param handle)。
pub const PARAM_DEF: usize = 3;
/// [`crate::param::ParamInstance`](实例期 param handle)。
pub const PARAM_INSTANCE: usize = 4;
/// [`crate::clip::ClipInstance`](实例期 clip handle;describe 期
/// [`crate::descriptor::ClipDescriptor`] 共用此标签——两类都只在
/// 各自的阶段被使用,属性 suite 不区分)。
pub const CLIP: usize = 5;
/// [`crate::image::Image`](clipGetImage 的产物)。
pub const IMAGE: usize = 6;
/// [`crate::suites::interact::Interact`](interact 实例 handle;
/// 实例期 effect/param-set 之外的独立交互对象)。
pub const INTERACT: usize = 7;
/// 打标签(宿主创建对象句柄用;公开供宿主/测试构造句柄)。
pub fn make(props: *const crate::property::PropertySet, t: usize) -> *mut std::ffi::c_void {
(props as usize | t) as *mut std::ffi::c_void
}
/// 剥标签,取 props 指针(标签 0 的裸指针原样返回)。
pub fn strip(handle: *mut std::ffi::c_void) -> *const crate::property::PropertySet {
((handle as usize) & !MASK) as *const crate::property::PropertySet
}
/// 读标签。
pub fn kind(handle: *mut std::ffi::c_void) -> usize {
(handle as usize) & MASK
}
}
/// 渲染上下文(TLS):render 驱动在调用插件 action 前设置,suite
/// 回调(timeline、clipGetImage 的 scale、进度)从中读取;对应 HS
/// 中实例在渲染期的状态(ofxhImageEffect.cpp Render in_args 的子集)。
#[derive(Clone, Copy)]
pub struct RenderCtx {
/// 当前渲染时间(秒)。
pub time: f64,
/// 渲染比例。
pub scale: crate::instance::RenderScale,
/// 项目时间域(timeline getTimeBounds)。
pub range: crate::instance::OfxRangeD,
}
thread_local! {
static RENDER_CTX: std::cell::RefCell<Option<RenderCtx>> = const { std::cell::RefCell::new(None) };
}
/// 设置/清除渲染上下文(render 驱动调用;action 返回前必须清除;
/// 公开:render 驱动在 host 层,测试也直接注入)。
pub fn set_render_ctx(ctx: Option<RenderCtx>) {
RENDER_CTX.with(|c| *c.borrow_mut() = ctx);
}
/// 读取渲染上下文(无上下文返回 None;无 TLS 时插件时间查询得到
/// 0 的 headless 默认)。
pub(crate) fn render_ctx() -> Option<RenderCtx> {
RENDER_CTX.with(|c| *c.borrow())
}
thread_local! {
/// 当前渲染的输出图像(render 驱动设置;image effect suite 的
/// clipGetImage 对 Output clip 返回它)。
static CURRENT_OUTPUT: std::cell::RefCell<Option<std::sync::Arc<crate::image::Image>>> =
const { std::cell::RefCell::new(None) };
}
/// 设置/清除当前输出图像(render 驱动调用;action 返回前必须清除)。
pub(crate) fn set_current_output(image: Option<std::sync::Arc<crate::image::Image>>) {
CURRENT_OUTPUT.with(|c| *c.borrow_mut() = image);
}
/// 读取当前输出图像。
pub(crate) fn current_output() -> Option<std::sync::Arc<crate::image::Image>> {
CURRENT_OUTPUT.with(|c| c.borrow().clone())
}
/// GL 渲染上下文(TLS):GL render 驱动在调用插件 action 前设置,
/// OpenGLRender suite 的 clipLoadTexture 从中取当前渲染器与输出
/// 纹理(对应 C++ 里实例渲染期的 GL 状态;ofxGPURender.h
/// "OpenGL Current Context" 一节要求宿主在 Render 期间持有 GL
/// 上下文——本设计的约定是调用方(oakrender 的 PluginJob 路径)在
/// 进入 render_job 前已把渲染器上下文置为 current,本表只传递
/// 渲染器引用与输出纹理值)。
#[derive(Clone)]
pub struct GlCtx {
/// 当前渲染器(oakrender 后端上下文)。
pub renderer: crate::render::Renderer,
/// 已附着的输出纹理(渲染目标;GL 模式下插件把结果画进它)。
pub output_texture: crate::render::Texture,
/// 当前 GL 纹理的实际像素深度(kOfxBitDepth* 静态串;Phase 2
/// 全链路 F32,由 render_gl 按插件 kOfxOpenGLPropPixelDepth 协商
/// 后填入——纹理句柄的 kOfxImageEffectPropPixelDepth 以它为准)。
pub gl_pixel_depth: &'static str,
/// 已附着的**真实 GL 输出纹理名**(GL 模式下宿主为输出帧建的
/// GL 纹理 + FBO 颜色附件;clipLoadTexture(Output) 的
/// OpenGLTextureIndex 以它为准——ofxGPURender.h 要求宿主把输出
/// 纹理绑定为当前颜色缓冲)。None = 无真实 GL 名(CPU 回退)。
pub output_gl_texture: Option<i32>,
}
thread_local! {
static GL_CTX: std::cell::RefCell<Option<GlCtx>> = const { std::cell::RefCell::new(None) };
}
/// 设置/清除 GL 渲染上下文(GL render 驱动调用;action 返回前必须
/// 清除;公开:测试直接注入)。
pub fn set_gl_ctx(ctx: Option<GlCtx>) {
GL_CTX.with(|c| *c.borrow_mut() = ctx);
}
/// 读取 GL 渲染上下文(无上下文返回 None——clipLoadTexture 在非
/// GL 渲染期调用时按规范返回 kOfxStatErrMissingHostFeature)。
pub(crate) fn gl_ctx() -> Option<GlCtx> {
GL_CTX.with(|c| c.borrow().clone())
}
/// 宿主进程身份(fetchSuite 的 version 检查用;= OFX API 1.5)。
pub(crate) const OFX_API_VERSION: i32 = 105;
/// fetchSuite 宿主入口:按名字与版本返回函数表指针;不认识或版本
/// 不符返回 `None`(FFI 层转 NULL)。
///
/// 第 1 期注册:OfxPropertySuite v1、OfxMemorySuite v1、
/// OfxImageEffectSuite v1、OfxParameterSuite v1、OfxMessageSuite
/// v1/v2、OfxProgressSuite v1/v2、OfxTimeLineSuite v1、
/// OfxMultiThreadSuite v1。
/// 第 2 期追加:OfxImageEffectOpenGLRenderSuite v1(GL 路径);
/// ofxColour 无 suite 表(纯属性 + GetOutputColourspace action)。
/// 第 3 期追加:OfxInteractSuite v1、OfxDrawSuite v1(interact 宿主)。
/// 第 4 期追加:OfxParametricParameterSuite v1(曲线参数,
/// suites/parametric.rs)。
pub fn fetch_suite(name: &str, version: i32) -> Option<*const std::ffi::c_void> {
let suite: *const std::ffi::c_void = match (name, version) {
("OfxPropertySuite", 1) => ptr(property::suite_v1()),
("OfxMemorySuite", 1) => ptr(memory::suite_v1()),
("OfxImageEffectSuite", 1) => ptr(image_effect::suite_v1()),
("OfxParameterSuite", 1) => ptr(param::suite_v1()),
("OfxMessageSuite", 1) => ptr(message::suite_v1()),
("OfxMessageSuite", 2) => ptr(message::suite_v2()),
("OfxProgressSuite", 1) => ptr(progress::suite_v1()),
("OfxProgressSuite", 2) => ptr(progress::suite_v2()),
("OfxTimeLineSuite", 1) => ptr(timeline::suite_v1()),
("OfxMultiThreadSuite", 1) => ptr(multithread::suite_v1()),
("OfxImageEffectOpenGLRenderSuite", 1) => ptr(gl_render::suite_v1()),
("OfxInteractSuite", 1) => ptr(interact::suite_v1()),
("OfxDrawSuite", 1) => ptr(draw::suite_v1()),
("OfxParametricParameterSuite", 1) => ptr(parametric::suite_v1()),
_ => return None,
};
Some(suite)
}
/// 表引用 → 不透明指针(fetch_suite 的统一出口)。
fn ptr<T>(p: &'static T) -> *const std::ffi::c_void {
p as *const T as *const std::ffi::c_void
}
#[cfg(test)]
mod tests {
use super::*;
/// suite 分发表:版本精确匹配、未知版本/名字 → None。
#[test]
fn fetch_suite_dispatch() {
assert!(fetch_suite("OfxPropertySuite", 1).is_some());
assert!(fetch_suite("OfxMemorySuite", 1).is_some());
assert!(fetch_suite("OfxImageEffectSuite", 1).is_some());
assert!(fetch_suite("OfxParameterSuite", 1).is_some());
assert!(fetch_suite("OfxMessageSuite", 1).is_some());
assert!(fetch_suite("OfxMessageSuite", 2).is_some());
assert!(fetch_suite("OfxProgressSuite", 1).is_some());
assert!(fetch_suite("OfxProgressSuite", 2).is_some());
assert!(fetch_suite("OfxTimeLineSuite", 1).is_some());
assert!(fetch_suite("OfxMultiThreadSuite", 1).is_some());
assert!(fetch_suite("OfxImageEffectOpenGLRenderSuite", 1).is_some());
assert!(fetch_suite("OfxInteractSuite", 1).is_some());
assert!(fetch_suite("OfxDrawSuite", 1).is_some());
assert!(fetch_suite("OfxParametricParameterSuite", 1).is_some());
assert!(fetch_suite("OfxPropertySuite", 2).is_none());
assert!(fetch_suite("OfxMessageSuite", 3).is_none());
assert!(fetch_suite("OfxImageEffectOpenGLRenderSuite", 2).is_none());
assert!(fetch_suite("OfxInteractSuite", 2).is_none());
assert!(fetch_suite("OfxDrawSuite", 2).is_none());
assert!(fetch_suite("OfxParametricParameterSuite", 2).is_none());
assert!(fetch_suite("OfxBogusSuite", 1).is_none());
assert!(fetch_suite("", 1).is_none());
}
/// 句柄标签:打标/剥标/读 kind 往返;对齐地址低位为 0。
#[test]
fn handle_tag_roundtrip() {
let set = crate::property::PropertySet::new();
let props = &set as *const crate::property::PropertySet;
assert_eq!(props as usize & tag::MASK, 0, "PropertySet 必须 ≥8 对齐");
for t in [
tag::PROPERTY_SET,
tag::DESCRIPTOR,
tag::INSTANCE,
tag::PARAM_DEF,
tag::PARAM_INSTANCE,
tag::CLIP,
tag::IMAGE,
tag::INTERACT,
] {
let h = tag::make(props, t);
assert_eq!(tag::kind(h), t);
assert_eq!(tag::strip(h) as usize, props as usize);
}
}
/// 渲染上下文 TLS:设置/读取/清除。
#[test]
fn render_ctx_tls() {
assert!(render_ctx().is_none());
let ctx = RenderCtx {
time: 1.5,
scale: crate::instance::RenderScale { x: 2.0, y: 2.0 },
range: crate::instance::OfxRangeD {
min: 0.0,
max: 100.0,
},
};
set_render_ctx(Some(ctx));
let got = render_ctx().unwrap();
assert_eq!(got.time, 1.5);
assert_eq!(got.scale.x, 2.0);
assert_eq!(got.range.max, 100.0);
set_render_ctx(None);
assert!(render_ctx().is_none());
}
/// GL 上下文 TLS:设置/读取/清除(clipLoadTexture 的渲染期取值)。
#[test]
fn gl_ctx_tls() {
assert!(gl_ctx().is_none());
// 最小 GpuContextLike 假实现(无 GPU 适配器需求)。
struct FakeGpu;
impl oak_render::backend::GpuContextLike for FakeGpu {
fn kind(&self) -> oak_render::backend::BackendKind {
oak_render::backend::BackendKind::Cpu
}
fn destroy_texture(&self, _token: u64) {}
fn upload(
&self,
_token: u64,
_frame: &oak_render::texture::Frame,
) -> oak_render::error::Result<()> {
Ok(())
}
fn download(&self, _token: u64) -> oak_render::error::Result<oak_render::texture::Frame> {
Ok(oak_render::texture::Frame::new())
}
fn blit(
&self,
_src: u64,
_dst: u64,
_processor: Option<&oak_render::color::ColorProcessor>,
) -> oak_render::error::Result<()> {
Ok(())
}
}
let renderer: crate::render::Renderer = std::sync::Arc::new(FakeGpu);
let tex = crate::render::Texture::dummy();
set_gl_ctx(Some(GlCtx {
renderer,
output_texture: tex.clone(),
gl_pixel_depth: "OfxBitDepthFloat",
output_gl_texture: Some(42),
}));
let got = gl_ctx().unwrap();
assert_eq!(
got.renderer.kind(),
oak_render::backend::BackendKind::Cpu
);
assert!(got.output_texture.is_dummy());
assert_eq!(got.gl_pixel_depth, "OfxBitDepthFloat");
assert_eq!(got.output_gl_texture, Some(42));
set_gl_ctx(None);
assert!(gl_ctx().is_none());
}
}
+341
View File
@@ -0,0 +1,341 @@
// 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/>.
//! OfxMultiThreadSuite v1:插件自起线程的登记与索引分配。
//!
//! 纪律:插件线程可在本 suite 存活期回调任意 suite——所有共享状态
//! 必须 Mutex(README §3)。线程经 `std::thread::scope` 启动并同步
//! join(OFX 语义:multiThread 返回时全部线程已完成;
//! HS: ofxhImageEffect.cpp gMultiThreadSuite),故无需常驻线程表。
//! 线程索引经 TLS 分配:宿主线程 [`index`] 为 -1、
//! [`is_spawned`] 为 0。
//!
//! 参照:HS: ofxhImageEffect.cpp gMultiThreadSuite。
use std::collections::HashMap;
use std::ffi::{c_int, c_uint, c_void};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use crate::suites::status;
thread_local! {
/// 本线程的 OFX 线程索引(宿主线程 = None)。
static THREAD_INDEX: std::cell::Cell<Option<c_uint>> = const { std::cell::Cell::new(None) };
}
/// 函数表布局(OfxMultiThreadSuiteV1)。
#[repr(C)]
pub struct MultiThreadSuiteV1 {
/// multiThread:启动 `n_threads` 个线程跑 `func`,线程索引
/// 0..n_threads-1 经 `thread_arg` 传入。
pub multi_thread: unsafe extern "C" fn(
func: unsafe extern "C" fn(c_uint, c_uint, *mut c_void),
n_threads: c_uint,
thread_arg: *mut c_void,
) -> c_int,
/// multiThreadNumCPUs
pub num_cpus: unsafe extern "C" fn(*mut c_int) -> c_int,
/// multiThreadIndex:当前线程的 OFX 线程索引(宿主线程为 -1)。
pub index: unsafe extern "C" fn(*mut c_int) -> c_int,
/// multiThreadIsSpawnedThread:当前线程是否插件线程。
pub is_spawned: unsafe extern "C" fn(*mut c_int) -> c_int,
/// mutexCreate:`count` 是初始可用计数(>1 时是信号量语义)。
pub mutex_create: unsafe extern "C" fn(*mut *mut c_void, c_int) -> c_int,
/// mutexDestroy
pub mutex_destroy: unsafe extern "C" fn(*mut c_void) -> c_int,
/// mutexLock
pub mutex_lock: unsafe extern "C" fn(*mut c_void) -> c_int,
/// mutexUnLock
pub mutex_unlock: unsafe extern "C" fn(*mut c_void) -> c_int,
/// mutexTryLock
pub mutex_try_lock: unsafe extern "C" fn(*mut c_void) -> c_int,
}
/// 公共入口模板:panic 兜底。
fn caught(f: impl FnOnce() -> c_int) -> c_int {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or(status::FAILED)
}
/// multiThread 实现:同步起 n 个线程(0..n-1),join 后返回。
/// 线程体只做两件事:登记 TLS 索引、调 `func`(C 代码,不 panic)。
unsafe extern "C" fn multi_thread(
func: unsafe extern "C" fn(c_uint, c_uint, *mut c_void),
n_threads: c_uint,
thread_arg: *mut c_void,
) -> c_int {
caught(|| {
// 裸指针不可 Send:以 usize 搬运,线程内还原(C 侧本即
// 整数传递语义)。
let arg = thread_arg as usize;
let _ = std::thread::scope(|scope| {
for i in 0..n_threads {
scope.spawn(move || {
THREAD_INDEX.with(|t| t.set(Some(i)));
// func 是插件代码:按 OFX 契约不 panic;Rust 侧
// 只做 TLS 登记,无 panic 源。
unsafe { (func)(i, n_threads, arg as *mut c_void) };
THREAD_INDEX.with(|t| t.set(None));
});
}
});
status::OK
})
}
unsafe extern "C" fn multi_thread_num_cpus(out: *mut c_int) -> c_int {
caught(|| {
if out.is_null() {
return status::ERR_VALUE;
}
// 物理核数(HS 同:系统 CPU 数)。
let n = std::thread::available_parallelism()
.map(|n| n.get() as c_int)
.unwrap_or(1);
unsafe { *out = n };
status::OK
})
}
unsafe extern "C" fn multi_thread_index(out: *mut c_int) -> c_int {
caught(|| {
if out.is_null() {
return status::ERR_VALUE;
}
// 宿主线程 → -1(HS 约定)。
unsafe { *out = THREAD_INDEX.with(|t| t.get()).map_or(-1, |i| i as c_int) };
status::OK
})
}
unsafe extern "C" fn multi_thread_is_spawned(out: *mut c_int) -> c_int {
caught(|| {
if out.is_null() {
return status::ERR_VALUE;
}
unsafe { *out = THREAD_INDEX.with(|t| t.get().is_some()) as c_int };
status::OK
})
}
// ---- 互斥锁(OfxMultiThreadSuiteV1 的 mutex* 函数组)-----------------------
//
// 句柄表:全局注册表按 usize 键发号;`count > 1` 是信号量语义(ofxMultiThread.h
// "a mutex with a count greater than 1 is a counting semaphore")。
// 插件在多线程渲染期用它们保护共享状态——ofxs 支持库的
// ofxsThreadSuiteCheck 在 load 时逐一检查这些函数非空,缺一个整批插件
// 直接拒载。
/// 计数信号量(count==1 时即普通互斥锁)。
struct OfxMutex {
permits: std::sync::Mutex<c_int>,
released: std::sync::Condvar,
}
/// 句柄注册表(句柄即下一个递增 id 转指针;0 保留给空)。
static MUTEXES: std::sync::LazyLock<Mutex<HashMap<usize, Arc<OfxMutex>>>> =
std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
/// 下一个互斥锁 id。
static NEXT_MUTEX: AtomicUsize = AtomicUsize::new(1);
fn mutex_lookup(handle: *mut c_void) -> Option<Arc<OfxMutex>> {
if handle.is_null() {
return None;
}
MUTEXES
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&(handle as usize))
.cloned()
}
unsafe extern "C" fn mutex_create(out: *mut *mut c_void, count: c_int) -> c_int {
caught(|| {
if out.is_null() {
return status::ERR_VALUE;
}
let id = NEXT_MUTEX.fetch_add(1, Ordering::Relaxed);
MUTEXES
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(id, Arc::new(OfxMutex {
permits: std::sync::Mutex::new(count.max(1)),
released: std::sync::Condvar::new(),
}));
unsafe { *out = id as *mut c_void };
status::OK
})
}
unsafe extern "C" fn mutex_destroy(handle: *mut c_void) -> c_int {
caught(|| {
if mutex_lookup(handle).is_none() {
return status::ERR_BAD_HANDLE;
}
MUTEXES
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&(handle as usize));
status::OK
})
}
unsafe extern "C" fn mutex_lock(handle: *mut c_void) -> c_int {
caught(|| {
let Some(m) = mutex_lookup(handle) else {
return status::ERR_BAD_HANDLE;
};
let mut permits = m.permits.lock().unwrap_or_else(|e| e.into_inner());
while *permits <= 0 {
permits = m.released.wait(permits).unwrap_or_else(|e| e.into_inner());
}
*permits -= 1;
status::OK
})
}
unsafe extern "C" fn mutex_unlock(handle: *mut c_void) -> c_int {
caught(|| {
let Some(m) = mutex_lookup(handle) else {
return status::ERR_BAD_HANDLE;
};
{
let mut permits = m.permits.lock().unwrap_or_else(|e| e.into_inner());
*permits += 1;
}
m.released.notify_one();
status::OK
})
}
unsafe extern "C" fn mutex_try_lock(handle: *mut c_void) -> c_int {
caught(|| {
let Some(m) = mutex_lookup(handle) else {
return status::ERR_BAD_HANDLE;
};
let mut permits = m.permits.lock().unwrap_or_else(|e| e.into_inner());
if *permits <= 0 {
// 规范:占不到锁返回 kOfxStatFailed(不是错误)。
return status::FAILED;
}
*permits -= 1;
status::OK
})
}
/// 静态函数表实例。
pub fn suite_v1() -> &'static MultiThreadSuiteV1 {
static SUITE: std::sync::OnceLock<MultiThreadSuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| MultiThreadSuiteV1 {
multi_thread: multi_thread,
num_cpus: multi_thread_num_cpus,
index: multi_thread_index,
is_spawned: multi_thread_is_spawned,
mutex_create: mutex_create,
mutex_destroy: mutex_destroy,
mutex_lock: mutex_lock,
mutex_unlock: mutex_unlock,
mutex_try_lock: mutex_try_lock,
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
/// 每个插件线程把 (index, count) 累计进 userdata。
unsafe extern "C" fn worker(index: c_uint, count: c_uint, arg: *mut c_void) {
let state = unsafe { &mut *(arg as *mut (AtomicUsize, AtomicUsize)) };
state.0.fetch_add(index as usize, Ordering::Relaxed);
state.1.fetch_add(count as usize, Ordering::Relaxed);
}
#[test]
fn multi_thread_spawns_and_joins() {
let s = suite_v1();
let state = (AtomicUsize::new(0), AtomicUsize::new(0));
unsafe {
assert_eq!(
(s.multi_thread)(worker, 8, &state as *const _ as *mut c_void),
status::OK
);
}
// 索引 0..7 各一次 → 28;count 各 8 → 64。
assert_eq!(state.0.load(Ordering::Relaxed), 28);
assert_eq!(state.1.load(Ordering::Relaxed), 64);
// 0 线程:no-op OK。
unsafe {
assert_eq!(
(s.multi_thread)(worker, 0, &state as *const _ as *mut c_void),
status::OK
);
}
}
/// 插件线程内查询 index/isSpawned 并把结果写回 arg 指向的槽。
/// (闭包捕获 suite 无法转 fn 指针,用具名函数 + 静态槽。)
static SPAWNED_RESULT: std::sync::LazyLock<std::sync::Mutex<Option<(c_int, c_int)>>> =
std::sync::LazyLock::new(|| std::sync::Mutex::new(None));
unsafe extern "C" fn query_worker(_index: c_uint, _count: c_uint, _arg: *mut c_void) {
let s = suite_v1();
let mut i = 0;
let mut sp = 1;
unsafe {
let _ = (s.index)(&mut i);
let _ = (s.is_spawned)(&mut sp);
}
*SPAWNED_RESULT.lock().unwrap_or_else(|e| e.into_inner()) = Some((i, sp));
}
#[test]
fn index_and_spawned() {
let s = suite_v1();
let mut i = 0;
let mut spawned = 1;
unsafe {
// 宿主线程:index = -1,isSpawned = 0。
assert_eq!((s.index)(&mut i), status::OK);
assert_eq!(i, -1);
assert_eq!((s.is_spawned)(&mut spawned), status::OK);
assert_eq!(spawned, 0);
// 插件线程内:index 正确、isSpawned = 1。
assert_eq!(
(s.multi_thread)(query_worker, 1, std::ptr::null_mut()),
status::OK
);
assert_eq!(
*SPAWNED_RESULT.lock().unwrap_or_else(|e| e.into_inner()),
Some((0, 1))
);
}
}
#[test]
fn num_cpus_positive() {
let s = suite_v1();
let mut n = 0;
unsafe {
assert_eq!((s.num_cpus)(&mut n), status::OK);
}
assert!(n >= 1);
}
}
File diff suppressed because it is too large Load Diff
+902
View File
@@ -0,0 +1,902 @@
// 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/>.
//! OfxParametricParameterSuite v1:参数化曲线参数(调色插件的
//! 曲线/LUT 类参数)。
//!
//! 语义对照 ofxParametricParam.h(属性表另见 HS ofxhParam.cpp:285-330):
//! - 曲线 = 每维一条 [`crate::param_curve::Curve`],存于参数值
//! [`crate::param::ParamValue::Parametric`](def 默认 / instance 当前
//! 值,`ParamInstance::from_def` 复制默认);
//! - 维度与定义域取参数属性 [`crate::param::P_PARAMETRIC_DIMENSION`]
//! (int,默认 1)与 [`crate::param::P_PARAMETRIC_RANGE`]
//! (double×2,默认 (0,1))——paramDefine 预置,插件 describe 期可改;
//! - 求值 = 三次 Hermite(slope 自动差分),越界 parametricPosition
//! 钳制到端点值,见 [`crate::param_curve::Curve::evaluate`];
//! - describe 期(Def)的 Set/Add/Delete 改**默认值**(HS:"If a
//! plugin wishes to set a different default value for a curve, it can
//! use the suite to set key/value pairs on the descriptor. When a new
//! instance is made, it will have these curve values as a default");
//! - 第 1 期无参数动画(宿主
//! `kOfxParamHostPropSupportsParametricAnimation = 0`):`time` 恒
//! 忽略(曲线是实例级静态的),`addAnimationKey` 同理忽略;
//! - 未配置的曲线(维度内但从未写入)按恒等默认求值/读数——与
//! "default default 是恒等查找" 一致;任何写入路径先把缺失曲线
//! 补成恒等默认再落库;
//! - 错误码:坏句柄 → BadHandle,非 parametric 参数 → BadHandle,
//! curveIndex / nth 越界 → BadIndex(头文件 GetNth/Set/Add 文档
//! 里写的 Unknown 是类型未知的泛指,本实现按任务约定统一
//! BadHandle/BadIndex)。
use std::borrow::Cow;
use std::ffi::{c_char, c_double, c_int, c_void};
use crate::descriptor::EffectDescriptor;
use crate::instance::Instance;
use crate::param::{ParamDef, ParamInstance, ParamValue};
use crate::param_curve::Curve;
use crate::property::{PropertySet, Value};
use crate::suites::{status, tag};
/// 函数表布局(与 SDK `OfxParametricParameterSuiteV1` 一致;字段序
/// 以 ofxParametricParam.h 为准)。
#[repr(C)]
pub struct ParametricParameterSuiteV1 {
/// parametricParamGetValue:求值曲线(越界位置钳制到端点值)。
pub parametric_param_get_value: unsafe extern "C" fn(
*mut c_void,
c_int,
c_double,
c_double,
*mut c_double,
) -> c_int,
/// parametricParamGetNControlPoints:控制点数。
pub parametric_param_get_n_control_points:
unsafe extern "C" fn(*mut c_void, c_int, c_double, *mut c_int) -> c_int,
/// parametricParamGetNthControlPoint:第 nth 个控制点的 key/value。
pub parametric_param_get_nth_control_point: unsafe extern "C" fn(
*mut c_void,
c_int,
c_double,
c_int,
*mut c_double,
*mut c_double,
) -> c_int,
/// parametricParamSetNthControlPoint:改第 nth 个控制点
/// (key 变化后保持有序,slope 重算)。
pub parametric_param_set_nth_control_point: unsafe extern "C" fn(
*mut c_void,
c_int,
c_double,
c_int,
c_double,
c_double,
c_int,
) -> c_int,
/// parametricParamAddControlPoint:加入/覆盖控制点(保持有序)。
pub parametric_param_add_control_point: unsafe extern "C" fn(
*mut c_void,
c_int,
c_double,
c_double,
c_double,
c_int,
) -> c_int,
/// parametricParamDeleteControlPoint:删第 nth 个控制点。
pub parametric_param_delete_control_point:
unsafe extern "C" fn(*mut c_void, c_int, c_int) -> c_int,
/// parametricParamDeleteAllControlPoints:清空某维曲线。
pub parametric_param_delete_all_control_points:
unsafe extern "C" fn(*mut c_void, c_int) -> c_int,
}
// ---- 句柄解析 -----------------------------------------------------------
/// param 句柄:describe 期是定义(值=默认值),实例期是实例。
/// Def 持 `&mut`(Set/Add/Delete 直改默认值);Instance 持 `&`
/// (经 [`ParamInstance::set_ofx`] 的内部 Mutex 改当前值)。
enum ParamRef<'a> {
Def(&'a mut ParamDef),
Instance(&'a ParamInstance),
}
/// 解析 param 句柄。空指针/标签不符 → BadHandle。
fn resolve_param(handle: *mut c_void) -> Result<ParamRef<'static>, c_int> {
if handle.is_null() {
return Err(status::ERR_BAD_HANDLE);
}
unsafe {
match tag::kind(handle) {
tag::PARAM_DEF => Ok(ParamRef::Def(&mut *(tag::strip(handle) as *mut ParamDef))),
tag::PARAM_INSTANCE => Ok(ParamRef::Instance(&*(
tag::strip(handle) as *const ParamInstance
))),
_ => Err(status::ERR_BAD_HANDLE),
}
}
}
/// 公共入口模板:panic 兜底。
#[track_caller]
fn caught(f: impl FnOnce() -> Result<(), c_int>) -> c_int {
let caller = std::panic::Location::caller();
let code = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_or_else(
|_| status::FAILED,
|r| r.map_or_else(|c| c, |()| status::OK),
);
if code != status::OK && std::env::var_os("OAK_OFX_TRACE").is_some() {
eprintln!("[ofx] parametric suite error {code} at {caller}");
}
code
}
// ---- 模型存取 -----------------------------------------------------------
/// 取参数曲线(Def=默认值,Instance=当前值)。值不是 parametric 曲线
/// → BadHandle(非 parametric 参数的 suite 语义;先于索引检查,保证
/// 非 parametric 恒为 BadHandle)。
fn curves_of(r: &ParamRef) -> Result<Vec<Curve>, c_int> {
match r {
ParamRef::Def(d) => match &d.default {
ParamValue::Parametric(c) => Ok(c.clone()),
_ => Err(status::ERR_BAD_HANDLE),
},
ParamRef::Instance(p) => match p.get() {
ParamValue::Parametric(c) => Ok(c),
_ => Err(status::ERR_BAD_HANDLE),
},
}
}
/// 写回曲线:Def → 默认值;Instance → 当前值 + instanceChanged 通知
/// (复用 param suite 的 [`crate::suites::param::notify_changed`]——
/// 曲线经 [`crate::param::notify_instance_changed`] 序列化为 JSON
/// 文本写回节点输入(undoable,同标量路径),保持宿主侧变更感知的
/// 纪律一致)。
fn write_curves(r: &mut ParamRef, curves: Vec<Curve>) {
match r {
ParamRef::Def(d) => d.default = ParamValue::Parametric(curves),
ParamRef::Instance(p) => {
let name = p.def.name.clone();
let addr = &p.props as *const _ as usize;
p.set_ofx(ParamValue::Parametric(curves));
crate::suites::param::notify_changed(addr, &name);
}
}
}
/// param 的属性集(句柄即 props 地址,偏移 0 句柄约定)。
fn props_of(handle: *mut c_void) -> &'static PropertySet {
unsafe { &*tag::strip(handle) }
}
/// 维度:`OfxParamPropParametricDimension`(int,默认 1;≤0 防御性
/// 按 1 处理——头文件要求"greater than 0")。
fn dimension_of(handle: *mut c_void) -> usize {
match props_of(handle).get(crate::param::P_PARAMETRIC_DIMENSION, 0) {
Some(Value::Int(d)) => d.max(1) as usize,
_ => 1,
}
}
/// 定义域:`OfxParamPropParametricRange`(double×2,默认 (0,1))——
/// 未配置曲线补恒等默认时的端点。
fn range_of(handle: *mut c_void) -> (f64, f64) {
let props = props_of(handle);
let lo = match props.get(crate::param::P_PARAMETRIC_RANGE, 0) {
Some(Value::Double(d)) => d,
_ => 0.0,
};
let hi = match props.get(crate::param::P_PARAMETRIC_RANGE, 1) {
Some(Value::Double(d)) => d,
_ => 1.0,
};
(lo, hi)
}
/// curveIndex 越界(相对 dimension 属性)→ BadIndex。
fn check_curve_index(handle: *mut c_void, curve_index: c_int) -> Result<usize, c_int> {
let ci = usize::try_from(curve_index).map_err(|_| status::ERR_BAD_INDEX)?;
if ci >= dimension_of(handle) {
return Err(status::ERR_BAD_INDEX);
}
Ok(ci)
}
/// 取第 `ci` 条曲线;缺失(维内但从未写入)→ 恒等默认(只读路径
/// 不落库:未配置曲线 = 恒等查找)。
fn curve_at<'a>(curves: &'a [Curve], ci: usize, range: (f64, f64)) -> Cow<'a, Curve> {
match curves.get(ci) {
Some(c) => Cow::Borrowed(c),
None => Cow::Owned(Curve::identity(range.0, range.1)),
}
}
/// 确保第 `ci` 条曲线存在(写入路径:缺失时补恒等默认再落库)。
fn ensure_curve(curves: &mut Vec<Curve>, ci: usize, range: (f64, f64)) -> &mut Curve {
while curves.len() <= ci {
curves.push(Curve::identity(range.0, range.1));
}
&mut curves[ci]
}
// ---- suite 函数 ---------------------------------------------------------
/// parametricParamGetValue:求值曲线。`time` 忽略(无参数动画);
/// 越界 parametricPosition 钳制到端点值([`Curve::evaluate`])。
unsafe extern "C" fn parametric_param_get_value(
param: *mut c_void,
curve_index: c_int,
_time: c_double,
parametric_position: c_double,
out: *mut c_double,
) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_VALUE);
}
unsafe { *out = 0.0 };
let r = resolve_param(param)?;
let curves = curves_of(&r)?;
let ci = check_curve_index(param, curve_index)?;
let range = range_of(param);
let v = curve_at(&curves, ci, range).evaluate(parametric_position);
unsafe { *out = v };
Ok(())
})
}
/// parametricParamGetNControlPoints:控制点数(未配置曲线 = 恒等默认
/// 的 2 点)。
unsafe extern "C" fn parametric_param_get_n_control_points(
param: *mut c_void,
curve_index: c_int,
_time: c_double,
out: *mut c_int,
) -> c_int {
caught(|| {
if out.is_null() {
return Err(status::ERR_VALUE);
}
unsafe { *out = 0 };
let r = resolve_param(param)?;
let curves = curves_of(&r)?;
let ci = check_curve_index(param, curve_index)?;
let n = curve_at(&curves, ci, range_of(param)).len();
unsafe { *out = n as c_int };
Ok(())
})
}
/// parametricParamGetNthControlPoint:第 nth 个控制点的 key/value
/// (nth 越界 → BadIndex;未配置曲线按恒等默认读数)。
unsafe extern "C" fn parametric_param_get_nth_control_point(
param: *mut c_void,
curve_index: c_int,
_time: c_double,
nth: c_int,
key: *mut c_double,
value: *mut c_double,
) -> c_int {
caught(|| {
if key.is_null() || value.is_null() {
return Err(status::ERR_VALUE);
}
unsafe {
*key = 0.0;
*value = 0.0;
};
let r = resolve_param(param)?;
let curves = curves_of(&r)?;
let ci = check_curve_index(param, curve_index)?;
let nth = usize::try_from(nth).map_err(|_| status::ERR_BAD_INDEX)?;
let c = curve_at(&curves, ci, range_of(param));
let p = c.nth(nth).ok_or(status::ERR_BAD_INDEX)?;
unsafe {
*key = p.key;
*value = p.value;
};
Ok(())
})
}
/// parametricParamSetNthControlPoint:改第 nth 个控制点为 (key,
/// value)。key 变化可能破坏有序性(头文件明确提醒)——模型侧先移除
/// 再按 key 插入、撞 key 按覆盖处理、slope 重算([`Curve::set_nth`])。
/// `addAnimationKey` 忽略(宿主不支持参数动画)。
unsafe extern "C" fn parametric_param_set_nth_control_point(
param: *mut c_void,
curve_index: c_int,
_time: c_double,
nth: c_int,
key: c_double,
value: c_double,
_add_animation_key: c_int,
) -> c_int {
caught(|| {
let mut r = resolve_param(param)?;
let mut curves = curves_of(&r)?;
let ci = check_curve_index(param, curve_index)?;
let nth = usize::try_from(nth).map_err(|_| status::ERR_BAD_INDEX)?;
ensure_curve(&mut curves, ci, range_of(param))
.set_nth(nth, key, value)
.map_err(|()| status::ERR_BAD_INDEX)?;
write_curves(&mut r, curves);
Ok(())
})
}
/// parametricParamAddControlPoint:加入控制点;同 key 已存在 → 覆盖
/// (头文件 "If a key exists sufficiently close to 'key', then it will
/// be set to the indicated control point";本实现取精确同 key)。
/// `addAnimationKey` 忽略(无参数动画)。
unsafe extern "C" fn parametric_param_add_control_point(
param: *mut c_void,
curve_index: c_int,
_time: c_double,
key: c_double,
value: c_double,
_add_animation_key: c_int,
) -> c_int {
caught(|| {
let mut r = resolve_param(param)?;
let mut curves = curves_of(&r)?;
let ci = check_curve_index(param, curve_index)?;
ensure_curve(&mut curves, ci, range_of(param)).upsert(key, value);
write_curves(&mut r, curves);
Ok(())
})
}
/// parametricParamDeleteControlPoint:删第 nth 个控制点(越界 →
/// BadIndex)。
unsafe extern "C" fn parametric_param_delete_control_point(
param: *mut c_void,
curve_index: c_int,
nth: c_int,
) -> c_int {
caught(|| {
let mut r = resolve_param(param)?;
let mut curves = curves_of(&r)?;
let ci = check_curve_index(param, curve_index)?;
let nth = usize::try_from(nth).map_err(|_| status::ERR_BAD_INDEX)?;
ensure_curve(&mut curves, ci, range_of(param))
.delete_nth(nth)
.map_err(|()| status::ERR_BAD_INDEX)?;
write_curves(&mut r, curves);
Ok(())
})
}
/// parametricParamDeleteAllControlPoints:清空某维曲线(清空后求值
/// 退化为恒等,[`Curve::evaluate`] 的空曲线分支)。
unsafe extern "C" fn parametric_param_delete_all_control_points(
param: *mut c_void,
curve_index: c_int,
) -> c_int {
caught(|| {
let mut r = resolve_param(param)?;
let mut curves = curves_of(&r)?;
let ci = check_curve_index(param, curve_index)?;
ensure_curve(&mut curves, ci, range_of(param)).clear();
write_curves(&mut r, curves);
Ok(())
})
}
/// 静态函数表实例。
pub fn suite_v1() -> &'static ParametricParameterSuiteV1 {
static SUITE: std::sync::OnceLock<ParametricParameterSuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| ParametricParameterSuiteV1 {
parametric_param_get_value: parametric_param_get_value,
parametric_param_get_n_control_points: parametric_param_get_n_control_points,
parametric_param_get_nth_control_point: parametric_param_get_nth_control_point,
parametric_param_set_nth_control_point: parametric_param_set_nth_control_point,
parametric_param_add_control_point: parametric_param_add_control_point,
parametric_param_delete_control_point: parametric_param_delete_control_point,
parametric_param_delete_all_control_points: parametric_param_delete_all_control_points,
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CString;
use std::sync::Arc;
use crate::host::Plugin;
use crate::param::{ParamInstance, ParamSetInstance};
use crate::property::PropertySet;
fn cs(s: &str) -> CString {
CString::new(s).unwrap()
}
fn descriptor_handle(d: &EffectDescriptor) -> *mut c_void {
tag::make(&d.props as *const PropertySet, tag::DESCRIPTOR)
}
/// 假插件(host::Plugin 的构造只为拿 Arc 喂给 Instance;describe
/// 之外的字段不被本测试触碰)。
fn dummy_plugin(descriptor: EffectDescriptor) -> Arc<Plugin> {
unsafe extern "C" fn dummy_entry(
_: *const c_char,
_: *const c_void,
_: *mut c_void,
_: *mut c_void,
) -> c_int {
status::OK
}
Arc::new(Plugin {
identifier: "test.plugin".into(),
version: (1, 0),
bundle_path: std::path::PathBuf::new(),
contexts: vec![],
descriptor,
lib: std::ptr::null_mut(),
entry: dummy_entry,
ofx_plugin: std::ptr::null_mut(),
unloaded: std::sync::atomic::AtomicBool::new(false),
})
}
fn instance_handle(i: &Instance) -> *mut c_void {
tag::make(&i.props as *const PropertySet, tag::INSTANCE)
}
/// describe 期建一个 parametric 参数 "curve"(默认维度 1),返回
/// 描述符与其 param 句柄。
fn define_parametric() -> (EffectDescriptor, *mut c_void) {
let desc = EffectDescriptor::new();
let s = crate::suites::param::suite_v1();
let dhandle = descriptor_handle(&desc);
let t = cs(crate::param::TYPE_PARAMETRIC);
let n = cs("curve");
let mut ph: *mut c_void = std::ptr::null_mut();
unsafe {
assert_eq!((s.param_define)(dhandle, t.as_ptr(), n.as_ptr(), &mut ph), 0);
}
assert_eq!(tag::kind(ph), tag::PARAM_DEF);
(desc, ph)
}
/// 把 describe 产物实例化(default → 实例值复制),返回
/// (实例 Arc, 实例 handle, 实例 param 句柄)。
fn instantiate(desc: EffectDescriptor) -> (Arc<Instance>, *mut c_void, *mut c_void) {
let params = ParamSetInstance {
params: desc
.params
.iter()
.map(|d| Box::new(ParamInstance::from_def((**d).clone())))
.collect(),
};
let plugin = dummy_plugin(desc);
let inst = Arc::new(Instance {
props: PropertySet::new(),
plugin,
context: "OfxImageEffectContextFilter".into(),
params,
clips: vec![],
node_identity: std::sync::atomic::AtomicUsize::new(0),
destroyed: std::sync::atomic::AtomicBool::new(false),
sequence_range: std::sync::Mutex::new(None),
progress_cb: std::sync::Mutex::new(None),
cancel: std::sync::atomic::AtomicBool::new(false),
edit: std::sync::Mutex::new(crate::instance::EditTransaction::new()),
render_lock: std::sync::Mutex::new(()),
interact: std::sync::Mutex::new(None),
});
let ih = instance_handle(&inst);
let s = crate::suites::param::suite_v1();
let n = cs("curve");
let mut ph: *mut c_void = std::ptr::null_mut();
unsafe {
assert_eq!((s.param_get_handle)(ih, n.as_ptr(), &mut ph, std::ptr::null_mut()), 0);
}
assert_eq!(tag::kind(ph), tag::PARAM_INSTANCE);
(inst, ih, ph)
}
/// describe 定义 + 实例化一步到位(默认维度 1)。
fn make_instance() -> (Arc<Instance>, *mut c_void, *mut c_void) {
let (desc, _dph) = define_parametric();
instantiate(desc)
}
fn ps() -> &'static ParametricParameterSuiteV1 {
suite_v1()
}
/// describe 期默认值:2 个恒等控制点 (0,0)/(1,1),求值 = 恒等。
#[test]
fn describe_defaults_are_identity() {
let (_desc, ph) = define_parametric();
let s = ps();
let mut n = -1;
unsafe {
assert_eq!((s.parametric_param_get_n_control_points)(ph, 0, 0.0, &mut n), 0);
}
assert_eq!(n, 2);
let (mut k, mut v) = (-1.0, -1.0);
unsafe {
assert_eq!((s.parametric_param_get_nth_control_point)(ph, 0, 0.0, 0, &mut k, &mut v), 0);
}
assert_eq!((k, v), (0.0, 0.0));
unsafe {
assert_eq!((s.parametric_param_get_nth_control_point)(ph, 0, 0.0, 1, &mut k, &mut v), 0);
}
assert_eq!((k, v), (1.0, 1.0));
// 恒等求值(越界钳制端点值)。
let mut out = 0.0;
unsafe {
assert_eq!((s.parametric_param_get_value)(ph, 0, 0.0, 0.5, &mut out), 0);
}
assert_eq!(out, 0.5);
unsafe {
assert_eq!((s.parametric_param_get_value)(ph, 0, 0.0, -3.0, &mut out), 0);
assert_eq!(out, 0.0);
assert_eq!((s.parametric_param_get_value)(ph, 0, 0.0, 7.0, &mut out), 0);
assert_eq!(out, 1.0);
}
}
/// describe 期 Set/Add/Delete 改**默认值**,实例化时复制到实例。
#[test]
fn descriptor_edits_become_instance_defaults() {
let (desc, ph) = define_parametric();
let s = ps();
// describe 期改默认:加两个点,改第 1 个点的值。
unsafe {
assert_eq!((s.parametric_param_add_control_point)(ph, 0, 0.0, 0.25, 0.5, 0), 0);
assert_eq!((s.parametric_param_add_control_point)(ph, 0, 0.0, 0.75, 0.9, 0), 0);
assert_eq!((s.parametric_param_set_nth_control_point)(ph, 0, 0.0, 1, 0.25, 0.6, 0), 0);
}
// 默认值本身生效。
let mut out = 0.0;
unsafe {
assert_eq!((s.parametric_param_get_value)(ph, 0, 0.0, 0.25, &mut out), 0);
}
assert_eq!(out, 0.6);
// 实例化:默认曲线随 from_def 复制。
let (_inst, _ih, iph) = instantiate(desc);
unsafe {
assert_eq!((s.parametric_param_get_value)(iph, 0, 0.0, 0.25, &mut out), 0);
}
assert_eq!(out, 0.6);
let mut n = 0;
unsafe {
assert_eq!((s.parametric_param_get_n_control_points)(iph, 0, 0.0, &mut n), 0);
}
assert_eq!(n, 4); // (0,0) (0.25,0.6) (0.75,0.9) (1,1)
}
/// 实例期全链路:Add → Set → Delete → DeleteAll,求值随模型变化。
#[test]
fn instance_add_set_delete_eval_chain() {
let (_inst, _ih, ph) = make_instance();
let s = ps();
// Add 中点 (0.3, 0.7):插值性质 + 有序。
unsafe {
assert_eq!((s.parametric_param_add_control_point)(ph, 0, 0.0, 0.3, 0.7, 0), 0);
}
let mut out = 0.0;
unsafe {
assert_eq!((s.parametric_param_get_value)(ph, 0, 0.0, 0.3, &mut out), 0);
}
assert_eq!(out, 0.7);
let mut n = 0;
unsafe {
assert_eq!((s.parametric_param_get_n_control_points)(ph, 0, 0.0, &mut n), 0);
}
assert_eq!(n, 3);
// SetNth 改 (0.3,0.7) → (0.4,0.6)。
unsafe {
assert_eq!((s.parametric_param_set_nth_control_point)(ph, 0, 0.0, 1, 0.4, 0.6, 0), 0);
}
let (mut k, mut v) = (-1.0, -1.0);
unsafe {
assert_eq!((s.parametric_param_get_nth_control_point)(ph, 0, 0.0, 1, &mut k, &mut v), 0);
}
assert_eq!((k, v), (0.4, 0.6));
unsafe {
assert_eq!((s.parametric_param_get_value)(ph, 0, 0.0, 0.4, &mut out), 0);
}
assert_eq!(out, 0.6);
// Delete 第 1 点 → 回到双点。
unsafe {
assert_eq!((s.parametric_param_delete_control_point)(ph, 0, 1), 0);
}
unsafe {
assert_eq!((s.parametric_param_get_n_control_points)(ph, 0, 0.0, &mut n), 0);
}
assert_eq!(n, 2);
// DeleteAll → 0 点,求值退化为恒等。
unsafe {
assert_eq!((s.parametric_param_delete_all_control_points)(ph, 0), 0);
assert_eq!((s.parametric_param_get_n_control_points)(ph, 0, 0.0, &mut n), 0);
assert_eq!((s.parametric_param_get_value)(ph, 0, 0.0, 0.5, &mut out), 0);
}
assert_eq!(n, 0);
assert_eq!(out, 0.5);
}
/// SetNth 改 key 破坏有序性 → 自动重排(头文件提醒的语义)。
#[test]
fn set_nth_reorders_on_key_change() {
let (_inst, _ih, ph) = make_instance();
let s = ps();
unsafe {
assert_eq!((s.parametric_param_add_control_point)(ph, 0, 0.0, 0.5, 0.5, 0), 0);
// 把第 0 点 (0,0) 挪到 0.75 → 序列变 (0.5) (0.75) (1)。
assert_eq!((s.parametric_param_set_nth_control_point)(ph, 0, 0.0, 0, 0.75, 0.75, 0), 0);
}
let (mut k, mut v) = (-1.0, -1.0);
for (i, (ek, ev)) in [(0.5, 0.5), (0.75, 0.75), (1.0, 1.0)].iter().enumerate() {
unsafe {
assert_eq!((s.parametric_param_get_nth_control_point)(ph, 0, 0.0, i as c_int, &mut k, &mut v), 0);
}
assert_eq!((k, v), (*ek, *ev), "nth {i}");
}
}
/// 同 key Add → 覆盖(不增点)。
#[test]
fn add_overwrites_same_key() {
let (_inst, _ih, ph) = make_instance();
let s = ps();
unsafe {
assert_eq!((s.parametric_param_add_control_point)(ph, 0, 0.0, 0.5, 0.4, 0), 0);
assert_eq!((s.parametric_param_add_control_point)(ph, 0, 0.0, 0.5, 0.9, 0), 0);
}
let mut n = 0;
unsafe {
assert_eq!((s.parametric_param_get_n_control_points)(ph, 0, 0.0, &mut n), 0);
}
assert_eq!(n, 3); // (0,0) (0.5,0.9) (1,1)
let (mut k, mut v) = (-1.0, -1.0);
unsafe {
assert_eq!((s.parametric_param_get_nth_control_point)(ph, 0, 0.0, 1, &mut k, &mut v), 0);
}
assert_eq!((k, v), (0.5, 0.9));
}
/// 错误码:坏句柄 / 非 parametric / curveIndex 越界 / nth 越界 /
/// 空 out。
#[test]
fn error_codes() {
let s = ps();
let mut out = 0.0;
// 空句柄 → BadHandle。
unsafe {
assert_eq!(
(s.parametric_param_get_value)(std::ptr::null_mut(), 0, 0.0, 0.5, &mut out),
status::ERR_BAD_HANDLE
);
}
// 空 out → ErrValue。
let (_inst, _ih, ph) = make_instance();
unsafe {
assert_eq!(
(s.parametric_param_get_value)(ph, 0, 0.0, 0.5, std::ptr::null_mut()),
status::ERR_VALUE
);
}
// curveIndex 越界(维度 1)→ BadIndex。
unsafe {
assert_eq!(
(s.parametric_param_get_value)(ph, 1, 0.0, 0.5, &mut out),
status::ERR_BAD_INDEX
);
}
// nth 越界(2 点曲线)→ BadIndex。
let mut k = 0.0;
unsafe {
assert_eq!(
(s.parametric_param_get_nth_control_point)(ph, 0, 0.0, 5, &mut k, &mut out),
status::ERR_BAD_INDEX
);
}
// 非 parametric 参数 → BadHandle(Integer 参数的句柄)。
let desc = EffectDescriptor::new();
let psuite = crate::suites::param::suite_v1();
let dhandle = descriptor_handle(&desc);
let t = cs("OfxParamTypeInteger");
let n = cs("gain");
let mut gph: *mut c_void = std::ptr::null_mut();
unsafe {
assert_eq!((psuite.param_define)(dhandle, t.as_ptr(), n.as_ptr(), &mut gph), 0);
// parametric 也定义一个,便于实例化后拿两个 handle。
let pt = cs(crate::param::TYPE_PARAMETRIC);
let pn = cs("curve");
let mut pph: *mut c_void = std::ptr::null_mut();
assert_eq!((psuite.param_define)(dhandle, pt.as_ptr(), pn.as_ptr(), &mut pph), 0);
let params = ParamSetInstance {
params: desc
.params
.iter()
.map(|d| Box::new(ParamInstance::from_def((**d).clone())))
.collect(),
};
let plugin = dummy_plugin(desc);
let inst = Arc::new(Instance {
props: PropertySet::new(),
plugin,
context: "OfxImageEffectContextFilter".into(),
params,
clips: vec![],
node_identity: std::sync::atomic::AtomicUsize::new(0),
destroyed: std::sync::atomic::AtomicBool::new(false),
sequence_range: std::sync::Mutex::new(None),
progress_cb: std::sync::Mutex::new(None),
cancel: std::sync::atomic::AtomicBool::new(false),
edit: std::sync::Mutex::new(crate::instance::EditTransaction::new()),
render_lock: std::sync::Mutex::new(()),
interact: std::sync::Mutex::new(None),
});
let ih = instance_handle(&inst);
let mut g: *mut c_void = std::ptr::null_mut();
let gn = cs("gain");
assert_eq!((psuite.param_get_handle)(ih, gn.as_ptr(), &mut g, std::ptr::null_mut()), 0);
assert_eq!(
(s.parametric_param_get_value)(g, 0, 0.0, 0.5, &mut out),
status::ERR_BAD_HANDLE
);
assert_eq!(
(s.parametric_param_add_control_point)(g, 0, 0.0, 0.5, 0.5, 0),
status::ERR_BAD_HANDLE
);
}
}
/// 维度属性驱动:插件设 dimension=2 后第二维可用、第三维 BadIndex;
/// 未配置曲线按恒等默认读数。
#[test]
fn dimension_prop_drives_curves() {
let (desc, ph) = define_parametric();
// 插件经属性 suite 把维度改成 2。
let psuite = crate::suites::property::suite_v1();
let dim = cs(crate::param::P_PARAMETRIC_DIMENSION);
unsafe {
assert_eq!((psuite.set_int)(ph, dim.as_ptr(), 0, 2), 0);
}
let s = ps();
// 第二维:Add 后求值可用。
unsafe {
assert_eq!((s.parametric_param_add_control_point)(ph, 1, 0.0, 0.25, 0.5, 0), 0);
}
let mut out = 0.0;
unsafe {
assert_eq!((s.parametric_param_get_value)(ph, 1, 0.0, 0.25, &mut out), 0);
}
assert_eq!(out, 0.5);
// 第一维未配置 → 恒等默认。
unsafe {
assert_eq!((s.parametric_param_get_value)(ph, 0, 0.0, 0.25, &mut out), 0);
}
assert_eq!(out, 0.25);
let mut n = 0;
unsafe {
assert_eq!((s.parametric_param_get_n_control_points)(ph, 0, 0.0, &mut n), 0);
}
assert_eq!(n, 2);
// 第三维 → BadIndex。
unsafe {
assert_eq!(
(s.parametric_param_get_value)(ph, 2, 0.0, 0.5, &mut out),
status::ERR_BAD_INDEX
);
assert_eq!(
(s.parametric_param_add_control_point)(ph, 2, 0.0, 0.5, 0.5, 0),
status::ERR_BAD_INDEX
);
}
// 维度属性随 from_def 复制到实例(实例句柄上同样生效)。
let (_inst, _ih, iph) = instantiate(desc);
let mut n = -1;
unsafe {
assert_eq!((s.parametric_param_get_n_control_points)(iph, 1, 0.0, &mut n), 0);
}
assert_eq!(n, 3); // (0,0) (0.25,0.5) (1,1)
}
/// range 属性参与未配置曲线的恒等默认(端点 = range 值)。
#[test]
fn range_prop_shapes_implicit_identity() {
let (_desc, ph) = define_parametric();
let psuite = crate::suites::property::suite_v1();
let dim = cs(crate::param::P_PARAMETRIC_DIMENSION);
let range = cs(crate::param::P_PARAMETRIC_RANGE);
unsafe {
assert_eq!((psuite.set_int)(ph, dim.as_ptr(), 0, 2), 0);
// range = (0, 255)。
assert_eq!((psuite.set_double)(ph, range.as_ptr(), 0, 0.0), 0);
assert_eq!((psuite.set_double)(ph, range.as_ptr(), 1, 255.0), 0);
}
let s = ps();
// 未配置的第二维:恒等默认端点 = range。
let (mut k, mut v) = (-1.0, -1.0);
unsafe {
assert_eq!((s.parametric_param_get_nth_control_point)(ph, 1, 0.0, 1, &mut k, &mut v), 0);
}
assert_eq!((k, v), (255.0, 255.0));
}
/// UI 属性(UIColour double×3N / InteractBackground 指针)经通用
/// 属性 suite set/get,并随 from_def 复制到实例。
#[test]
fn ui_props_set_get_and_copy() {
let (desc, ph) = define_parametric();
let psuite = crate::suites::property::suite_v1();
// UIColour:3 个 double(维度 1 → 1 个 RGB 三元组)。
let colour = cs(crate::param::P_PARAMETRIC_UI_COLOUR);
let rgb: [f64; 3] = [1.0, 0.0, 0.5];
unsafe {
assert_eq!((psuite.set_double_n)(ph, colour.as_ptr(), 3, rgb.as_ptr()), 0);
}
// InteractBackground:任意指针。
let bg = cs(crate::param::P_PARAMETRIC_INTERACT_BG);
let sentinel = 0x1234usize as *mut c_void;
unsafe {
assert_eq!((psuite.set_pointer)(ph, bg.as_ptr(), 0, sentinel), 0);
}
// 读回。
let mut got = [0.0; 3];
unsafe {
assert_eq!((psuite.get_double_n)(ph, colour.as_ptr(), 3, got.as_mut_ptr()), 0);
}
assert_eq!(got, rgb);
let mut gotp: *mut c_void = std::ptr::null_mut();
unsafe {
assert_eq!((psuite.get_pointer)(ph, bg.as_ptr(), 0, &mut gotp), 0);
}
assert_eq!(gotp, sentinel);
// 实例 props 深拷贝。
let (_inst, _ih, iph) = instantiate(desc);
let mut got2 = [0.0; 3];
unsafe {
assert_eq!((psuite.get_double_n)(iph, colour.as_ptr(), 3, got2.as_mut_ptr()), 0);
}
assert_eq!(got2, rgb);
let mut gotp2: *mut c_void = std::ptr::null_mut();
unsafe {
assert_eq!((psuite.get_pointer)(iph, bg.as_ptr(), 0, &mut gotp2), 0);
}
assert_eq!(gotp2, sentinel);
}
/// 实例编辑走 instance-changed 通知路径(未绑定节点 → no-op,
/// 不 panic 即通过;登记路径的节流语义由 param suite 测试覆盖)。
#[test]
fn instance_edits_go_through_notify_path() {
let (_inst, _ih, ph) = make_instance();
let s = ps();
unsafe {
assert_eq!((s.parametric_param_add_control_point)(ph, 0, 0.0, 0.2, 0.8, 0), 0);
assert_eq!((s.parametric_param_set_nth_control_point)(ph, 0, 0.0, 1, 0.2, 0.9, 0), 0);
assert_eq!((s.parametric_param_delete_control_point)(ph, 0, 1), 0);
assert_eq!((s.parametric_param_delete_all_control_points)(ph, 0), 0);
}
let mut out = 0.0;
unsafe {
assert_eq!((s.parametric_param_get_value)(ph, 0, 0.0, 0.2, &mut out), 0);
}
assert_eq!(out, 0.2);
}
}
+208
View File
@@ -0,0 +1,208 @@
// 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/>.
//! OfxProgressSuite v1/v2:进度 → 当前渲染的
//! [`crate::progress::ProgressReporter`]。
//!
//! 定位方式:TLS(render 驱动在调用插件 action 前
//! [`set_current`],action 返回后清除)——进度只在渲染期内有意义,
//! 不设全局状态(progress.rs 文档)。
//! 语义:update 返回 false(取消)→ kOfxStatReplyNo
//! (HS: ofxhImageEffect.cpp gProgressSuite);无报告器(渲染外
//! 调用)→ 静默 OK。start/end 为括号,OK。
use std::ffi::{c_char, c_double, c_int, c_void};
use crate::progress::ProgressReporter;
use crate::suites::status;
thread_local! {
static CURRENT: std::cell::RefCell<Option<ProgressReporter>> = const { std::cell::RefCell::new(None) };
}
/// 设置/清除当前报告器(render 驱动调用;公开:render 驱动在
/// host 层,测试也直接注入)。
pub fn set_current(reporter: Option<ProgressReporter>) {
CURRENT.with(|c| *c.borrow_mut() = reporter);
}
/// 读取当前报告器的取消状态(image effect suite 的 abort 用)。
pub(crate) fn is_cancelled() -> bool {
CURRENT.with(|c| c.borrow().as_ref().is_some_and(|r| r.is_cancelled()))
}
/// 进度更新:取消 → kOfxStatReplyNo;无报告器/未取消 → OK。
fn progress_update(progress: f64) -> c_int {
let cancelled = CURRENT.with(|c| match c.borrow().as_ref() {
Some(r) => !r.update(progress),
None => false,
});
if cancelled {
status::REPLY_NO
} else {
status::OK
}
}
/// 公共入口模板:panic 兜底。
fn caught(f: impl FnOnce() -> c_int) -> c_int {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or(status::FAILED)
}
/// 函数表布局(OfxProgressSuiteV1)。
#[repr(C)]
pub struct ProgressSuiteV1 {
/// progressStart
pub start: unsafe extern "C" fn(*mut c_void, *const c_char) -> c_int,
/// progressUpdate(返回非 kOfxStatOK 即取消)
pub update: unsafe extern "C" fn(*mut c_void, c_double) -> c_int,
/// progressEnd
pub end: unsafe extern "C" fn(*mut c_void) -> c_int,
}
/// 函数表布局(OfxProgressSuiteV2:start 带 label + message)。
#[repr(C)]
pub struct ProgressSuiteV2 {
/// progressStart
pub start: unsafe extern "C" fn(*mut c_void, *const c_char, *const c_char) -> c_int,
/// progressUpdate
pub update: unsafe extern "C" fn(*mut c_void, c_double) -> c_int,
/// progressEnd
pub end: unsafe extern "C" fn(*mut c_void) -> c_int,
}
/// C 字符串解码(空指针/非法 UTF-8 → 空串)。
unsafe fn decode<'a>(p: *const c_char) -> &'a str {
if p.is_null() {
return "";
}
unsafe { std::ffi::CStr::from_ptr(p) }
.to_str()
.unwrap_or("")
}
/// progressStart:括号起点;携 label(v2 另携 message)经
/// [`crate::progress`] 工厂现造 UI 报告器(无工厂/已有报告器时
/// no-op),状态恒 OK。
unsafe extern "C" fn progress_start_v1(_handle: *mut c_void, label: *const c_char) -> c_int {
caught(|| {
let label = unsafe { decode(label) }.to_string();
CURRENT.with(|c| {
if let Some(r) = c.borrow().as_ref() {
r.install_ui(&label, "");
}
});
status::OK
})
}
unsafe extern "C" fn progress_update_v1(_handle: *mut c_void, progress: c_double) -> c_int {
caught(|| progress_update(progress))
}
unsafe extern "C" fn progress_end_v1(_handle: *mut c_void) -> c_int {
caught(|| {
CURRENT.with(|c| {
if let Some(r) = c.borrow().as_ref() {
r.end_ui();
}
});
status::OK
})
}
unsafe extern "C" fn progress_start_v2(
_handle: *mut c_void,
label: *const c_char,
message: *const c_char,
) -> c_int {
caught(|| {
let label = unsafe { decode(label) }.to_string();
let message = unsafe { decode(message) }.to_string();
CURRENT.with(|c| {
if let Some(r) = c.borrow().as_ref() {
r.install_ui(&label, &message);
}
});
status::OK
})
}
unsafe extern "C" fn progress_update_v2(_handle: *mut c_void, progress: c_double) -> c_int {
caught(|| progress_update(progress))
}
unsafe extern "C" fn progress_end_v2(_handle: *mut c_void) -> c_int {
caught(|| status::OK)
}
/// 静态函数表实例(v1)。
pub fn suite_v1() -> &'static ProgressSuiteV1 {
static SUITE: std::sync::OnceLock<ProgressSuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| ProgressSuiteV1 {
start: progress_start_v1,
update: progress_update_v1,
end: progress_end_v1,
})
}
/// 静态函数表实例(v2)。
pub fn suite_v2() -> &'static ProgressSuiteV2 {
static SUITE: std::sync::OnceLock<ProgressSuiteV2> = std::sync::OnceLock::new();
SUITE.get_or_init(|| ProgressSuiteV2 {
start: progress_start_v2,
update: progress_update_v2,
end: progress_end_v2,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// 取消型出口(头文件契约:非 0 = 中止)。
unsafe extern "C" fn cancel_cb(_p: f64, _userdata: *mut c_void) -> c_int {
1
}
/// 静默:update 恒 OK;带取消回调:update → REPLY_NO 且 abort
/// 查询为真(粘滞)。
#[test]
fn update_cancel_and_abort() {
// 无报告器(渲染外):静默 OK。
set_current(None);
let s = suite_v1();
unsafe {
assert_eq!((s.update)(std::ptr::null_mut(), 0.5), status::OK);
assert_eq!(
(s.start)(std::ptr::null_mut(), std::ptr::null()),
status::OK
);
assert_eq!((s.end)(std::ptr::null_mut()), status::OK);
}
// 带取消回调:update → REPLY_NO;is_cancelled 为真。
set_current(Some(unsafe {
ProgressReporter::new(cancel_cb, std::ptr::null_mut())
}));
unsafe {
assert_eq!((s.update)(std::ptr::null_mut(), 0.5), status::REPLY_NO);
}
assert!(is_cancelled());
set_current(None);
assert!(!is_cancelled());
}
}
+719
View File
@@ -0,0 +1,719 @@
// 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/>.
//! OfxPropertySuite v1:属性读写。
//!
//! 语义逐条对照 HS: ofxhPropertySuite.cpp:
//! - 读未定义属性 / 类型不符 → kOfxStatErrUnknown(HS: propGet 的
//! `fetchTypedProperty` 失败路径,ofxhPropertySuite.cpp:787-794);
//! - 越界读写 → kOfxStatErrBadIndex(HS: `getValueRaw`/
//! `setValue`,ofxhPropertySuite.cpp:257/284);
//! - propGetN 拷贝 min(count, dimension) 个元素,不报错
//! (HS: `getValueNRaw`,ofxhPropertySuite.cpp:271-280);
//! - propSetN 维度变化时整体替换:本 crate 的属性维度始终跟随数组
//! 长度(HS 对固定维度属性 count > dimension 会返回
//! kOfxStatErrBadIndex,ofxhPropertySuite.cpp:299——本 crate 不区分
//! 固定/可变维度,如实更宽容;三个系统 bundle 均以正确 count 调用,
//! 无行为分歧);
//! - 只读属性:SDK 无 kOfxStatErrReadOnly,HostSupport 也不在 suite
//! 层拦截写(`_pluginReadOnly` 仅供宿主内部逻辑查询)——本实现
//! 如实不拦截;若日后需要,在 PropertySet 增加只读标记再评。
//! - propReset:HostSupport 恢复到 define 时默认值
//! (ofxhPropertySuite.cpp:330);本 crate 不保存默认值快照,
//! 第 1 期明确返回 kOfxStatErrUnsupported(真话比静默 no-op 安全)。
use std::ffi::{c_char, c_double, c_int, c_void, CStr, CString};
use crate::property::{Property, PropertySet, Value};
use crate::suites::status;
/// 函数表布局(与 SDK `OfxPropertySuiteV1` 逐字段一致)。
#[repr(C)]
pub struct PropertySuiteV1 {
/// propSetPointer
pub set_pointer: unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *mut c_void) -> c_int,
/// propSetString
pub set_string: unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *const c_char) -> c_int,
/// propSetDouble
pub set_double: unsafe extern "C" fn(*mut c_void, *const c_char, c_int, c_double) -> c_int,
/// propSetInt
pub set_int: unsafe extern "C" fn(*mut c_void, *const c_char, c_int, c_int) -> c_int,
/// propSetPointerN
pub set_pointer_n:
unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *const *mut c_void) -> c_int,
/// propSetStringN
pub set_string_n:
unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *const *const c_char) -> c_int,
/// propSetDoubleN
pub set_double_n:
unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *const c_double) -> c_int,
/// propSetIntN
pub set_int_n: unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *const c_int) -> c_int,
/// propGetPointer
pub get_pointer:
unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *mut *mut c_void) -> c_int,
/// propGetString
pub get_string:
unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *mut *mut c_char) -> c_int,
/// propGetDouble
pub get_double: unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *mut c_double) -> c_int,
/// propGetInt
pub get_int: unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *mut c_int) -> c_int,
/// propGetPointerN
pub get_pointer_n:
unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *mut *mut c_void) -> c_int,
/// propGetStringN
pub get_string_n:
unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *mut *mut c_char) -> c_int,
/// propGetDoubleN
pub get_double_n:
unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *mut c_double) -> c_int,
/// propGetIntN
pub get_int_n: unsafe extern "C" fn(*mut c_void, *const c_char, c_int, *mut c_int) -> c_int,
/// propReset
pub reset: unsafe extern "C" fn(*mut c_void, *const c_char) -> c_int,
/// propGetDimension
pub get_dimension: unsafe extern "C" fn(*mut c_void, *const c_char, *mut c_int) -> c_int,
}
/// 属性值类别(suite 层的类型检查;对应 HS 的 `Property::TypeEnum`)。
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
Int,
Double,
Str,
Pointer,
}
impl Kind {
fn of(v: &Value) -> Kind {
match v {
Value::Int(_) => Kind::Int,
Value::Double(_) => Kind::Double,
Value::String(_) => Kind::Str,
Value::Pointer(_) => Kind::Pointer,
}
}
}
/// 属性 suite 公共入口模板:解句柄 + panic 兜底。
///
/// 句柄按 [`crate::suites::tag`] 约定:低 3 位是对象种类标签,地址
/// 即对象 props 字段(偏移 0);剥标签后可直接当 PropertySet 用。
/// 裸 PropertySet 指针(标签 0,宿主内部/测试直传)原样通过。
///
/// `# Safety`:`handle` 必须指向活的 `PropertySet` 或已注册对象
/// (suite 生命周期契约:宿主对象先于 suite 调用创建,后于全部调用
/// 销毁)。
#[track_caller]
unsafe fn caught(handle: *mut c_void, f: impl FnOnce(&PropertySet) -> Result<(), c_int>) -> c_int {
let caller = std::panic::Location::caller();
let code = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if handle.is_null() {
return status::ERR_BAD_HANDLE;
}
let set = unsafe { &*crate::suites::tag::strip(handle) };
f(set).map_or_else(|code| code, |()| status::OK)
}))
.unwrap_or(status::FAILED);
if code != status::OK && std::env::var_os("OAK_OFX_TRACE").is_some() {
eprintln!("[ofx] property suite error {code} at {caller}");
}
code
}
/// 属性名:空指针 / 非 UTF-8 → kOfxStatErrValue(防御性;HostSupport
/// 直接解引用会崩)。
///
/// `# Safety`:`name` 必须是有效的 NUL 结尾 C 字符串(插件契约)。
unsafe fn c_name<'a>(name: *const c_char) -> Result<&'a str, c_int> {
if name.is_null() {
return Err(status::ERR_VALUE);
}
unsafe { CStr::from_ptr(name) }
.to_str()
.map_err(|_| status::ERR_VALUE)
}
/// 越界防护:`index` 转 usize(负数 → 越界错误)。
fn idx(index: c_int) -> Result<usize, c_int> {
usize::try_from(index).map_err(|_| status::ERR_BAD_INDEX)
}
/// 先类型后索引的取值(HS 顺序:`fetchTypedProperty` 在
/// `getValueRaw` 之前,ofxhPropertySuite.cpp:787/794/257)。
fn get_value<'a>(
props: &'a [Property],
name: &str,
index: c_int,
kind: Kind,
) -> Result<&'a Value, c_int> {
let result = get_value_inner(props, name, index, kind);
if std::env::var_os("OAK_OFX_TRACE").is_some() {
match &result {
Ok(_) => eprintln!("[ofx] propGet({name}[{index}]) -> ok"),
Err(c) => eprintln!("[ofx] propGet({name}[{index}]) -> {c}"),
}
}
result
}
fn get_value_inner<'a>(
props: &'a [Property],
name: &str,
index: c_int,
kind: Kind,
) -> Result<&'a Value, c_int> {
let p = props
.iter()
.find(|p| p.name == name)
.ok_or(status::ERR_UNKNOWN)?;
// 首元素代理整条属性的类型(宿主只定义同构数组;HS 是定义期
// 固定类型,等价)。空数组没有类型探针,跳过类型检查,越界
// 由下面的索引访问报 BadIndex(HS getValueRaw 语义)。
if let Some(probe) = p.values.first() {
if Kind::of(probe) != kind {
return Err(status::ERR_UNKNOWN);
}
}
p.values.get(idx(index)?).ok_or(status::ERR_BAD_INDEX)
}
// ---- propSet(单元素)-----------------------------------------------------
/// propSet 通用实现:属性未定义时按 OFX 语义**隐式创建**(ofxProperty.h:
/// "If the property does not exist it is created",HS setValue 同)——
/// 插件 describe 期写的大量描述符属性(grouping、各 capability 开关)
/// 并未由宿主预定义,拒绝创建会让 describe 直接失败。已定义但类型
/// 不符 → Unknown;越界 → BadIndex。
fn set_value(set: &PropertySet, name: &str, index: c_int, value: Value) -> Result<(), c_int> {
set.with_locked(|props| {
let idx = idx(index)?;
let Some(p) = props.iter_mut().find(|p| p.name == name) else {
// 隐式创建:维度 index+1,前导槽位以同值填充(HS 的新属性
// 默认值语义——新建属性先有一个默认元素再逐位写)。
let mut values = vec![value.clone(); idx];
values.push(value);
props.push(crate::property::Property {
name: name.to_string(),
values,
});
return Ok(());
};
// 空属性(宿主预定义的空数组,如 OfxImageEffectPropSupportedContexts)
// 没有类型探针:按 HS 的 index == size 追加语义直接 push。
if p.values.is_empty() {
if idx != 0 {
return Err(status::ERR_BAD_INDEX);
}
p.values.push(value);
return Ok(());
}
let probe = &p.values[0];
if Kind::of(probe) != Kind::of(&value) {
return Err(status::ERR_UNKNOWN);
}
// HS `setValue` 允许 index == size 时追加(ofxhPropertySuite.cpp:284)
// ——addSupportedContext 等协商属性正是这样逐位增长的。
if idx == p.values.len() {
p.values.push(value);
return Ok(());
}
let slot = p.values.get_mut(idx).ok_or(status::ERR_BAD_INDEX)?;
*slot = value;
Ok(())
})
}
unsafe extern "C" fn prop_set_pointer(
handle: *mut c_void,
name: *const c_char,
index: c_int,
value: *mut c_void,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
set_value(set, name, index, Value::Pointer(value))
})
}
}
unsafe extern "C" fn prop_set_string(
handle: *mut c_void,
name: *const c_char,
index: c_int,
value: *const c_char,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if value.is_null() {
return Err(status::ERR_VALUE);
}
// C 语义:截断到首个 NUL;CString::new 不会失败
//(from_ptr 已保证 NUL 结尾)。
let s = CString::new(CStr::from_ptr(value).to_bytes()).unwrap();
set_value(set, name, index, Value::String(s))
})
}
}
unsafe extern "C" fn prop_set_double(
handle: *mut c_void,
name: *const c_char,
index: c_int,
value: c_double,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
set_value(set, name, index, Value::Double(value))
})
}
}
unsafe extern "C" fn prop_set_int(
handle: *mut c_void,
name: *const c_char,
index: c_int,
value: c_int,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
set_value(set, name, index, Value::Int(value))
})
}
}
// ---- propSetN(批量)------------------------------------------------------
/// 从 C 数组读出 `count` 个元素并整体写入;count != 现有维度时
/// 整体替换(HS `setValueN` 的 resize 语义,ofxhPropertySuite.cpp:299-311)。
fn set_values(
set: &PropertySet,
name: &str,
count: c_int,
values: Vec<Value>,
) -> Result<(), c_int> {
set.with_locked(|props| {
let Some(p) = props.iter_mut().find(|p| p.name == name) else {
// 与单元素 set_value 一致:未定义属性按 OFX 语义隐式创建。
props.push(crate::property::Property {
name: name.to_string(),
values,
});
return Ok(());
};
// count == 0 时无类型可探(HS 仍会做 fetchTypedProperty)。
if let Some(first) = p.values.first() {
if let Some(v) = values.first() {
if Kind::of(first) != Kind::of(v) {
return Err(status::ERR_UNKNOWN);
}
}
}
let count = idx(count)?;
if count != p.values.len() {
// 维度变化:整体替换(HS 是 resize + 逐位写,等价)。
p.values = values;
} else {
for (i, v) in values.into_iter().enumerate() {
p.values[i] = v;
}
}
Ok(())
})
}
unsafe extern "C" fn prop_set_pointer_n(
handle: *mut c_void,
name: *const c_char,
count: c_int,
values: *const *mut c_void,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if count > 0 && values.is_null() {
return Err(status::ERR_VALUE);
}
let vals = (0..idx(count)?)
.map(|i| Value::Pointer(*values.add(i)))
.collect();
set_values(set, name, count, vals)
})
}
}
unsafe extern "C" fn prop_set_string_n(
handle: *mut c_void,
name: *const c_char,
count: c_int,
values: *const *const c_char,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if count > 0 && values.is_null() {
return Err(status::ERR_VALUE);
}
let mut vals = Vec::with_capacity(count.max(0) as usize);
for i in 0..idx(count)? {
let v = *values.add(i);
if v.is_null() {
return Err(status::ERR_VALUE);
}
vals.push(Value::String(
CString::new(CStr::from_ptr(v).to_bytes()).unwrap(),
));
}
set_values(set, name, count, vals)
})
}
}
unsafe extern "C" fn prop_set_double_n(
handle: *mut c_void,
name: *const c_char,
count: c_int,
values: *const c_double,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if count > 0 && values.is_null() {
return Err(status::ERR_VALUE);
}
let vals = (0..idx(count)?)
.map(|i| Value::Double(*values.add(i)))
.collect();
set_values(set, name, count, vals)
})
}
}
unsafe extern "C" fn prop_set_int_n(
handle: *mut c_void,
name: *const c_char,
count: c_int,
values: *const c_int,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if count > 0 && values.is_null() {
return Err(status::ERR_VALUE);
}
let vals = (0..idx(count)?)
.map(|i| Value::Int(*values.add(i)))
.collect();
set_values(set, name, count, vals)
})
}
}
// ---- propGet(单元素)-----------------------------------------------------
/// 非字符串标量读取(克隆值写出;字符串走内驻指针路径)。
fn get_scalar(set: &PropertySet, name: &str, index: c_int, kind: Kind) -> Result<Value, c_int> {
set.with_locked(|props| get_value(props, name, index, kind).cloned())
}
unsafe extern "C" fn prop_get_pointer(
handle: *mut c_void,
name: *const c_char,
index: c_int,
out: *mut *mut c_void,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if out.is_null() {
return Err(status::ERR_VALUE);
}
let v = get_scalar(set, name, index, Kind::Pointer)?;
match v {
Value::Pointer(p) => {
*out = p;
Ok(())
}
_ => Err(status::FAILED),
}
})
}
}
/// propGetString:写**内驻** C 串指针(OFX 契约:指向宿主内部存储,
/// 属性被下次修改前有效;克隆的 CString 指针会悬垂,绝不能给插件)。
fn get_string(set: &PropertySet, name: &str, index: c_int) -> Result<*mut c_char, c_int> {
set.with_locked(|props| match get_value(props, name, index, Kind::Str)? {
Value::String(s) => Ok(s.as_ptr() as *mut c_char),
_ => Err(status::FAILED),
})
}
unsafe extern "C" fn prop_get_string(
handle: *mut c_void,
name: *const c_char,
index: c_int,
out: *mut *mut c_char,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if out.is_null() {
return Err(status::ERR_VALUE);
}
let r = get_string(set, name, index);
if std::env::var_os("OAK_OFX_TRACE").is_some() {
let status = match &r {
Ok(_) => 0,
Err(c) => *c,
};
eprintln!("[ofx] propGetString(h={handle:p}, {name}[{index}]) -> {status}");
}
*out = r?;
Ok(())
})
}
}
unsafe extern "C" fn prop_get_double(
handle: *mut c_void,
name: *const c_char,
index: c_int,
out: *mut c_double,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if out.is_null() {
return Err(status::ERR_VALUE);
}
let v = get_scalar(set, name, index, Kind::Double)?;
match v {
Value::Double(d) => {
*out = d;
Ok(())
}
_ => Err(status::FAILED),
}
})
}
}
unsafe extern "C" fn prop_get_int(
handle: *mut c_void,
name: *const c_char,
index: c_int,
out: *mut c_int,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if out.is_null() {
return Err(status::ERR_VALUE);
}
let v = get_scalar(set, name, index, Kind::Int)?;
match v {
Value::Int(i) => {
*out = i;
Ok(())
}
_ => Err(status::FAILED),
}
.map_err(|c| {
if std::env::var_os("OAK_OFX_TRACE").is_some() {
eprintln!("[ofx] propGetInt({name}) -> {c}");
}
c
})
})
}
}
// ---- propGetN(批量)------------------------------------------------------
/// 批量读取:拷贝 min(count, dimension) 个(HS `getValueNRaw`,
/// ofxhPropertySuite.cpp:271-280,不报错)。
fn get_n(
set: &PropertySet,
name: &str,
count: c_int,
kind: Kind,
write: impl Fn(&Value, usize),
) -> Result<(), c_int> {
set.with_locked(|props| {
let p = props
.iter()
.find(|p| p.name == name)
.ok_or(status::ERR_UNKNOWN)?;
let probe = p.values.first().ok_or(status::ERR_UNKNOWN)?;
if Kind::of(probe) != kind {
return Err(status::ERR_UNKNOWN);
}
let n = idx(count)?.min(p.values.len());
for (i, v) in p.values.iter().take(n).enumerate() {
write(v, i);
}
Ok(())
})
}
unsafe extern "C" fn prop_get_pointer_n(
handle: *mut c_void,
name: *const c_char,
count: c_int,
out: *mut *mut c_void,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if count > 0 && out.is_null() {
return Err(status::ERR_VALUE);
}
get_n(set, name, count, Kind::Pointer, |v, i| match v {
Value::Pointer(p) => *out.add(i) = *p,
_ => {}
})
})
}
}
unsafe extern "C" fn prop_get_string_n(
handle: *mut c_void,
name: *const c_char,
count: c_int,
out: *mut *mut c_char,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if count > 0 && out.is_null() {
return Err(status::ERR_VALUE);
}
get_n(set, name, count, Kind::Str, |v, i| match v {
Value::String(s) => *out.add(i) = s.as_ptr() as *mut c_char,
_ => {}
})
})
}
}
unsafe extern "C" fn prop_get_double_n(
handle: *mut c_void,
name: *const c_char,
count: c_int,
out: *mut c_double,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if count > 0 && out.is_null() {
return Err(status::ERR_VALUE);
}
get_n(set, name, count, Kind::Double, |v, i| match v {
Value::Double(d) => *out.add(i) = *d,
_ => {}
})
})
}
}
unsafe extern "C" fn prop_get_int_n(
handle: *mut c_void,
name: *const c_char,
count: c_int,
out: *mut c_int,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if count > 0 && out.is_null() {
return Err(status::ERR_VALUE);
}
get_n(set, name, count, Kind::Int, |v, i| match v {
Value::Int(d) => *out.add(i) = *d,
_ => {}
})
})
}
}
// ---- propReset / propGetDimension -----------------------------------------
unsafe extern "C" fn prop_reset(handle: *mut c_void, name: *const c_char) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
// HS `reset()` 恢复到 define 时的默认值
// (ofxhPropertySuite.cpp:330);本 crate 不保存默认值快照,
// 第 1 期明确不支持(见模块文档)。
let _ = (set, name);
Err(status::ERR_UNSUPPORTED)
})
}
}
unsafe extern "C" fn prop_get_dimension(
handle: *mut c_void,
name: *const c_char,
out: *mut c_int,
) -> c_int {
unsafe {
caught(handle, |set| {
let name = c_name(name)?;
if out.is_null() {
return Err(status::ERR_VALUE);
}
// HS: fetchProperty 失败(未定义)→ Unknown(ofxhPropertySuite.cpp:992);
// 已定义的空数组(如协商属性的初始状态)是合法维度 0,不是错误。
let exists = set.with_locked(|props| props.iter().any(|p| p.name == name));
if !exists {
return Err(status::ERR_UNKNOWN);
}
*out = set.dimension(name) as c_int;
Ok(())
})
}
}
/// 静态函数表实例(fetch_suite 返回其地址)。
pub fn suite_v1() -> &'static PropertySuiteV1 {
static SUITE: std::sync::OnceLock<PropertySuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| PropertySuiteV1 {
set_pointer: prop_set_pointer,
set_string: prop_set_string,
set_double: prop_set_double,
set_int: prop_set_int,
set_pointer_n: prop_set_pointer_n,
set_string_n: prop_set_string_n,
set_double_n: prop_set_double_n,
set_int_n: prop_set_int_n,
get_pointer: prop_get_pointer,
get_string: prop_get_string,
get_double: prop_get_double,
get_int: prop_get_int,
get_pointer_n: prop_get_pointer_n,
get_string_n: prop_get_string_n,
get_double_n: prop_get_double_n,
get_int_n: prop_get_int_n,
reset: prop_reset,
get_dimension: prop_get_dimension,
})
}
+197
View File
@@ -0,0 +1,197 @@
// 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/>.
//! OfxTimeLineSuite v1:时间查询转发到当前渲染上下文
//! ([`crate::suites::RenderCtx`],frame range 来自 clip 桥)。
//! 参照 HS: ofxhImageEffect.cpp gTimelineSuite。
//!
//! 无渲染上下文(渲染外调用)→ 回退 app 注入的活动 viewer 时间源
//! ([`set_active_viewer_provider`],阶段 6a 注入点);也未注入则
//! 时间 0 / 时间域 (0,0) 的 headless 默认。gotoTime 第 1 期无时间线
//! 驱动 → OK no-op(渲染时间由驱动固定,见
//! [`crate::suites::set_render_ctx`])。
use std::ffi::{c_double, c_int, c_void};
use std::sync::{Arc, Mutex, OnceLock};
use crate::suites::{render_ctx, status};
// ---------------------------------------------------------------------------
// app 注入点:活动 viewer 时间源
// ---------------------------------------------------------------------------
/// 活动 viewer 的时间信息(timeline suite 渲染外回退源的最小集)。
#[derive(Clone, Copy, Debug)]
pub struct ViewerTimeInfo {
/// viewer 当前时间(秒)。
pub time: f64,
/// 时间域下界(秒)。
pub range_min: f64,
/// 时间域上界(秒)。
pub range_max: f64,
}
/// 活动 viewer 提供器:返回 None 表示当前无活动 viewer。
pub type ActiveViewerProvider = Arc<dyn Fn() -> Option<ViewerTimeInfo> + Send + Sync>;
static ACTIVE_VIEWER: OnceLock<Mutex<Option<ActiveViewerProvider>>> = OnceLock::new();
fn viewer_slot() -> &'static Mutex<Option<ActiveViewerProvider>> {
ACTIVE_VIEWER.get_or_init(|| Mutex::new(None))
}
/// 注册/清除活动 viewer 提供器(app 接线点;覆盖式)。
pub fn set_active_viewer_provider(provider: Option<ActiveViewerProvider>) {
*viewer_slot().lock().unwrap_or_else(|e| e.into_inner()) = provider;
}
fn active_viewer() -> Option<ViewerTimeInfo> {
let provider = viewer_slot()
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()?;
provider()
}
/// 函数表布局(OfxTimeLineSuiteV1)。
#[repr(C)]
pub struct TimeLineSuiteV1 {
/// getTime
pub get_time: unsafe extern "C" fn(*mut c_void, *mut c_double) -> c_int,
/// gotoTime
pub goto_time: unsafe extern "C" fn(*mut c_void, c_double) -> c_int,
/// getTimeBounds
pub get_time_bounds: unsafe extern "C" fn(*mut c_void, *mut c_double, *mut c_double) -> c_int,
}
/// 公共入口模板:handle 空检查 + panic 兜底。
unsafe fn caught(handle: *mut c_void, f: impl FnOnce() -> c_int) -> c_int {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if handle.is_null() {
return status::ERR_BAD_HANDLE;
}
f()
}))
.unwrap_or(status::FAILED)
}
unsafe extern "C" fn timeline_get_time(handle: *mut c_void, time: *mut c_double) -> c_int {
unsafe {
caught(handle, || {
if time.is_null() {
return status::ERR_VALUE;
}
// 渲染上下文 → 活动 viewer → 0(headless 默认)。
*time = render_ctx()
.map(|c| c.time)
.or_else(|| active_viewer().map(|v| v.time))
.unwrap_or(0.0);
status::OK
})
}
}
/// gotoTime:第 1 期宿主不随插件移动时间线(渲染时间由驱动固定),
/// OK no-op。
unsafe extern "C" fn timeline_goto_time(handle: *mut c_void, _time: c_double) -> c_int {
unsafe { caught(handle, || status::OK) }
}
unsafe extern "C" fn timeline_get_time_bounds(
handle: *mut c_void,
min: *mut c_double,
max: *mut c_double,
) -> c_int {
unsafe {
caught(handle, || {
if min.is_null() || max.is_null() {
return status::ERR_VALUE;
}
// 渲染上下文 → 活动 viewer → (0,0)(headless 默认)。
let r = render_ctx()
.map(|c| (c.range.min, c.range.max))
.or_else(|| active_viewer().map(|v| (v.range_min, v.range_max)))
.unwrap_or((0.0, 0.0));
*min = r.0;
*max = r.1;
status::OK
})
}
}
/// 静态函数表实例。
pub fn suite_v1() -> &'static TimeLineSuiteV1 {
static SUITE: std::sync::OnceLock<TimeLineSuiteV1> = std::sync::OnceLock::new();
SUITE.get_or_init(|| TimeLineSuiteV1 {
get_time: timeline_get_time,
goto_time: timeline_goto_time,
get_time_bounds: timeline_get_time_bounds,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::instance::{OfxRangeD, RenderScale};
use crate::suites::{set_render_ctx, RenderCtx};
#[test]
fn queries_forward_to_render_ctx() {
let s = suite_v1();
let handle = 0x10usize as *mut c_void;
let mut t = 0.0;
let mut min = 0.0;
let mut max = 0.0;
// 无上下文:0 / (0,0)。
unsafe {
assert_eq!((s.get_time)(handle, &mut t), status::OK);
assert_eq!(t, 0.0);
assert_eq!((s.get_time_bounds)(handle, &mut min, &mut max), status::OK);
assert_eq!((min, max), (0.0, 0.0));
}
// 有上下文:转发。
set_render_ctx(Some(RenderCtx {
time: 42.5,
scale: RenderScale { x: 1.0, y: 1.0 },
range: OfxRangeD {
min: 10.0,
max: 200.0,
},
}));
unsafe {
assert_eq!((s.get_time)(handle, &mut t), status::OK);
assert_eq!(t, 42.5);
assert_eq!((s.get_time_bounds)(handle, &mut min, &mut max), status::OK);
assert_eq!((min, max), (10.0, 200.0));
assert_eq!((s.goto_time)(handle, 99.0), status::OK);
}
set_render_ctx(None);
// 空 handle / 空 out。
unsafe {
assert_eq!(
(s.get_time)(std::ptr::null_mut(), &mut t),
status::ERR_BAD_HANDLE
);
assert_eq!(
(s.get_time)(handle, std::ptr::null_mut()),
status::ERR_VALUE
);
}
}
}