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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! [`PluginInstance`]: one loaded effect and the host state it runs against.
//! Loading, rendering, layers and parameters live in the submodules.

use crate::core::error::{AexloError, Result};
use crate::core::in_data::{CallBindings, EffectState, HostInfo as InDataHost, RenderContext};
use crate::host::app::Host;
use crate::host::host_layer::HostLayer;
use crate::host::layer_param::LinkedLayer;
use crate::host::smart_render::SmartRenderData;
use crate::observe::{CommandEvent, CommandPhase, Installed, ObserveLevel, Observer};
use crate::param_value::ParamValue;
use crate::utils;

use crate::gpu::GPU_BYTES_PER_PIXEL;
use crate::pixel::{AnyLayer, Depth8, Layer, Pixel, PixelDepth, PixelDepthKind};
use crate::time::Time;
use after_effects_sys::{
	PF_ArbParamsExtra, PF_Arbitrary_COPY_FUNC, PF_Arbitrary_DISPOSE_FUNC, PF_Arbitrary_NEW_FUNC, PF_ArbitraryH,
	PF_Err_INVALID_CALLBACK, PF_Err_NONE, PF_GPU_Framework, PF_GPU_Framework_NONE, PF_GPUDeviceSetdownExtra,
	PF_GPUDeviceSetdownInput, PF_GPUDeviceSetupExtra, PF_GPUDeviceSetupInput, PF_GPUDeviceSetupOutput,
	PF_OutFlag2_SUPPORTS_GPU_RENDER_F32, PF_OutFlags, PF_OutFlags2, PF_ParamDef, PF_ParamDefUnion, PF_ParamType,
	PF_ProgPtr,
};
use after_effects_sys::{
	PF_Cmd, PF_Param_ANGLE, PF_Param_ARBITRARY_DATA, PF_Param_CHECKBOX, PF_Param_COLOR, PF_Param_FIX_SLIDER,
	PF_Param_FLOAT_SLIDER, PF_Param_LAYER, PF_Param_PATH, PF_Param_POINT, PF_Param_POINT_3D, PF_Param_POPUP,
	PF_Param_SLIDER,
};
use dlopen2::raw::Library;
use std::{
	collections::HashMap,
	ffi::{CStr, CString, c_void},
	path::{Path, PathBuf},
	ptr::NonNull,
	ptr::null_mut,
	sync::Arc,
	time::Instant,
};

use crate::core::constants::{DEFAULT_HEIGHT as HEIGHT, DEFAULT_WIDTH as WIDTH};

/// The effect commands (`PF_Cmd_*`) aexlo sends to a plugin.
///
/// The discriminants are the SDK values, so `command as i32` is the wire
/// value. The entry point itself takes the raw [`PF_Cmd`] (see
/// [`PluginEntryPoint`]); this names the ones the host issues and logs them
/// readably.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub(crate) enum RawCommand {
	About = after_effects_sys::PF_Cmd_ABOUT as i32,
	GlobalSetup = after_effects_sys::PF_Cmd_GLOBAL_SETUP as i32,
	GlobalSetdown = after_effects_sys::PF_Cmd_GLOBAL_SETDOWN as i32,
	ParamsSetup = after_effects_sys::PF_Cmd_PARAMS_SETUP as i32,
	SequenceSetup = after_effects_sys::PF_Cmd_SEQUENCE_SETUP as i32,
	SequenceSetdown = after_effects_sys::PF_Cmd_SEQUENCE_SETDOWN as i32,
	DoDialog = after_effects_sys::PF_Cmd_DO_DIALOG as i32,
	Render = after_effects_sys::PF_Cmd_RENDER as i32,
	UserChangedParam = after_effects_sys::PF_Cmd_USER_CHANGED_PARAM as i32,
	UpdateParamsUi = after_effects_sys::PF_Cmd_UPDATE_PARAMS_UI as i32,
	Event = after_effects_sys::PF_Cmd_EVENT as i32,
	ArbitraryCallback = after_effects_sys::PF_Cmd_ARBITRARY_CALLBACK as i32,
	SmartPreRender = after_effects_sys::PF_Cmd_SMART_PRE_RENDER as i32,
	SmartRender = after_effects_sys::PF_Cmd_SMART_RENDER as i32,
	SmartRenderGpu = after_effects_sys::PF_Cmd_SMART_RENDER_GPU as i32,
	GpuDeviceSetup = after_effects_sys::PF_Cmd_GPU_DEVICE_SETUP as i32,
	GpuDeviceSetdown = after_effects_sys::PF_Cmd_GPU_DEVICE_SETDOWN as i32,
}

