aexlo 0.1.0

Run After Effects plugins without Adobe dependencies.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use std::ffi::{CStr, CString};

use after_effects_sys::{A_char, PF_Err, PF_Err_BAD_CALLBACK_PARAM, PF_Err_INTERNAL_STRUCT_DAMAGED, PF_Err_NONE};

#[cfg(feature = "diagnostics")]
use crate::core::diagnostics::DiagnosticBuilder;

macro_rules! impl_math_sys {
	($name:ident, $func:ident, $arg:literal, $diag_path:literal) => {
		#[inline(always)]
		pub(crate) extern "C" fn $name(x: f64) -> f64 {
			let result = x.$func();

			#[cfg(feature = "diagnostics")]
			DiagnosticBuilder::new()
				.set_name($diag_path)
				.add_arg($arg, x)
				.set_result(result)
				.emit();

			result
		}
	};
	($name:ident, $func:ident, $arg1:literal, $arg2:literal, $diag_path:literal) => {
		#[inline(always)]
		pub(crate) extern "C" fn $name(a: f64, b: f64) -> f64 {
			let result = a.$func(b);

			#[cfg(feature = "diagnostics")]
			DiagnosticBuilder::new()
				.set_name($diag_path)
				.add_arg($arg1, a)
				.add_arg($arg2, b)
				.set_result(result)
				.emit();

			result
		}
	};
}

impl_math_sys!(atan_sys, atan, "x", "InData/utils/ansi/atan");
impl_math_sys!(atan2_sys, atan2, "y", "x", "InData/utils/ansi/atan2");
impl_math_sys!(ceil_sys, ceil, "x", "InData/utils/ansi/ceil");
impl_math_sys!(cos_sys, cos, "x", "InData/utils/ansi/cos");
impl_math_sys!(exp_sys, exp, "x", "InData/utils/ansi/exp");
impl_math_sys!(fabs_sys, abs, "x", "InData/utils/ansi/fabs");
impl_math_sys!(floor_sys, floor, "x", "InData/utils/ansi/floor");
impl_math_sys!(fmod_sys, rem_euclid, "x", "y", "InData/utils/ansi/fmod");
impl_math_sys!(hypot_sys, hypot, "x", "y", "InData/utils/ansi/hypot");
impl_math_sys!(log_sys, ln, "x", "InData/utils/ansi/log");
impl_math_sys!(log10_sys, log10, "x", "InData/utils/ansi/log10");
impl_math_sys!(pow_sys, powf, "x", "y", "InData/utils/ansi/pow");
impl_math_sys!(sin_sys, sin, "x", "InData/utils/ansi/sin");
impl_math_sys!(sqrt_sys, sqrt, "x", "InData/utils/ansi/sqrt");
impl_math_sys!(tan_sys, tan, "x", "InData/utils/ansi/tan");
impl_math_sys!(asin_sys, asin, "x", "InData/utils/ansi/asin");
impl_math_sys!(acos_sys, acos, "x", "InData/utils/ansi/acos");

