refactor: workspace layout — crates/, app at root, legacy C++ removed

Single mechanical restructure commit:
- root Cargo.toml = oakapp bin + workspace; one cargo build produces
  oakapp, oak-cli, oak-worker, liboakengine.dylib
- app/rust/src -> src/ (app at repo root, no rust/ nesting)
- src/<mod>/rust -> crates/oak<mod>; src/oakcore-rs -> crates/oakcore;
  src/bindings/oakotio -> crates/oakotio; src/engine/rust ->
  crates/oakengine (keeps cdylib+staticlib+rlib)
- public C headers include/<mod>/ -> crates/oakengine/include/<mod>/
- OFX SDK headers vendored into crates/oakplugin/ofx/ (HostSupport gone)
- legacy deleted: old src/ C++ modules, engine/, core/, ffmpeg_bridge/,
  app/ (Qt), cli/worker C++, root CMakeLists, third_party/KDDockWidgets
  submodule, otio-install, all build-* output (~40GB)
- oakstorage kept but excluded from the workspace (skeleton w/ todos);
  gpui excluded (own workspace)
- verified: cargo build green, cargo test --workspace 1845/0
  (with the documented OCIO_RS_* env override for the homebrew OCIO)
This commit is contained in:
2026-08-10 20:24:25 +08:00
parent f8540e3892
commit 013a175707
4212 changed files with 8331 additions and 2274987 deletions
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "oakcore-rs"
version = "0.1.0"
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "oakcore-rs"
version = "0.1.0"
edition = "2021"
description = "Rust value types mirroring oakcore (Rational, TimeRange, format enums)"
license = "GPL-3.0-or-later"
[lib]
crate-type = ["rlib"]
[dependencies]
+20
View File
@@ -0,0 +1,20 @@
# oakcore-rs — Rust value-type foundation for the oak Rust modules
> Status: **declaration draft for review** (no implementation, not wired
> into any build). Companion to `crates/oaknode` and `crates/oakrender`.
Rust reimplementation of the oakcore C++ value types that cross every
module boundary: `Rational`, `TimeRange`, `TimeRangeList`, pixel/sample
format enums. These are pure data types with value semantics — the one
place where duplicating the C++ layout discipline in plain Rust is both
safe and required (a Rust crate cannot hold C++ objects by value).
Rules:
- Bit-exact arithmetic compatibility with `olive::core::Rational`
(reduction, overflow behavior, comparison) — the golden rule is the
C++ test-suite semantics, not "ideal" rational math.
- `#[repr(C)]` only where a type crosses the C ABI; everything else is
plain Rust with `Copy + Clone + Eq + Hash`.
- No I/O, no allocation in arithmetic paths, no panics on degenerate
input (denominator zero follows the C++ sentinel semantics).
+95
View File
@@ -0,0 +1,95 @@
// 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/>.
//! The shared ABI value-handle type (single-lib unification).
//!
//! Every module crate used to define its own `CHandle` with an identical
//! `{ctx, addref, release, abi_version}` layout but a distinct Rust type,
//! so cross-module calls had to cross an `extern "C"`/dlsym boundary.
//! With the module-to-module calls going back to direct Rust calls (see
//! `docs/zh/plans/riir/single-lib.md`), one canonical handle type lives
//! here in `oakcore-rs` (the crate every module already depends on) and
//! every crate re-exports it. The C layout is unchanged, so the frozen
//! module C ABIs (`Oak<Mod><Type>*` handles in `include/<mod>/*.h`) are
//! unaffected.
use std::ffi::c_void;
/// ABI value handle mirroring the C handle struct
/// (`{ctx, addref, release, abi_version}`) from `include/common/handle.h`.
///
/// `ctx` points to an opaque refcounted box; `addref`/`release` are the
/// box's atomic increment/decrement (release destroys at zero);
/// `abi_version` is a tag stamped by each crate's `make_owned` (0 for
/// empty handles). Structurally identical to every `Oak<Mod><Type>` value
/// handle, so a handle can cross any module boundary by value.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CHandle {
/// Opaque box pointer.
pub ctx: *mut c_void,
/// Atomic increment.
pub addref: Option<unsafe extern "C" fn(*mut c_void)>,
/// Atomic decrement; destroys at zero.
pub release: Option<unsafe extern "C" fn(*mut c_void)>,
/// ABI version.
pub abi_version: u32,
}
impl CHandle {
/// The empty handle.
pub const fn null() -> Self {
CHandle {
ctx: std::ptr::null_mut(),
addref: None,
release: None,
abi_version: 0,
}
} /// Whether this is the empty (zero) handle.
pub fn is_null(&self) -> bool {
self.ctx.is_null()
}
/// Take an additional reference through the handle's `addref` and
/// return the (now refcount-incremented) copy.
///
/// # Safety
/// `self` must be a live handle returned by a module function.
pub unsafe fn addref(&self) -> Self {
let mut copy = *self;
if let Some(addref) = copy.addref {
let _ = &mut copy;
unsafe {
addref(copy.ctx);
}
}
copy
}
}
/// The empty handle is the natural default (some crates derive `Default`
/// on structs holding a handle).
impl Default for CHandle {
fn default() -> Self {
Self::null()
}
}
// Handles follow the shared_ptr-like convention of
// `include/common/handle.h`: they are opaque, refcounted and safe to
// share across threads (the module crates use them behind mutexes).
unsafe impl Send for CHandle {}
unsafe impl Sync for CHandle {}
+34
View File
@@ -0,0 +1,34 @@
// 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/>.
//! oakcore-rs: Rust value types mirroring the oakcore C++ library.
//!
//! Bit-exact behavioral compatibility with `olive::core` is the design
//! constraint; see README.md.
#![warn(missing_docs)]
mod rational;
mod samplefmt;
mod timerange;
/// Shared ABI value-handle type (see [`handle::CHandle`]).
pub mod handle;
pub use handle::CHandle;
pub use rational::Rational;
pub use samplefmt::{PixelFormat, SampleFormat};
pub use timerange::{TimeRange, TimeRangeList};
+481
View File
@@ -0,0 +1,481 @@
// 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/>.
//! Rational numbers with oakcore-compatible semantics.
/// The cap used by the C++ `reduce_fraction` oracle: it reduces against
/// `INT_MAX` regardless of the wider integer width. We keep the same cap so
/// that every value C++ can represent round-trips bit-for-bit.
const REDUCE_MAX: i128 = i32::MAX as i128;
/// `RATIONAL_MIN` as produced by the C++ `Rational(INT_MIN)` constructor:
/// because the reduce cap is `INT_MAX`, `INT_MIN` reduces to `-2147483647/1`
/// (not `-2147483648/1`). Arithmetic treats this value (and its positive
/// counterpart) as a sentinel that propagates NaN.
const RATIONAL_MIN: Rational = Rational { num: -2147483647, den: 1 };
/// `RATIONAL_MAX` (`Rational(INT_MAX)`, i.e. `2147483647/1`).
const RATIONAL_MAX: Rational = Rational { num: 2147483647, den: 1 };
/// A rational number, always kept reduced with a non-negative
/// denominator (mirrors `olive::core::Rational`).
///
/// Compatibility notes (these are load-bearing, project files depend
/// on them):
/// - `0/0` is the "null/invalid" sentinel (`Rational()` in C++).
/// - Arithmetic follows the C++ overflow behavior: intermediate
/// products are 128-bit where the C++ uses wider temporaries; where
/// C++ truncates, we truncate identically.
/// - `from_string`/`to_string` round-trip the exact C++ text format
/// (e.g. "30000/1001"), including the sentinel spellings used in
/// project XML ("0/0", RATIONAL_MIN/MAX sentinels).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub struct Rational {
num: i64,
den: i64,
}
/// Signed Euclidean GCD on absolute values (mirrors the C++
/// `i64_gcd`). Computed in `i128` so that `i64::MIN`-class inputs
/// cannot overflow when negated.
fn i64_gcd(mut a: i128, mut b: i128) -> i128 {
if a < 0 {
a = -a;
}
if b < 0 {
b = -b;
}
while b != 0 {
let t = a % b;
a = b;
b = t;
}
a
}
/// Reduce `num`/`den` in place so that `|num| <= max` and `den <= max`,
/// using the exact C++ algorithm (`core/src/util/fractionutils.cpp`,
/// ported from FFmpeg's `av_reduce`). Implemented in `i128` so the
/// intermediate products never overflow for any `i64` input.
fn reduce_fraction(num: &mut i128, den: &mut i128, max: i128) {
if *den == 0 {
*num = 0;
return;
}
let sign = (*num < 0) != (*den < 0);
let gcd = i64_gcd(*num, *den);
if gcd != 0 {
*num = if *num < 0 { -*num } else { *num } / gcd;
*den = if *den < 0 { -*den } else { *den } / gcd;
}
if *num <= max && *den <= max {
*num = if sign { -*num } else { *num };
return;
}
// Continued fraction approximation (FFmpeg's av_reduce).
let mut a0n: i128 = 0;
let mut a0d: i128 = 1;
let mut a1n: i128 = 1;
let mut a1d: i128 = 0;
let mut n = *num;
let mut d = *den;
while d != 0 {
let x = n / d;
let next_den = n - d * x;
let a2n = x * a1n + a0n;
let a2d = x * a1d + a0d;
if a2n > max || a2d > max {
let mut x = x;
if a1n != 0 {
x = (max - a0n) / a1n;
}
if a1d != 0 && (max - a0d) / a1d < x {
x = (max - a0d) / a1d;
}
if d * (2 * x * a1d + a0d) > n * a1d {
a1n = x * a1n + a0n;
a1d = x * a1d + a0d;
}
break;
}
a0n = a1n;
a0d = a1d;
a1n = a2n;
a1d = a2d;
n = d;
d = next_den;
}
*num = if sign { -a1n } else { a1n };
*den = a1d;
}
/// C `frexp`: split into mantissa in [0.5, 1) and base-2 exponent.
/// Only used by `from_double`; NaN/inf/zero pass through with exp 0.
fn frexp(x: f64, exp: &mut i32) -> f64 {
if x == 0.0 || x.is_nan() || x.is_infinite() {
*exp = 0;
return x;
}
let bits = x.to_bits();
let raw = ((bits >> 52) & 0x7ff) as i32;
if raw == 0 {
// Subnormal: scale up into the normal range first.
let scaled = x * 9007199254740992.0; // 2^53
let mut e = 0;
let m = frexp(scaled, &mut e);
*exp = e - 53;
return m;
}
*exp = raw - 1022;
f64::from_bits((bits & !(0x7ffu64 << 52)) | (1022u64 << 52))
}
/// Apply C++ `fix_signs`: negative denominators are normalized by
/// flipping both signs; `0/0` stays as the NaN sentinel; a zero
/// numerator becomes `0/1`.
fn fix_signs(num: &mut i64, den: &mut i64) {
if *den < 0 {
*den = -*den;
*num = -*num;
} else if *den == 0 {
*num = 0;
} else if *num == 0 {
*den = 1;
}
}
/// Build a rational from already-reduced `i128` values, applying
/// `fix_signs` and narrowing to `i64` (safe: `reduce_fraction` caps at
/// `i32::MAX`).
fn from_reduced(num: i128, den: i128) -> Rational {
let mut num = num as i64;
let mut den = den as i64;
fix_signs(&mut num, &mut den);
Rational { num, den }
}
/// Compare two fractions exactly (C++ `compare_fractions`). Non-NaN
/// inputs yield `-1`/`0`/`1`; the `0/0` cases return `i32::MIN`
/// (meaningless, never used for total ordering).
fn compare_fractions(an: i64, ad: i64, bn: i64, bd: i64) -> i32 {
let tmp = an as i128 * bd as i128 - bn as i128 * ad as i128;
if tmp != 0 {
// C++: `((tmp ^ ad ^ bd) >> 63) | 1` == sign of tmp (dens are >= 0).
if tmp > 0 {
1
} else {
-1
}
} else if bd != 0 && ad != 0 {
0
} else if an != 0 && bn != 0 {
((an >> 31) - (bn >> 31)) as i32
} else {
i32::MIN
}
}
/// Parse a single C++ `strtol`-style integer (base 10); garbage or
/// empty input yields 0.
fn to_int(s: &str) -> i64 {
s.trim().parse::<i64>().unwrap_or(0)
}
/// Rounding modes for the C++ `Timecode` conversion helpers.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Rounding {
Round,
Floor,
}
/// C++ `Rational::flipped` as a free function: swap numerator and
/// denominator, then `fix_signs`. A null rational (0/0 or 0/n) is left
/// unchanged.
fn flipped(r: Rational) -> Rational {
if r.num == 0 {
return r;
}
let mut num = r.den;
let mut den = r.num;
fix_signs(&mut num, &mut den);
Rational { num, den }
}
/// C++ `Timecode::timestamp_to_time`: `timebase.num * ts / timebase.den`,
/// reduced against `INT_MAX`.
fn timestamp_to_time(ts: i64, timebase: Rational) -> Rational {
let mut num = timebase.num as i128 * ts as i128;
let mut den = timebase.den as i128;
reduce_fraction(&mut num, &mut den, REDUCE_MAX);
from_reduced(num, den)
}
/// C++ `Timecode::time_to_timestamp` (any rounding mode), given an
/// explicit timebase.
pub(crate) fn time_to_timestamp_rnd(time: Rational, timebase: Rational, rnd: Rounding) -> i64 {
let d = time.to_f64() * flipped(timebase).to_f64();
if d.is_nan() {
return 0;
}
let eps = 0.000000000001;
match rnd {
Rounding::Round => d.round() as i64,
Rounding::Floor => {
if d > d.ceil() - eps {
d.ceil() as i64
} else {
d.floor() as i64
}
}
}
}
/// C++ `Timecode::snap_time_to_timebase` with the `k_floor` rounding
/// used by `TimeRangeListFrameIterator`.
pub(crate) fn snap_time_to_timebase(time: Rational, timebase: Rational) -> Rational {
let ts = time_to_timestamp_rnd(time, timebase, Rounding::Floor);
timestamp_to_time(ts, timebase)
}
impl Rational {
/// The invalid sentinel (C++ `Rational()`, i.e. 0/0).
pub const NULL: Rational = Rational { num: 0, den: 0 };
/// Construct reduced; `new(0, 0)` yields [`Rational::NULL`].
pub fn new(num: i64, den: i64) -> Rational {
let mut num = num;
let mut den = den;
fix_signs(&mut num, &mut den);
let mut num = num as i128;
let mut den = den as i128;
reduce_fraction(&mut num, &mut den, REDUCE_MAX);
Rational {
num: num as i64,
den: den as i64,
}
}
/// Numerator of the reduced form.
pub fn numerator(self) -> i64 {
self.num
}
/// Denominator of the reduced form (0 for the null sentinel).
pub fn denominator(self) -> i64 {
self.den
}
/// True for the null sentinel (`num == 0`, so 0/0 and 0/1).
pub fn is_null(self) -> bool {
self.num == 0
}
/// True for the NaN sentinel (`den == 0`, only 0/0 after
/// normalization). C++ `isNaN()`.
pub fn is_nan(self) -> bool {
self.den == 0
}
/// True when this value equals `RATIONAL_MIN` or `RATIONAL_MAX`
/// (the sentinels that propagate NaN through arithmetic in C++).
fn is_minmax(self) -> bool {
self == RATIONAL_MIN || self == RATIONAL_MAX
}
/// Parse the C++ text format; invalid input yields the null
/// sentinel (C++ `fromString` behavior).
pub fn from_string(s: &str) -> Rational {
let elements: Vec<&str> = s.split('/').collect();
match elements.len() {
1 => Rational::new(to_int(elements[0]), 1),
2 => Rational::new(to_int(elements[0]), to_int(elements[1])),
_ => Rational::NULL,
}
}
/// Format identical to C++ `toString()`.
pub fn to_display_string(self) -> String {
format!("{}/{}", self.num, self.den)
}
/// Truncating conversion to f64 (C++ `toDouble`).
pub fn to_f64(self) -> f64 {
if self.den != 0 {
self.num as f64 / self.den as f64
} else {
f64::NAN
}
}
/// f64 → Rational (C++ `Rational::from_double`, continued-fraction
/// port of FFmpeg's `av_d2q`; NaN and |v| > INT_MAX+3 yield the
/// 0/0 NaN sentinel).
/// `// CPP-PARITY: core/src/util/rational.cpp:39`
pub fn from_double(value: f64) -> Rational {
if value.is_nan() || value.abs() > i32::MAX as f64 + 3.0 {
return Rational::NULL;
}
let mut exponent = 0;
let _ = frexp(value, &mut exponent);
exponent = (exponent - 1).max(0);
let den: i64 = 1i64 << (62 - exponent);
let num: i64 = (value * den as f64 + 0.5).floor() as i64;
let mut rnum = num as i128;
let mut rden = den as i128;
reduce_fraction(&mut rnum, &mut rden, i32::MAX as i128);
if (rnum == 0 || rden == 0) && value != 0.0 {
// Too small to represent above; retry at maximum precision.
rnum = (value * i64::MAX as f64) as i64 as i128;
rden = i64::MAX as i128;
reduce_fraction(&mut rnum, &mut rden, i32::MAX as i128);
}
from_reduced(rnum, rden)
}
/// Frame-number conversion using this value as a timebase
/// (C++ `Timecode::time_to_timestamp` semantics, rounding mode
/// included).
pub fn time_to_timestamp(self, time: Rational) -> i64 {
time_to_timestamp_rnd(time, self, Rounding::Round)
}
/// Inverse of [`Rational::time_to_timestamp`]
/// (C++ `Timecode::timestamp_to_time`).
pub fn timestamp_to_time(self, ts: i64) -> Rational {
timestamp_to_time(ts, self)
}
}
impl std::ops::Add for Rational {
type Output = Rational;
fn add(self, rhs: Rational) -> Rational {
if self.is_minmax() || rhs.is_minmax() {
return Rational::NULL;
}
if self.is_nan() {
return self;
}
if rhs.is_nan() {
return Rational::NULL;
}
let mut n = self.num as i128 * rhs.den as i128 + rhs.num as i128 * self.den as i128;
let mut d = self.den as i128 * rhs.den as i128;
reduce_fraction(&mut n, &mut d, REDUCE_MAX);
from_reduced(n, d)
}
}
impl std::ops::Sub for Rational {
type Output = Rational;
fn sub(self, rhs: Rational) -> Rational {
if self.is_minmax() || rhs.is_minmax() {
return Rational::NULL;
}
if self.is_nan() {
return self;
}
if rhs.is_nan() {
return Rational::NULL;
}
let mut n = self.num as i128 * rhs.den as i128 - rhs.num as i128 * self.den as i128;
let mut d = self.den as i128 * rhs.den as i128;
reduce_fraction(&mut n, &mut d, REDUCE_MAX);
from_reduced(n, d)
}
}
impl std::ops::Mul for Rational {
type Output = Rational;
fn mul(self, rhs: Rational) -> Rational {
if self.is_minmax() || rhs.is_minmax() {
return Rational::NULL;
}
if self.is_nan() {
return self;
}
if rhs.is_nan() {
return Rational::NULL;
}
let mut n = self.num as i128 * rhs.num as i128;
let mut d = self.den as i128 * rhs.den as i128;
reduce_fraction(&mut n, &mut d, REDUCE_MAX);
from_reduced(n, d)
}
}
impl std::ops::Div for Rational {
type Output = Rational;
fn div(self, rhs: Rational) -> Rational {
if self.is_minmax() || rhs.is_minmax() {
return Rational::NULL;
}
if self.is_nan() {
return self;
}
if rhs.is_nan() {
return Rational::NULL;
}
let mut n = self.num as i128 * rhs.den as i128;
let mut d = self.den as i128 * rhs.num as i128;
reduce_fraction(&mut n, &mut d, REDUCE_MAX);
from_reduced(n, d)
}
}
impl PartialOrd for Rational {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Rational {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
use std::cmp::Ordering;
// NaN (0/0) orders before everything and equals itself, keeping
// `Ord` consistent with the derived structural `Eq` (C++ makes
// 0/0 == 0/0 false, but this crate deliberately keeps Eq).
match (self.den == 0, other.den == 0) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Less,
(false, true) => Ordering::Greater,
(false, false) => match compare_fractions(self.num, self.den, other.num, other.den) {
0 => Ordering::Equal,
1 => Ordering::Greater,
_ => Ordering::Less,
},
}
}
}
+145
View File
@@ -0,0 +1,145 @@
// 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/>.
//! Pixel and sample format enums (oakcore `PixelFormat` /
//! `SampleFormat` equivalents). Integer values MUST match the C++
//! enums (`core/include/olive/core/render/pixelformat.h`,
//! `sampleformat.h`) — they cross the C ABI as `int`.
/// Pixel format (values identical to `olive::core::PixelFormat::Format`:
/// invalid=-1, u8=0, u10=1, u16=2, f16=3, f32=4).
#[repr(i32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PixelFormat {
/// Invalid/unspecified.
Invalid = -1,
/// 8-bit unsigned per channel.
U8 = 0,
/// 10-bit unsigned per channel (packed).
U10 = 1,
/// 16-bit unsigned per channel.
U16 = 2,
/// 16-bit half float.
F16 = 3,
/// 32-bit float (primary pipeline format).
F32 = 4,
}
impl PixelFormat {
/// Bytes per channel (C++ `byte_count`; Invalid -> 0, U10 -> 4
/// since it is packed RGBA10A2 stored as 4 bytes per pixel).
pub fn bytes_per_channel(self) -> usize {
match self {
PixelFormat::Invalid => 0,
PixelFormat::U8 => 1,
PixelFormat::U10 => 4,
PixelFormat::U16 | PixelFormat::F16 => 2,
PixelFormat::F32 => 4,
}
}
/// Bytes per pixel for `channels` (C++ `bytes_per_pixel`).
pub fn bytes_per_pixel(self, channels: usize) -> usize {
self.bytes_per_channel() * channels
}
}
/// Audio sample format (values identical to
/// `olive::core::SampleFormat::Format`: PLANAR first — u8_p=0, s16_p=1,
/// s32_p=2, s64_p=3, f32_p=4, f64_p=5, then packed u8=6, s16=7, s32=8,
/// s64=9, f32=10, f64=11). This order is load-bearing: oakaudio's
/// default format constant (f32_p) is 4.
#[repr(i32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SampleFormat {
/// Invalid/unspecified.
Invalid = -1,
/// Unsigned 8-bit planar.
U8Planar = 0,
/// Signed 16-bit planar.
S16Planar = 1,
/// Signed 32-bit planar.
S32Planar = 2,
/// Signed 64-bit planar.
S64Planar = 3,
/// 32-bit float planar.
F32Planar = 4,
/// 64-bit float planar.
F64Planar = 5,
/// Unsigned 8-bit packed.
U8 = 6,
/// Signed 16-bit packed.
S16 = 7,
/// Signed 32-bit packed.
S32 = 8,
/// Signed 64-bit packed.
S64 = 9,
/// 32-bit float packed.
F32 = 10,
/// 64-bit float packed.
F64 = 11,
}
impl SampleFormat {
/// Bytes per sample (C++ `byte_count`; Invalid -> 0).
pub fn bytes_per_sample(self) -> usize {
match self {
SampleFormat::Invalid => 0,
SampleFormat::U8Planar | SampleFormat::U8 => 1,
SampleFormat::S16Planar | SampleFormat::S16 => 2,
SampleFormat::S32Planar
| SampleFormat::S32
| SampleFormat::F32Planar
| SampleFormat::F32 => 4,
SampleFormat::S64Planar
| SampleFormat::S64
| SampleFormat::F64Planar
| SampleFormat::F64 => 8,
}
}
/// True for planar layouts (C++ `is_planar`).
pub fn is_planar(self) -> bool {
(self as i32) >= 0 && (self as i32) < 6
}
/// Packed counterpart of a planar format (and vice versa;
/// C++ `to_packed`/`to_planar`).
pub fn to_packed(self) -> SampleFormat {
match self {
SampleFormat::U8Planar => SampleFormat::U8,
SampleFormat::S16Planar => SampleFormat::S16,
SampleFormat::S32Planar => SampleFormat::S32,
SampleFormat::S64Planar => SampleFormat::S64,
SampleFormat::F32Planar => SampleFormat::F32,
SampleFormat::F64Planar => SampleFormat::F64,
other => other,
}
}
/// See [`SampleFormat::to_packed`].
pub fn to_planar(self) -> SampleFormat {
match self {
SampleFormat::U8 => SampleFormat::U8Planar,
SampleFormat::S16 => SampleFormat::S16Planar,
SampleFormat::S32 => SampleFormat::S32Planar,
SampleFormat::S64 => SampleFormat::S64Planar,
SampleFormat::F32 => SampleFormat::F32Planar,
SampleFormat::F64 => SampleFormat::F64Planar,
other => other,
}
}
}
+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/>.
//! Time ranges and normalized range lists (oakcore `TimeRange` /
//! `TimeRangeList` equivalents).
use crate::rational::{self, Rational};
/// Half-open time range [in, out) — mirrors `olive::core::TimeRange`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub struct TimeRange {
in_: Rational,
out: Rational,
}
impl TimeRange {
/// Construct and normalize (C++ ctor calls `normalize()`: if `out <
/// in` the two are swapped). The doc comment on the skeleton claimed
/// normalization is not performed; matching C++ takes precedence.
pub fn new(in_: Rational, out: Rational) -> TimeRange {
let mut r = TimeRange { in_, out };
r.normalize();
r
}
/// Inclusive start.
pub fn in_(&self) -> Rational {
self.in_
}
/// Exclusive end.
pub fn out(&self) -> Rational {
self.out
}
/// `out - in`. When either endpoint is a `RATIONAL_MIN/MAX`
/// sentinel the subtraction propagates NaN, matching C++ which
/// stores the same sentinel value for `length_`.
pub fn length(&self) -> Rational {
self.out - self.in_
}
/// True when `t` lies in [in, out).
pub fn contains(&self, t: Rational) -> bool {
t >= self.in_ && t < self.out
}
/// True when `self` contains `compare`, honoring inclusivity of the
/// in/out edges (C++ `TimeRange::contains(TimeRange)`).
fn contains_range(
&self,
compare: &TimeRange,
in_inclusive: bool,
out_inclusive: bool,
) -> bool {
let contains_in = if in_inclusive {
compare.in_ >= self.in_
} else {
compare.in_ > self.in_
};
let contains_out = if out_inclusive {
compare.out <= self.out
} else {
compare.out < self.out
};
contains_in && contains_out
}
/// True when `self` and `a` overlap, honoring edge inclusivity
/// (C++ `TimeRange::overlaps_with`).
fn overlaps_with(&self, a: &TimeRange, in_inclusive: bool, out_inclusive: bool) -> bool {
let does_not_overlap_in = if in_inclusive {
a.out < self.in_
} else {
a.out <= self.in_
};
let does_not_overlap_out = if out_inclusive {
a.in_ > self.out
} else {
a.in_ >= self.out
};
!does_not_overlap_in && !does_not_overlap_out
}
/// Intersection; empty when disjoint (C++ `intersected`).
///
/// Note: C++ normalizes the result, so disjoint inputs produce a
/// swapped (in > out) range rather than an "empty" marker; we match
/// that bit-for-bit.
pub fn intersected(&self, other: &TimeRange) -> TimeRange {
TimeRange::new(
std::cmp::max(self.in_, other.in_),
std::cmp::min(self.out, other.out),
)
}
/// Union that also merges touching ranges (C++ `combined`).
pub fn combined(&self, other: &TimeRange) -> TimeRange {
TimeRange::new(
std::cmp::min(self.in_, other.in_),
std::cmp::max(self.out, other.out),
)
}
/// C++ `set_in` + `normalize`.
fn set_in(&mut self, in_: Rational) {
self.in_ = in_;
self.normalize();
}
/// C++ `set_out` + `normalize`.
fn set_out(&mut self, out: Rational) {
self.out = out;
self.normalize();
}
/// C++ `normalize`: swap if `out < in`.
fn normalize(&mut self) {
if self.out < self.in_ {
std::mem::swap(&mut self.out, &mut self.in_);
}
}
}
/// Normalized (sorted, non-overlapping) list of ranges — mirrors
/// `olive::core::TimeRangeList` including its merge-on-insert and
/// subtraction semantics.
#[derive(Clone, Debug, Default)]
pub struct TimeRangeList {
ranges: Vec<TimeRange>,
}
impl TimeRangeList {
/// Empty list.
pub fn new() -> Self {
TimeRangeList { ranges: Vec::new() }
}
/// True when any element fully contains `range` (C++
/// `TimeRangeList::contains`, inclusive edges).
fn contains_range(&self, range: &TimeRange) -> bool {
self.ranges
.iter()
.any(|r| r.contains_range(range, true, true))
}
/// Insert a range, merging overlaps and touching neighbors
/// (C++ `insert(TimeRange)`).
pub fn insert(&mut self, range: TimeRange) {
// If the list already fully contains this range, nothing to do.
if self.contains_range(&range) {
return;
}
let mut range = range;
let mut i = 0;
while i < self.ranges.len() {
let compare = self.ranges[i];
if compare.overlaps_with(&range, true, true) {
range = compare.combined(&range);
self.ranges.remove(i);
} else {
i += 1;
}
}
self.ranges.push(range);
}
/// Subtract a range (C++ `remove`, via `util_remove`).
pub fn remove(&mut self, range: TimeRange) {
let mut additions: Vec<TimeRange> = Vec::new();
let mut i = 0;
while i < self.ranges.len() {
let compare = self.ranges[i];
if range.contains_range(&compare, true, true) {
// The removal range entirely encompasses this element.
self.ranges.remove(i);
} else if compare.contains_range(&range, false, false) {
// The removal range is strictly inside this element:
// split it into two.
let mut new_range = compare;
new_range.set_in(range.out);
let mut trimmed = compare;
trimmed.set_out(range.in_);
self.ranges[i] = trimmed;
additions.push(new_range);
break;
} else {
if compare.in_ < range.in_ && compare.out > range.in_ {
// This element's out overlaps the range's in: trim it.
self.ranges[i].set_out(range.in_);
} else if compare.in_ < range.out && compare.out > range.out {
// This element's in overlaps the range's out: trim it.
self.ranges[i].set_in(range.out);
}
i += 1;
}
}
self.ranges.extend(additions);
}
/// Sorted ranges view.
pub fn ranges(&self) -> &[TimeRange] {
&self.ranges
}
/// True when the list has no ranges.
pub fn is_empty(&self) -> bool {
self.ranges.is_empty()
}
/// Total covered duration (sum of each range's length).
pub fn total_length(&self) -> Rational {
let mut total = Rational::new(0, 1);
for r in &self.ranges {
total = total + r.length();
}
total
}
/// First time covered by any range (C++ `in()` on the first range);
/// null rational when empty.
pub fn first(&self) -> Rational {
match self.ranges.first() {
Some(r) => r.in_(),
None => Rational::NULL,
}
}
/// Frame-accurate iteration helper: snap a time to the containing
/// frame grid of `timebase` (C++ TimeRangeListFrameIterator snap,
/// `k_floor` rounding).
pub fn snap(&self, time: Rational, timebase: Rational) -> Rational {
let _ = self; // self carries no state relevant to a single snap
rational::snap_time_to_timebase(time, timebase)
}
}
+401
View File
@@ -0,0 +1,401 @@
// 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/>.
//! oakcore-rs contract tests. The oracle is the C++ oakcore behavior:
/// every case below names the C++ semantic it pins down.
use oakcore_rs::{PixelFormat, Rational, SampleFormat, TimeRange, TimeRangeList};
/// Construction reduces (2/4 -> 1/2), normalizes sign (1/-2 -> -1/2),
/// and 0/0 is the null sentinel. C++: Rational ctor + reduced().
#[test]
fn rational_reduction_and_sentinel() {
assert_eq!(Rational::new(2, 4), Rational::new(1, 2));
assert_eq!(Rational::new(2, 4).numerator(), 1);
assert_eq!(Rational::new(2, 4).denominator(), 2);
assert_eq!(Rational::new(1, -2), Rational::new(-1, 2));
assert_eq!(Rational::new(1, -2).numerator(), -1);
assert_eq!(Rational::new(1, -2).denominator(), 2);
// 0/0 is the null/invalid sentinel.
let n = Rational::new(0, 0);
assert!(n.is_null());
assert!(n.is_nan());
assert_eq!(n, Rational::NULL);
// A zero numerator normalizes the denominator to 1 (0/5 -> 0/1).
let z = Rational::new(0, 5);
assert!(z.is_null());
assert!(!z.is_nan());
assert_eq!(z, Rational::new(0, 1));
assert_eq!(Rational::NULL, Rational::new(0, 0));
}
/// Arithmetic matches C++ exactly, including 30000/1001-style video
/// rates: (1001/30000 * 30000/1001 == 1), addition across denominators,
/// division by zero yields the C++ result (null propagation).
#[test]
fn rational_arithmetic_video_rates() {
assert_eq!(
Rational::new(1001, 30000) * Rational::new(30000, 1001),
Rational::new(1, 1)
);
assert_eq!(Rational::new(1, 3) + Rational::new(1, 6), Rational::new(1, 2));
assert_eq!(Rational::new(1, 2) - Rational::new(1, 3), Rational::new(1, 6));
assert_eq!(Rational::new(2, 3) * Rational::new(3, 4), Rational::new(1, 2));
// Division by a zero-value rational yields 0/0 (NaN): the denominator
// becomes 0 and reduce_fraction forces the numerator to 0.
let d = Rational::new(1, 1) / Rational::new(0, 1);
assert!(d.is_nan());
assert!(d.is_null());
assert_eq!(d, Rational::NULL);
// 0/0 on the left propagates the (unchanged) NaN self.
assert_eq!(Rational::NULL + Rational::new(1, 2), Rational::NULL);
// 0/0 on the right yields NULL for every operator.
assert_eq!(Rational::new(1, 2) + Rational::NULL, Rational::NULL);
assert_eq!(Rational::new(1, 2) - Rational::NULL, Rational::NULL);
assert_eq!(Rational::new(1, 2) * Rational::NULL, Rational::NULL);
assert_eq!(Rational::new(1, 2) / Rational::NULL, Rational::NULL);
}
/// from_string/to_string round-trip incl. sentinel spellings used by
/// project XML ("0/0", RATIONAL_MIN/MAX); garbage input -> null.
#[test]
fn rational_string_roundtrip() {
assert_eq!(Rational::from_string("0/0"), Rational::NULL);
assert_eq!(
Rational::from_string("2147483647"),
Rational::new(2147483647, 1)
);
assert_eq!(
Rational::from_string("-2147483647/1"),
Rational::new(-2147483647, 1)
);
// Garbage single token parses as 0 -> 0/1 (null but not NaN).
let g = Rational::from_string("abc");
assert!(g.is_null());
assert!(!g.is_nan());
assert_eq!(g, Rational::new(0, 1));
assert_eq!(g.to_display_string(), "0/1");
assert_eq!(Rational::new(30000, 1001).to_display_string(), "30000/1001");
// More than two '/' elements -> null sentinel.
assert_eq!(Rational::from_string("a/b/c"), Rational::NULL);
}
/// Ordering across denominators (1/3 vs 1001/3000) and equality of
/// differently-reduced equal values.
#[test]
fn rational_ordering() {
assert!(Rational::new(1, 3) < Rational::new(1001, 3000));
assert!(Rational::new(1, 3) > Rational::new(1, 4));
assert_eq!(Rational::new(1, 3), Rational::new(2, 6));
assert!(Rational::new(1, 2) > Rational::new(1, 3));
// NaN orders before everything and equals itself.
assert!(Rational::NULL < Rational::new(1, 1));
assert!(Rational::new(1, 1) > Rational::NULL);
assert_eq!(Rational::NULL, Rational::NULL);
// Total order sorts a mixed list.
let mut v = vec![Rational::new(1, 2), Rational::new(1, 4), Rational::new(1, 3)];
v.sort();
assert_eq!(
v,
vec![Rational::new(1, 4), Rational::new(1, 3), Rational::new(1, 2)]
);
}
/// time_to_timestamp/timestamp_to_time match C++ Timecode rounding
/// (half-away-from-zero at frame boundaries), incl. negative times.
#[test]
fn timecode_rounding() {
// 29.97 fps: the timebase is seconds-per-frame = 1001/30000.
let tb = Rational::new(1001, 30000);
// 0 seconds -> 0 frames.
assert_eq!(tb.time_to_timestamp(Rational::new(0, 1)), 0);
// 1 full frame.
assert_eq!(tb.time_to_timestamp(Rational::new(1001, 30000)), 1);
// Half a frame (0.5 * 1001/30000 s) rounds half-away-from-zero -> 1.
let half = Rational::new(1001, 60000);
assert_eq!(tb.time_to_timestamp(half), 1);
// Negative half frame rounds to -1 (llround half away from zero).
assert_eq!(tb.time_to_timestamp(Rational::new(-1001, 60000)), -1);
// 30 frames round-trip to exactly 1001/1000 s.
assert_eq!(tb.timestamp_to_time(30), Rational::new(1001, 1000));
// timestamp -> time -> timestamp round trip.
assert_eq!(tb.time_to_timestamp(tb.timestamp_to_time(29)), 29);
assert_eq!(tb.time_to_timestamp(tb.timestamp_to_time(300)), 300);
// Video-rate time: 30 frames at 1001/1000 s -> 30.
assert_eq!(tb.time_to_timestamp(Rational::new(1001, 1000)), 30);
}
/// TimeRange: contains/intersected/combined, touching ranges,
/// zero-length ranges. C++: TimeRange methods.
#[test]
fn timerange_ops() {
let r = TimeRange::new(Rational::new(0, 1), Rational::new(10, 1));
assert!(r.contains(Rational::new(5, 1)));
assert!(r.contains(Rational::new(0, 1)));
assert!(!r.contains(Rational::new(10, 1)));
assert!(!r.contains(Rational::new(-1, 1)));
assert_eq!(r.length(), Rational::new(10, 1));
let a = TimeRange::new(Rational::new(0, 1), Rational::new(10, 1));
let b = TimeRange::new(Rational::new(5, 1), Rational::new(15, 1));
assert_eq!(
a.intersected(&b),
TimeRange::new(Rational::new(5, 1), Rational::new(10, 1))
);
assert_eq!(
a.combined(&b),
TimeRange::new(Rational::new(0, 1), Rational::new(15, 1))
);
// Touching ranges combined into one.
let c = TimeRange::new(Rational::new(10, 1), Rational::new(20, 1));
assert_eq!(
a.combined(&c),
TimeRange::new(Rational::new(0, 1), Rational::new(20, 1))
);
// Zero-length range.
let z = TimeRange::new(Rational::new(5, 1), Rational::new(5, 1));
assert_eq!(z.length(), Rational::new(0, 1));
assert!(!z.contains(Rational::new(5, 1)));
// out < in is normalized by swapping.
let swapped = TimeRange::new(Rational::new(10, 1), Rational::new(5, 1));
assert_eq!(
swapped,
TimeRange::new(Rational::new(5, 1), Rational::new(10, 1))
);
}
/// TimeRangeList insert merges overlapping AND touching ranges;
/// remove splits. C++: TimeRangeList.
#[test]
fn timerangelist_normalization() {
let mut list = TimeRangeList::new();
assert!(list.is_empty());
assert_eq!(list.first(), Rational::NULL);
list.insert(TimeRange::new(Rational::new(0, 1), Rational::new(10, 1)));
list.insert(TimeRange::new(Rational::new(20, 1), Rational::new(30, 1)));
// Overlaps (0,10): merges into (0,15), leaving (0,15) + (20,30).
list.insert(TimeRange::new(Rational::new(5, 1), Rational::new(15, 1)));
assert!(!list.is_empty());
assert_eq!(list.total_length(), Rational::new(25, 1));
assert_eq!(list.ranges().len(), 2);
let mut ins: Vec<_> = list.ranges().iter().map(|r| r.in_()).collect();
ins.sort();
assert_eq!(ins, vec![Rational::new(0, 1), Rational::new(20, 1)]);
// Touching inserts merge into a single range.
let mut t = TimeRangeList::new();
t.insert(TimeRange::new(Rational::new(0, 1), Rational::new(10, 1)));
t.insert(TimeRange::new(Rational::new(10, 1), Rational::new(20, 1)));
assert_eq!(t.ranges().len(), 1);
assert_eq!(
t.ranges()[0],
TimeRange::new(Rational::new(0, 1), Rational::new(20, 1))
);
// remove splits (0,20) into (0,5) + (15,20) around the removed (5,15).
let mut s = TimeRangeList::new();
s.insert(TimeRange::new(Rational::new(0, 1), Rational::new(20, 1)));
s.remove(TimeRange::new(Rational::new(5, 1), Rational::new(15, 1)));
assert_eq!(s.ranges().len(), 2);
let mut outs: Vec<_> = s.ranges().iter().map(|r| r.out()).collect();
outs.sort();
assert_eq!(outs, vec![Rational::new(5, 1), Rational::new(20, 1)]);
// first() returns the first range's in().
let mut f = TimeRangeList::new();
f.insert(TimeRange::new(Rational::new(3, 1), Rational::new(7, 1)));
assert_eq!(f.first(), Rational::new(3, 1));
}
/// Frame-grid snap semantics (C++ TimeRangeListFrameIterator::Snap).
#[test]
fn timerangelist_snap() {
let list = TimeRangeList::new();
let tb = Rational::new(1001, 30000); // 29.97 fps, seconds per frame.
// 0.5 frames floors down to frame 0.
let half = Rational::new(1001, 60000);
assert_eq!(list.snap(half, tb), Rational::new(0, 1));
// Exactly 1 frame stays put.
let one = Rational::new(1001, 30000);
assert_eq!(list.snap(one, tb), Rational::new(1001, 30000));
// 1.5 frames (1001/20000 s) floors down to 1 frame.
let one_and_half = Rational::new(1001, 20000);
assert_eq!(list.snap(one_and_half, tb), Rational::new(1001, 30000));
// 30 frames round-trip exactly.
assert_eq!(list.snap(Rational::new(1001, 1000), tb), Rational::new(1001, 1000));
}
/// Enum discriminants identical to the C++ enums (C ABI contract).
#[test]
fn format_enum_values_match_cpp() {
assert_eq!(PixelFormat::Invalid as i32, -1);
assert_eq!(PixelFormat::U8 as i32, 0);
assert_eq!(PixelFormat::U10 as i32, 1);
assert_eq!(PixelFormat::U16 as i32, 2);
assert_eq!(PixelFormat::F16 as i32, 3);
assert_eq!(PixelFormat::F32 as i32, 4);
assert_eq!(PixelFormat::Invalid.bytes_per_channel(), 0);
assert_eq!(PixelFormat::U8.bytes_per_channel(), 1);
assert_eq!(PixelFormat::U10.bytes_per_channel(), 4); // packed RGBA10A2
assert_eq!(PixelFormat::U16.bytes_per_channel(), 2);
assert_eq!(PixelFormat::F16.bytes_per_channel(), 2);
assert_eq!(PixelFormat::F32.bytes_per_channel(), 4);
assert_eq!(PixelFormat::F32.bytes_per_pixel(4), 16);
assert_eq!(SampleFormat::Invalid as i32, -1);
assert_eq!(SampleFormat::U8Planar as i32, 0);
assert_eq!(SampleFormat::S16Planar as i32, 1);
assert_eq!(SampleFormat::S32Planar as i32, 2);
assert_eq!(SampleFormat::S64Planar as i32, 3);
assert_eq!(SampleFormat::F32Planar as i32, 4);
assert_eq!(SampleFormat::F64Planar as i32, 5);
assert_eq!(SampleFormat::U8 as i32, 6);
assert_eq!(SampleFormat::S16 as i32, 7);
assert_eq!(SampleFormat::S32 as i32, 8);
assert_eq!(SampleFormat::S64 as i32, 9);
assert_eq!(SampleFormat::F32 as i32, 10);
assert_eq!(SampleFormat::F64 as i32, 11);
assert_eq!(SampleFormat::Invalid.bytes_per_sample(), 0);
assert_eq!(SampleFormat::U8.bytes_per_sample(), 1);
assert_eq!(SampleFormat::S16.bytes_per_sample(), 2);
assert_eq!(SampleFormat::S32.bytes_per_sample(), 4);
assert_eq!(SampleFormat::F32.bytes_per_sample(), 4);
assert_eq!(SampleFormat::F64.bytes_per_sample(), 8);
assert_eq!(SampleFormat::F64Planar.bytes_per_sample(), 8);
assert!(SampleFormat::U8Planar.is_planar());
assert!(SampleFormat::F64Planar.is_planar());
assert!(!SampleFormat::U8.is_planar());
assert!(!SampleFormat::Invalid.is_planar());
assert_eq!(SampleFormat::U8Planar.to_packed(), SampleFormat::U8);
assert_eq!(SampleFormat::F64Planar.to_packed(), SampleFormat::F64);
assert_eq!(SampleFormat::U8.to_packed(), SampleFormat::U8);
assert_eq!(SampleFormat::U8.to_planar(), SampleFormat::U8Planar);
assert_eq!(SampleFormat::S16.to_planar(), SampleFormat::S16Planar);
assert_eq!(SampleFormat::F64.to_planar(), SampleFormat::F64Planar);
}
/// Extreme i64 inputs (which C++ `int` could never receive) must reduce
/// without panicking, capped to the C++ `i32::MAX` reduce cap; the
/// RATIONAL_MIN/MAX sentinels propagate NaN through arithmetic.
#[test]
fn rational_large_inputs_and_minmax() {
let mn = Rational::new(i64::MIN, 1);
assert_eq!(mn.numerator(), -2147483647);
assert_eq!(mn.denominator(), 1);
let mx = Rational::new(i64::MAX, 1);
assert_eq!(mx.numerator(), 2147483647);
assert_eq!(mx.denominator(), 1);
let mx = Rational::new(2147483647, 1);
assert!(!mx.is_null()); // 2147483647/1 is a valid value, not null
let r = mx + Rational::new(1, 1);
assert!(r.is_nan());
assert_eq!(r, Rational::NULL);
let mn = Rational::new(-2147483647, 1);
let r = Rational::new(1, 1) * mn;
assert!(r.is_nan());
}
/// Additional edge cases: full-encompassing remove erases, partial
/// removes trim the correct endpoint, NaN timebase yields 0 frames, and
/// invalid format conversions are identities.
#[test]
fn additional_edge_cases() {
// remove fully encompassing an element erases it.
let mut l = TimeRangeList::new();
l.insert(TimeRange::new(Rational::new(0, 1), Rational::new(20, 1)));
l.remove(TimeRange::new(Rational::new(-5, 1), Rational::new(25, 1)));
assert!(l.is_empty());
// Trim the element's out down to the removal's in.
let mut l2 = TimeRangeList::new();
l2.insert(TimeRange::new(Rational::new(0, 1), Rational::new(20, 1)));
l2.remove(TimeRange::new(Rational::new(5, 1), Rational::new(25, 1)));
assert_eq!(l2.ranges().len(), 1);
assert_eq!(
l2.ranges()[0],
TimeRange::new(Rational::new(0, 1), Rational::new(5, 1))
);
// Trim the element's in up to the removal's out.
let mut l3 = TimeRangeList::new();
l3.insert(TimeRange::new(Rational::new(0, 1), Rational::new(20, 1)));
l3.remove(TimeRange::new(Rational::new(-5, 1), Rational::new(5, 1)));
assert_eq!(l3.ranges().len(), 1);
assert_eq!(
l3.ranges()[0],
TimeRange::new(Rational::new(5, 1), Rational::new(20, 1))
);
// A NaN timebase yields 0 frames.
assert_eq!(Rational::NULL.time_to_timestamp(Rational::new(1, 1)), 0);
// to_f64 of the null sentinel is NaN.
assert!(Rational::NULL.to_f64().is_nan());
// Invalid format conversions are identities.
assert_eq!(SampleFormat::Invalid.to_packed(), SampleFormat::Invalid);
assert_eq!(SampleFormat::Invalid.to_planar(), SampleFormat::Invalid);
}
/// from_double: C++ Rational::from_double parity — NaN and huge values
/// yield 0/0; common values round-trip; tiny values use the
/// high-precision retry path.
#[test]
fn rational_from_double() {
use oakcore_rs::Rational;
assert!(Rational::from_double(f64::NAN).is_nan());
assert!(Rational::from_double(1e300).is_nan());
assert!(Rational::from_double(-1e300).is_nan());
let r = Rational::from_double(0.5);
assert_eq!((r.numerator(), r.denominator()), (1, 2));
let fps = Rational::from_double(29.97002997002997);
assert!((fps.to_f64() - 29.97002997002997).abs() < 1e-9);
let third = Rational::from_double(1.0 / 3.0);
assert!((third.to_f64() - 1.0 / 3.0).abs() < 1e-9);
assert_eq!(Rational::from_double(0.0).numerator(), 0);
}