impl RawCommand {
	pub(crate) fn to_sys(self) -> PF_Cmd {
		self as PF_Cmd
	}
}

mod layers;
mod load;
mod params;
mod render;
#[cfg(test)]
mod tests;

pub use load::Loader;
pub use render::RenderPath;

const DEFAULT_ENTRY_POINT_NAME: &str = "EffectMain";

/// Normalized `[r, g, b, a]` of the fresh output world AE hands a plugin.
const OPAQUE_BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];

/// Entry point names to try if the plugin doesn't implement `PluginDataEntryFunction2`.
const FALLBACK_ENTRY_POINT_CANDIDATES: &[&str] = &[DEFAULT_ENTRY_POINT_NAME, "EntryPointFunc"];
/// Fixed symbol name of the AE SDK's self-describing plugin data entry function.
const PLUGIN_DATA_ENTRY_SYMBOL: &str = "PluginDataEntryFunction2";
const HOST_NAME: &str = "AfterEffects";
const HOST_VERSION: &str = "25.2";

// On Windows, an effect that lets a C++ exception leave its entry point would
// cross a Rust frame and abort the process. The call sits in a C handler so
// the host reports a failed command instead. Access violations and other
// structured exceptions are not caught (see seh_call.cpp).
#[cfg(windows)]
unsafe extern "C" {
	fn aexlo_call_entry(
		entry: *const c_void,
		cmd: i32,
		in_data: *mut c_void,
		out_data: *mut c_void,
		params: *mut c_void,
		output: *mut c_void,
		extra: *mut c_void,
		exception_code: *mut u32,
	) -> i32;
}

/// Calls `entry_point`. On Windows a C++ exception that escapes the plugin
/// becomes `PF_Err_INTERNAL_STRUCT_DAMAGED`.
///
/// # Safety
/// `entry_point` must be the plugin's entry point, and the pointers must be
/// the ones [`PluginInstance::call_plugin`] passes to it.
unsafe fn call_entry(
	entry_point: PluginEntryPoint,
	command: RawCommand,
	in_data: *mut after_effects_sys::PF_InData,
	out_data: *mut after_effects_sys::PF_OutData,
	params: after_effects_sys::PF_ParamList,
	output: *mut after_effects_sys::PF_LayerDef,
	extra: *mut c_void,
) -> after_effects_sys::PF_Err {
	#[cfg(windows)]
	{
		let mut code = 0u32;
		// SAFETY: the caller upholds `call_entry`'s contract. The C wrapper
		// invokes the same cdecl entry point and catches an exception that
		// would otherwise abort the process.
		let result = unsafe {
			aexlo_call_entry(
				entry_point as usize as *const c_void,
				command.to_sys() as i32,
				in_data.cast(),
				out_data.cast(),
				params.cast(),
				output.cast(),
				extra,
				&mut code,
			)
		};
		if code != 0 {
			log::error!(
				"plugin command {command:?} threw a C++ exception ({code:#x}); reporting PF_Err_INTERNAL_STRUCT_DAMAGED"
			);
			return after_effects_sys::PF_Err_INTERNAL_STRUCT_DAMAGED as after_effects_sys::PF_Err;
		}
		result as after_effects_sys::PF_Err
	}
	#[cfg(not(windows))]
	{
		// SAFETY: the caller upholds `call_entry`'s contract.
		unsafe { entry_point(command.to_sys(), in_data, out_data, params, output, extra) }
	}
}