/// Emulates `sprintf()` function
///
/// # Safety
///
/// This function is unsafe because:
/// 1. It handles raw pointers (`arg1`, `arg2`, and variadic arguments) which must be valid.
/// 2. `arg1` is assumed to be a pointer to a mutable buffer of at least 256 bytes.
///    The function will strictly write no more than 256 bytes (including null terminator),
///    but the caller is responsible for ensuring the buffer allocation.
/// 3. `arg2` must be a valid, null-terminated C-string.
/// 4. Variadic arguments must correspond exactly to the format specifiers in `arg2`.
///    Mismatching arguments (e.g. passing a float for `%d`) leads to undefined behavior.
/// 5. Only `%d` and `%s` format specifiers are actively supported.
pub(crate) unsafe extern "C" fn sprintf_sys(arg1: *mut A_char, arg2: *const A_char, mut args: ...) -> PF_Err {
	crate::core::ffi::guard("sprintf_sys", || {
		const SPRINTF_BUFFER_SIZE: usize = 256;

		if arg1.is_null() || arg2.is_null() {
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		let format_str = match unsafe { CStr::from_ptr(arg2) }.to_str() {
			Ok(s) => s,
			Err(_) => {
				return PF_Err_INTERNAL_STRUCT_DAMAGED as PF_Err;
			}
		};

		// Raw implementation to handle %d and %s format specifiers
		let mut result = String::new();
		let mut chars = format_str.chars().peekable();

		// Built incrementally as variadic args are pulled, so it can't be a single
		// trailing `diag!`; the cfg-gated statements keep it zero-cost otherwise.
		#[cfg(feature = "diagnostics")]
		let mut diagnostics = DiagnosticBuilder::new();
		#[cfg(feature = "diagnostics")]
		diagnostics
			.set_name("UtilityCallbacks/ansi/sprintf")
			.add_arg("format", format!("{:?}", format_str));

		while let Some(c) = chars.next() {
			if c == '%' {
				if let Some(next) = chars.next() {
					match next {
						'd' => {
							// Get an integer argument
							let arg = unsafe { args.next_arg::<i32>() };

							#[cfg(feature = "diagnostics")]
							diagnostics.add_arg("arg_int", format!("{:?}", arg));
							result.push_str(&arg.to_string());
						}
						's' => {
							// Get a string argument
							let ptr = unsafe { args.next_arg::<*const i8>() };

							if !ptr.is_null() {
								match unsafe { CStr::from_ptr(ptr) }.to_str() {
									Ok(s) => {
										result.push_str(s);
										#[cfg(feature = "diagnostics")]
										diagnostics.add_arg("arg_str", format!("{:?}", s));
									}
									Err(_) => result.push_str("(invalid)"),
								}
							} else {
								result.push_str("(null)");
							}
						}
						'%' => {
							result.push('%');
						}
						_ => {
							// Unsupported format specifier, just include it as-is
							result.push('%');
							result.push(next);
						}
					}
				} else {
					// Trailing %
					result.push('%');
				}
			} else {
				result.push(c);
			}
		}

		// Copy result to the output buffer
		let c_result = match CString::new(result) {
			Ok(s) => s,
			Err(_) => {
				return PF_Err_INTERNAL_STRUCT_DAMAGED as PF_Err;
			}
		};

		let bytes = c_result.as_bytes_with_nul();
		let copy_len = bytes.len().min(SPRINTF_BUFFER_SIZE);

		// Copy bytes
		unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), arg1 as *mut u8, copy_len) };

		// Ensure null termination if we truncated or filled exactly
		// If copy_len < SPRINTF_BUFFER_SIZE, the null byte from as_bytes_with_nul is already copied.
		// If copy_len == SPRINTF_BUFFER_SIZE, we forced a cut, so we must manually null-terminate at the end.
		if copy_len == SPRINTF_BUFFER_SIZE && SPRINTF_BUFFER_SIZE > 0 {
			unsafe { *((arg1 as *mut u8).add(SPRINTF_BUFFER_SIZE - 1)) = 0 };
		}

		#[cfg(feature = "diagnostics")]
		diagnostics.set_result(format!("{:?}", c_result)).emit();

		PF_Err_NONE as PF_Err
	})
}

pub unsafe extern "C" fn strcpy_sys(arg1: *mut A_char, arg2: *const A_char) -> *mut A_char {
	//== Validation ==//
	if arg1.is_null() || arg2.is_null() {
		return std::ptr::null_mut();
	}

	let src = match unsafe { CStr::from_ptr(arg2) }.to_str() {
		Ok(s) => s,
		Err(_) => return std::ptr::null_mut(),
	};

	let cstring = match CString::new(src) {
		Ok(s) => s,
		Err(_) => return std::ptr::null_mut(),
	};

	let bytes = cstring.as_bytes_with_nul();
	unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), arg1 as *mut u8, bytes.len()) };

	arg1
}

#[cfg(test)]
mod tests {
	use super::*;
	use std::ffi::CStr;

	#[test]
	fn atan_test() {
		let x = 1.0;
		let result = atan_sys(x);

		assert!(
			(result - std::f64::consts::FRAC_PI_4).abs() < 1e-10,
			"Expected atan(1.0) to be close to π/4, got {}",
			result
		);
	}