/// ABI of an After Effects effect entry point (`EffectMain`): the fixed
/// `(cmd, in_data, out_data, params, output, extra)` signature every effect
/// exports. Handed to [`Host::from_entry`] to drive an in-process
/// effect without `dlopen`.
pub type PluginEntryPoint = unsafe extern "C" fn(
	cmd: PF_Cmd,
	in_data: *mut after_effects_sys::PF_InData,
	out_data: *mut after_effects_sys::PF_OutData,
	params: after_effects_sys::PF_ParamList,
	output: *mut after_effects_sys::PF_LayerDef,
	extra: *mut ::std::os::raw::c_void,
) -> after_effects_sys::PF_Err;

/// Independent instance of an After Effects Plug-in.
/// It is created by loading a plug-in with [`Host::load`] or by driving an in-process entry point with [`Host::from_entry`].
/// Manages its library, entry point, parameters, and execution state.
/// All operations related to the plug-in should be invoked from this.
pub struct PluginInstance {
	/// Identifies AEGP registrations whose callbacks must not outlive this DLL.
	aegp_owner: u64,
	raw_library: Option<Library>,
	entry_point: Option<PluginEntryPoint>,
	entry_point_name: Option<String>,
	binary_file_path: PathBuf,

	/// The dynamic library actually `dlopen`ed (resolved from
	/// `binary_file_path`, e.g. the binary inside a `.plugin` bundle), or `None`
	/// for in-process entry points. Reported to the plugin through
	/// `get_platform_data` (`PF_PlatData_EXE_FILE_PATH_W`, ...) - per instance,
	/// so loading a second plugin doesn't clobber the first one's path.
	resolved_binary_path: Option<PathBuf>,

	/// Persistent output world handed back by `checkout_output` during smart render.
	world: after_effects_sys::PF_LayerDef,

	/// Persistent input world handed back by `checkout_layer_pixels` during smart
	/// render. Kept in sync with `input_layer` so the pointer stays valid across calls.
	input_world: after_effects_sys::PF_LayerDef,

	utility_callbacks: Box<after_effects_sys::_PF_UtilCallbacks>,

	/// Basic Suite pointer.
	pica: Box<after_effects_sys::SPBasicSuite>,

	/// Host-wide constants composed into every `PF_InData`.
	host_info: InDataHost,
	/// Plugin-owned handles carried across commands.
	effect_state: EffectState,
	/// Frame the next command operates on.
	pub(crate) render_context: RenderContext,
	out_data: after_effects_sys::PF_OutData,
	/// `out_flags` as declared at `PF_Cmd_GLOBAL_SETUP`.
	global_out_flags: PF_OutFlags,
	/// `out_flags2` as declared at `PF_Cmd_GLOBAL_SETUP`.
	global_out_flags2: PF_OutFlags2,

	/// Instance-specific parameters from the host (non-global storage).
	params: Vec<after_effects_sys::PF_ParamDef>,

	/// Popup choice labels captured per parameter at `PF_Cmd_PARAMS_SETUP`,
	/// parallel to `params` (empty for non-popup params). Captured at add time
	/// because a popup's `namesptr` points into a plugin-owned string that only
	/// lives for the add-param callback; reading it later is a dangling read.
	popup_choices: Vec<Vec<String>>,

	/// Track if instance params need synchronization.
	params_dirty: bool,

	/// Raw pointers into `params`, passed to the plugin entry point on each call.
	/// Rebuilt lazily in `call_plugin` whenever `params_dirty` is set, since pushing
	/// to `params` may reallocate its backing buffer and invalidate old pointers.
	params_ptr_cache: Vec<*mut PF_ParamDef>,