	#[test]
	fn atan2_test() {
		let y = 1.0;
		let x = 1.0;
		let result = atan2_sys(y, x);

		assert!(
			(result - std::f64::consts::FRAC_PI_4).abs() < 1e-10,
			"Expected atan2(1.0, 1.0) to be close to π/4, got {}",
			result
		);
	}

	#[test]
	fn ceil_test() {
		let x = 1.5;
		let result = ceil_sys(x);

		assert!(
			(result - 2.0).abs() < 1e-10,
			"Expected ceil(1.5) to be close to 2.0, got {}",
			result
		);
	}

	#[test]
	fn cos_test() {
		let x = 0.0;
		let result = cos_sys(x);

		assert!(
			(result - 1.0).abs() < 1e-10,
			"Expected cos(0.0) to be close to 1.0, got {}",
			result
		);
	}

	#[test]
	fn exp_test() {
		let x = 1.0;
		let result = exp_sys(x);

		assert!(
			(result - std::f64::consts::E).abs() < 1e-10,
			"Expected exp(1.0) to be close to e, got {}",
			result
		);
	}

	#[test]
	fn fabs_test() {
		let x = -3.5;
		let result = fabs_sys(x);

		assert!(
			(result - 3.5).abs() < 1e-10,
			"Expected fabs(-3.5) to be close to 3.5, got {}",
			result
		);
	}

	#[test]
	fn floor_test() {
		let x = 1.5;
		let result = floor_sys(x);

		assert!(
			(result - 1.0).abs() < 1e-10,
			"Expected floor(1.5) to be close to 1.0, got {}",
			result
		);
	}

	#[test]
	fn fmod_test() {
		let x = 5.5;
		let y = 2.0;
		let result = fmod_sys(x, y);

		assert!(
			(result - 1.5).abs() < 1e-10,
			"Expected fmod(5.5, 2.0) to be close to 1.5, got {}",
			result
		);
	}

	#[test]
	fn hypot_test() {
		let x = 3.0;
		let y = 4.0;
		let result = hypot_sys(x, y);

		assert!(
			(result - 5.0).abs() < 1e-10,
			"Expected hypot(3.0, 4.0) to be close to 5.0, got {}",
			result
		);
	}

	#[test]
	fn log_test() {
		let x = std::f64::consts::E;
		let result = log_sys(x);

		assert!(
			(result - 1.0).abs() < 1e-10,
			"Expected log(e) to be close to 1.0, got {}",
			result
		);
	}

	#[test]
	fn log10_test() {
		let x = 100.0;
		let result = log10_sys(x);

		assert!(
			(result - 2.0).abs() < 1e-10,
			"Expected log10(100) to be close to 2.0, got {}",
			result
		);
	}

	#[test]
	fn pow_test() {
		let x = 2.0;
		let y = 3.0;
		let result = pow_sys(x, y);

		assert!(
			(result - 8.0).abs() < 1e-10,
			"Expected pow(2.0, 3.0) to be close to 8.0, got {}",
			result
		);
	}

	#[test]
	fn sin_test() {
		let x = std::f64::consts::FRAC_PI_2; // 90 degrees
		let result = sin_sys(x);

		assert!(
			(result - 1.0).abs() < 1e-10,
			"Expected sin(π/2) to be close to 1.0, got {}",
			result
		);
	}

	#[test]
	fn sqrt_test() {
		let x = 16.0;
		let result = sqrt_sys(x);

		assert!(
			(result - 4.0).abs() < 1e-10,
			"Expected sqrt(16) to be close to 4.0, got {}",
			result
		);
	}

	#[test]
	fn tan_test() {
		let x = std::f64::consts::FRAC_PI_4; // 45 degrees
		let result = tan_sys(x);

		assert!(
			(result - 1.0).abs() < 1e-10,
			"Expected tan(π/4) to be close to 1.0, got {}",
			result
		);
	}