	/// The effect's own layer. Its depth is the project depth: the output
	/// follows it (see [`Self::set_input_layer`]).
	pub(crate) input_layer: HostLayer,
	pub(crate) output_layer: HostLayer,

	smart_render_data: SmartRenderData,

	/// Metal device/queue plus the `MTLBuffer`s backing this instance's GPU worlds,
	/// created lazily when driving a plugin that declared GPU render support.
	gpu_context: Option<crate::gpu::GpuContext>,

	/// Reusable staging buffers for the GPU upload/readback paths, so a preview
	/// loop doesn't reallocate ~66 MB per 1080p frame.
	gpu_upload_staging: Vec<f32>,
	gpu_readback_staging: Vec<f32>,

	/// Whether the GPU input buffer currently holds `input_layer`'s pixels.
	/// Cleared by [`Self::set_input`] (and on context creation) so the next
	/// [`Self::render_gpu`] re-packs and re-uploads; left set otherwise, since a
	/// parameter-only change doesn't touch the input pixels.
	gpu_input_uploaded: bool,

	/// Opaque, plugin-owned GPU state returned by `PF_Cmd_GPU_DEVICE_SETUP`
	/// (compiled pipelines, etc.), handed back to the plugin during GPU render and
	/// released by `PF_Cmd_GPU_DEVICE_SETDOWN`.
	gpu_data: *mut ::std::os::raw::c_void,

	/// Whether `PF_Cmd_GPU_DEVICE_SETUP` has succeeded and is still awaiting its
	/// `PF_Cmd_GPU_DEVICE_SETDOWN`. Tracked separately from [`Self::gpu_data`]
	/// because plugins may keep their GPU state elsewhere and return null.
	gpu_device_ready: bool,

	/// Label the plugin gave its Options button via `PF_SetOptionsButtonName`.
	options_button_name: Option<String>,

	/// One effect-window context per custom control. After Effects creates it
	/// for `PF_Event_NEW_CONTEXT` and hands the same handle to every later
	/// event, so the plugin's `plugin_state` survives from activation to click.
	ui_contexts: HashMap<usize, LiveUiContext>,
	/// Parameters that have already received `NEW_CONTEXT` and `ACTIVATE`.
	custom_ui_ready: std::collections::HashSet<usize>,
	/// Latest raster of each custom-UI control, keyed by parameter index.
	custom_controls: HashMap<usize, CustomControlImage>,

	/// Pixel formats (FourCCs) registered through the "PF Pixel Format Suite".
	supported_pixel_formats: Vec<crate::PixelFormat>,

	/// Masks on the effect's layer, served through the Path Query/Data suites.
	mask_paths: Vec<crate::MaskPath>,

	/// Layers linked to the plugin's own `PF_Param_LAYER` parameters, by index.
	linked_layers: HashMap<usize, LinkedLayer>,

	/// Smart-render checkout ids mapped to the layer parameter they checked
	/// out, recorded by `checkout_layer` during pre-render.
	layer_checkouts: HashMap<after_effects_sys::A_long, usize>,

	/// Whether iterate callbacks may run on worker threads (see
	/// [`Self::set_parallel_iterate`]).
	parallel_iterate: bool,

	/// Indices of the arbitrary-data parameters whose value handle the plugin
	/// created for us at setup (see [`Self::setup_arbitrary_params`]); handed
	/// back through `PF_Arbitrary_DISPOSE_FUNC` on drop.
	owned_arb_values: Vec<usize>,

	/// Whether [`Self::setup_arbitrary_params`] has run since the last
	/// `PF_Cmd_PARAMS_SETUP`; arbitrary streams read `NO_DATA` until it has.
	arb_streams_live: bool,

	/// Who is told about commands and calls (see [`Self::set_observer`]).
	observer: Option<Installed>,

	/// Strict-mode instrumentation (see [`Self::set_strict`]).
	strict: crate::Strict,
	/// Strict-mode bookkeeping, shared with host callbacks during commands.
	tracker: crate::strict::SharedTracker,
	/// The guarded copy of the output a CPU render writes into (strict mode).
	output_guard: Option<crate::strict::Guarded>,
	/// Whether the plugin has been set down (see [`Self::finish`]).
	torn_down: bool,
}

struct ControlPointer {
	x: i32,
	y: i32,
	last: bool,
}

fn wants_redraw(flags: i32) -> bool {
	let again = (after_effects_sys::PF_EO_ALWAYS_UPDATE | after_effects_sys::PF_EO_UPDATE_NOW)
		as after_effects_sys::PF_EventOutFlags;
	flags & again != 0
}

struct LiveUiContext {
	/// Keeps the context allocation alive; the handle points into it.
	#[allow(dead_code)]
	context: Box<after_effects_sys::PF_Context>,
	handle: Box<*mut after_effects_sys::PF_Context>,
}

impl LiveUiContext {
	fn new() -> Self {
		let mut context = Box::new(after_effects_sys::PF_Context {
			magic: after_effects_sys::PF_CONTEXT_MAGIC,
			w_type: after_effects_sys::PF_Window_EFFECT as after_effects_sys::PF_WindowType,
			reserved_flt: std::ptr::null_mut(),
			plugin_state: [0; 4],
			reserved_drawref: std::ptr::null_mut(),
			reserved_paneP: std::ptr::null_mut(),
			reserved_job_manageP: std::ptr::null_mut(),
		});
		let ptr = context.as_mut() as *mut after_effects_sys::PF_Context;
		Self {
			context,
			handle: Box::new(ptr),
		}
	}

	fn handle(&mut self) -> after_effects_sys::PF_ContextH {
		self.handle.as_mut()
	}

	fn set_draw_ref(&mut self, draw: after_effects_sys::DRAWBOT_DrawRef) {
		self.context.reserved_drawref = draw;
	}

	fn clear_draw_ref(&mut self) {
		self.context.reserved_drawref = std::ptr::null_mut();
	}
}

/// What a custom-control click or drag asked the host to do next.
pub struct CustomControlEvent {
	/// The plugin set `PF_EO_ALWAYS_UPDATE` or `PF_EO_UPDATE_NOW`.
	pub redraw: bool,
	/// The plugin set `send_drag`. The host keeps sending `PF_Event_DRAG`
	/// until mouse-up, and that last sample has `last_time` set. A click that
	/// never moves still needs this mouse-up; that is what commits the click.
	pub send_drag: bool,
}

/// Straight RGBA image of one custom-UI control after `PF_Event_DRAW`.
#[derive(Clone)]
pub struct CustomControlImage {
	/// Width in pixels.
	pub width: u32,
	/// Height in pixels.
	pub height: u32,
	/// Straight (non-premultiplied) RGBA, 4 bytes per pixel, row-major.
	pub rgba: Vec<u8>,
}

impl PluginInstance {
	/// Call the plugin with `PF_Cmd_ABOUT` and return the text it reports,
	/// typically its name, version and copyright.
	///
	/// # Errors
	/// [`AexloError::PluginExecutionFailed`] if the plugin rejects the command.
	pub fn about(&mut self) -> Result<String> {
		self.call_plugin(RawCommand::About, null_mut())?;

		Ok(self.message())
	}

	/// `out_flags` as the plugin declared them at `PF_Cmd_GLOBAL_SETUP`.
	pub fn out_flags(&self) -> crate::OutFlags {
		crate::OutFlags::from_bits(self.global_out_flags as u32)
	}

	/// `out_flags2` as the plugin declared them at `PF_Cmd_GLOBAL_SETUP`.
	pub fn out_flags2(&self) -> crate::OutFlags2 {
		crate::OutFlags2::from_bits(self.global_out_flags2 as u32)
	}