	/// Run `sprintf_sys` with the given format and variadic args, asserting it
	/// succeeds, and return the string written into the output buffer.
	///
	/// A macro rather than a function because the argument list is variadic.
	macro_rules! sprintf {
		($fmt:expr $(, $arg:expr)* $(,)?) => {{
			let fmt = CString::new($fmt).unwrap();
			let mut buffer = [0 as A_char; 256];
			let err = unsafe { sprintf_sys(buffer.as_mut_ptr(), fmt.as_ptr() $(, $arg)*) };
			assert_eq!(err, PF_Err_NONE as PF_Err, "sprintf_sys returned error {err}");
			unsafe { CStr::from_ptr(buffer.as_ptr()) }.to_str().unwrap().to_owned()
		}};
	}

	#[test]
	fn sprintf_no_specifier_copies_verbatim() {
		assert_eq!(sprintf!("Hello, world!"), "Hello, world!");
	}

	#[test]
	fn sprintf_single_int() {
		assert_eq!(sprintf!("%d", 42i32), "42");
	}

	#[test]
	fn sprintf_several_ints() {
		assert_eq!(sprintf!("%d + %d = %d", 2i32, 3i32, 5i32), "2 + 3 = 5");
	}

	#[test]
	fn sprintf_negative_int() {
		assert_eq!(sprintf!("%d", -7i32), "-7");
	}

	#[test]
	fn sprintf_string() {
		let s = CString::new("aexlo").unwrap();
		assert_eq!(sprintf!("%s", s.as_ptr()), "aexlo");
	}

	#[test]
	fn sprintf_null_string_arg() {
		assert_eq!(sprintf!("%s", std::ptr::null::<A_char>()), "(null)");
	}

	#[test]
	fn sprintf_mixed_specifiers() {
		let name = CString::new("frame").unwrap();
		assert_eq!(sprintf!("%s=%d", name.as_ptr(), 7i32), "frame=7");
	}

	#[test]
	fn sprintf_literal_percent() {
		assert_eq!(sprintf!("100%% done"), "100% done");
	}

	#[test]
	fn sprintf_unsupported_specifier_passthrough() {
		// Only %d/%s/%% are handled; anything else is emitted verbatim.
		assert_eq!(sprintf!("%q"), "%q");
	}

	#[test]
	fn sprintf_trailing_percent() {
		assert_eq!(sprintf!("done%"), "done%");
	}

	#[test]
	fn sprintf_null_buffer_is_bad_callback_param() {
		let fmt = CString::new("%d").unwrap();
		let err = unsafe { sprintf_sys(std::ptr::null_mut(), fmt.as_ptr(), 1i32) };
		assert_eq!(err, PF_Err_BAD_CALLBACK_PARAM as PF_Err);
	}

	#[test]
	fn sprintf_null_format_is_bad_callback_param() {
		let mut buffer = [0 as A_char; 256];
		let err = unsafe { sprintf_sys(buffer.as_mut_ptr(), std::ptr::null()) };
		assert_eq!(err, PF_Err_BAD_CALLBACK_PARAM as PF_Err);
	}

	// Note: passing fewer args than the format has specifiers (e.g. `sprintf!("%d")`)
	// is genuine C-variadic UB - the reader pulls a nonexistent arg - so it is
	// intentionally not exercised here.

	#[test]
	fn strcpy_test() {
		let src = std::ffi::CString::new("Hello, world!").unwrap();
		let mut buffer = [0i8; 256];

		let result_ptr = unsafe { strcpy_sys(buffer.as_mut_ptr(), src.as_ptr()) };

		assert!(!result_ptr.is_null(), "Expected strcpy to return a non-null pointer");

		let result_str = unsafe { CStr::from_ptr(result_ptr).to_str().unwrap() };

		assert!(
			result_str == src.to_str().unwrap(),
			"Expected strcpy to copy the string correctly, got {:?}",
			result_str
		);
	}

	#[test]
	fn asin_test() {
		let x = 0.5;
		let result = asin_sys(x);

		assert!(
			(result - std::f64::consts::FRAC_PI_6).abs() < 1e-10,
			"Expected asin(0.5) to be close to π/6, got {}",
			result
		);
	}

	#[test]
	fn acos_test() {
		let x = 0.5;
		let result = acos_sys(x);

		assert!(
			(result - std::f64::consts::FRAC_PI_3).abs() < 1e-10,
			"Expected acos(0.5) to be close to π/3, got {}",
			result
		);
	}
}