	/// Turn strict-mode instrumentation on or off for this instance (see
	/// [`Strict`](crate::Strict)). With everything off, the host behaves and
	/// costs exactly as without strict mode.
	pub fn set_strict(&mut self, strict: crate::Strict) {
		self.strict = strict;
		if let Ok(mut tracker) = self.tracker.lock() {
			tracker.strict = strict;
		}
	}

	/// The strict-mode features in effect.
	pub fn strict(&self) -> crate::Strict {
		self.strict
	}

	/// What strict mode found since the last call (violations are reported
	/// once). Unwritten output pixels are not violations the host can judge;
	/// count them with [`unwritten_pixels`](crate::unwritten_pixels) on
	/// [`Self::output`] after a render.
	pub fn strict_report(&mut self) -> crate::StrictReport {
		self.tracker
			.lock()
			.map(|mut t| std::mem::take(&mut t.report))
			.unwrap_or_default()
	}

	/// Tear the plugin down (`SEQUENCE_SETDOWN`, `GLOBAL_SETDOWN`, as on drop)
	/// and return what strict mode found, including handles and worlds the
	/// plugin never released ([`Strict::track_allocations`](crate::Strict)).
	pub fn finish(mut self) -> crate::StrictReport {
		self.teardown();
		self.strict_report()
	}

	/// Route host callbacks on this thread to this instance's tracker while
	/// the guard lives, when strict mode or an observer wants them.
	fn tracking(&self) -> Option<crate::strict::TrackGuard> {
		let wanted = self.strict.any() || self.observer.is_some();
		wanted.then(|| crate::strict::enter(Some(self.tracker.clone())))
	}

	/// Tell `observer` about every command sent to the plugin from now on and,
	/// at [`ObserveLevel::Calls`], every suite function it calls back on the
	/// dispatching thread. `None` removes it.
	pub fn set_observer(&mut self, observer: Option<Arc<dyn Observer>>, level: ObserveLevel) {
		if let Ok(mut tracker) = self.tracker.lock() {
			tracker.observer = observer.clone();
		}
		self.observer = observer.map(|observer| Installed { observer, level });
	}

	/// Get a pointer to the instance's persistent output world (`PF_LayerDef`/`PF_EffectWorld`).
	///
	/// Used by smart-render callbacks to hand back a stable pointer instead of one
	/// pointing at a temporary value that would dangle after the callback returns.
	pub(crate) fn output_world_ptr(&mut self) -> *mut after_effects_sys::PF_EffectWorld {
		&mut self.world as *mut after_effects_sys::PF_LayerDef as *mut after_effects_sys::PF_EffectWorld
	}

	/// Get a pointer to the instance's persistent input world (`PF_LayerDef`/`PF_EffectWorld`).
	///
	/// Used by smart-render `checkout_layer_pixels` to hand back a stable pointer to
	/// the input layer, kept in sync with `input_layer` by [`Self::set_input`].
	pub(crate) fn input_world_ptr(&mut self) -> *mut after_effects_sys::PF_EffectWorld {
		&mut self.input_world as *mut after_effects_sys::PF_LayerDef as *mut after_effects_sys::PF_EffectWorld
	}

	/// Borrow the instance's GPU context (Metal or CUDA), if GPU rendering is active.
	///
	/// Used by [`PF_GPUDeviceSuite1`](crate::suites) callbacks (recovered via
	/// `effect_ref`) to answer `GetDeviceInfo`/`GetGPUWorldData`.
	pub(crate) fn gpu_context(&self) -> Option<&crate::gpu::GpuContext> {
		self.gpu_context.as_ref()
	}

	/// Mutably borrow the instance's GPU context, if GPU rendering is active.
	///
	/// Used by [`PF_GPUDeviceSuite1`](crate::suites) callbacks that allocate or
	/// release device memory (`AllocateDeviceMemory`/`FreeDeviceMemory`).
	pub(crate) fn gpu_context_mut(&mut self) -> Option<&mut crate::gpu::GpuContext> {
		self.gpu_context.as_mut()
	}

	/// The dynamic library this instance `dlopen`ed, if any. Used by the
	/// `get_platform_data` callback to answer plugin path queries.
	pub(crate) fn resolved_binary_path(&self) -> Option<&Path> {
		self.resolved_binary_path.as_deref()
	}

	/// Get a PluginInstance pointer from an effect reference pointer.
	///
	/// The returned pointer does not imply unique mutable access.
	/// Callers must uphold aliasing rules before dereferencing.
	pub(crate) fn get_instance_ptr(effect_ref: PF_ProgPtr) -> Option<NonNull<PluginInstance>> {
		if effect_ref.is_null() {
			return None;
		}

		NonNull::new(effect_ref as *mut PluginInstance)
	}

	// ---- Getter ------------------------------------------
	/// Get input layer dimensions in pixels (width, height).
	pub fn input_size(&self) -> (u32, u32) {
		(self.input_layer.width(), self.input_layer.height())
	}

	/// Get output dimensions in pixel (width, height).
	pub fn output_size(&self) -> (u32, u32) {
		(self.output_layer.width(), self.output_layer.height())
	}

	/// The label the plugin set for its Options button
	/// (`PF_EffectUISuite1::PF_SetOptionsButtonName`), if any.
	pub fn options_button_name(&self) -> Option<&str> {
		self.options_button_name.as_deref()
	}

	pub(crate) fn set_options_button_name(&mut self, name: String) {
		self.options_button_name = Some(name);
	}

	/// Pixel formats (`PF_PixelFormat` / `PrPixelFormat` FourCCs) the plugin
	/// registered via the "PF Pixel Format Suite", in registration order. 8-bit
	/// ARGB is implied and only listed if registered explicitly.
	pub fn supported_pixel_formats(&self) -> &[crate::PixelFormat] {
		&self.supported_pixel_formats
	}

	pub(crate) fn add_supported_pixel_format(&mut self, format: u32) {
		let format = crate::PixelFormat::from_fourcc(format);
		if !self.supported_pixel_formats.contains(&format) {
			self.supported_pixel_formats.push(format);
		}
	}

	pub(crate) fn clear_supported_pixel_formats(&mut self) {
		self.supported_pixel_formats.clear();
	}

	/// Whether the plugin's iterate callbacks (`PF_Iterate*Suite`, the legacy
	/// `utils->iterate*` and `iterate_generic`) may run on worker threads.
	///
	/// On by default, as in After Effects. Turn it off for plugins whose pixel
	/// callbacks rely on running on the thread that called iterate -- notably
	/// plugins built on the Rust `after-effects` crate that acquire suites
	/// inside the callback (its suite pointer lives in a thread-local set on
	/// entry to `EffectMain`, so such a call panics on a worker thread and
	/// aborts the process). Every callback then runs in order on the calling
	/// thread.
	pub fn set_parallel_iterate(&mut self, parallel: bool) {
		self.parallel_iterate = parallel;
	}

	/// See [`Self::set_parallel_iterate`].
	pub fn parallel_iterate(&self) -> bool {
		self.parallel_iterate
	}

	/// Get the output message from the instance (set during `PF_Cmd_ABOUT` command).
	///
	/// The message may contain line breaks and special characters (e.g. \r, \n).
	/// Invalid UTF-8 sequences are replaced with the Unicode replacement character (�).
	fn message(&self) -> String {
		let bytes = &self.out_data.return_msg;

		// Cramp the buffer at the first null byte (if any) to avoid trailing garbage
		let cramped_length = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());

		// SAFETY: `c_char` and `u8` share size and alignment; only the sign interpretation differs, which is irrelevant when reading raw bytes.
		let utf8: &[u8] = unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const u8, cramped_length) };

		String::from_utf8_lossy(utf8).into_owned()
	}
}