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
use std::ptr::{null, null_mut};

use after_effects_sys::*;

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

//==== Stub implementations ================================
unsafe extern "C" fn checkout_layer_stub(
	effect_ref: PF_ProgPtr,
	index: PF_ParamIndex,
	checkout_idL: A_long,
	req: *const after_effects_sys::PF_RenderRequest,
	_what_time: A_long,
	_time_step: A_long,
	_time_scale: A_u_long,
	checkout_result: *mut after_effects_sys::PF_CheckoutResult,
) -> PF_Err {
	crate::core::ffi::guard("checkout_layer_stub", || {
		//== Validation ==//
		if effect_ref.is_null() {
			log::error!("checkout_layer: effect_ref is null");
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		if req.is_null() {
			log::error!("checkout_layer: request pointer is null");
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		if checkout_result.is_null() {
			log::error!("checkout_layer: checkout_result pointer is null");
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		//== Implementation ==//
		// Report the actual size of the checked-out layer (the input layer for
		// index 0, a linked layer parameter otherwise), not the compile-time
		// default. An unlinked layer parameter checks out as an empty layer.
		// Remember which layer this checkout id refers to, for
		// `checkout_layer_pixels`.
		let (layer_w, layer_h) = match PluginInstance::get_instance_ptr(effect_ref) {
			Some(mut instance) => {
				// SAFETY: `effect_ref` is the `PluginInstance` aexlo handed the plugin in `in_data`, and the plugin calls back during one of that instance's commands (see `PluginInstance::get_instance_ptr`).
				let instance = unsafe { instance.as_mut() };
				let index = usize::try_from(index).unwrap_or(0);
				instance.record_layer_checkout(checkout_idL, index);
				instance.layer_param_size(index).unwrap_or((0, 0))
			}
			None => (WIDTH as i32, HEIGHT as i32),
		};

		let result = after_effects_sys::PF_CheckoutResult {
			result_rect: after_effects_sys::PF_Rect {
				left: 0,
				top: 0,
				right: layer_w,
				bottom: layer_h,
			},
			max_result_rect: after_effects_sys::PF_Rect {
				left: 0,
				top: 0,
				right: layer_w,
				bottom: layer_h,
			},
			par: after_effects_sys::PF_RationalScale { num: 1, den: 1 },
			solid: 1,
			reservedB: [0; 3],
			ref_width: layer_w,
			ref_height: layer_h,
			reserved: [0; 6],
		};

		crate::strict::checkout(crate::CheckoutKind::DeclareLayer, checkout_idL, 0);

		// The plugin passes an uninitialized `PF_CheckoutResult` and reads the layer
		// bounds back out of it; leaving it unwritten hands the plugin stack garbage.
		// SAFETY: `checkout_result` is non-null (checked above) and points at the plugin's `PF_CheckoutResult`.
		unsafe { *checkout_result = result };

		diag!("PF_PreRenderCallbacks/checkout_layer",
			"effect_ref" => format!("{:#x}", effect_ref as usize),
			"index" => index,
			"checkout_idL" => checkout_idL,
			"what_time" => _what_time,
			"time_step" => _time_step,
			"time_scale" => _time_scale;
			result: format!("{:?}", result),
		);

		PF_Err_NONE as PF_Err
	})
}

unsafe extern "C" fn checkout_layer_pixels_stub(
	effect_ref: PF_ProgPtr,
	_checkout_idL: A_long,
	pixels: *mut *mut PF_EffectWorld,
) -> PF_Err {
	crate::core::ffi::guard("checkout_layer_pixels_stub", || {
		//== Validation ==//
		if effect_ref.is_null() {
			log::error!("checkout_layer_pixels: effect_ref is null");
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		if pixels.is_null() {
			log::warn!("checkout_layer_pixels: pixels pointer is null");
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		//== Implementation ==//
		// Never panic here: unwinding across the plugin's C frames is UB, so an
		// unknown effect_ref is reported as a callback error instead.
		let Some(mut instance) = PluginInstance::get_instance_ptr(effect_ref) else {
			log::error!(
				"checkout_layer_pixels: no instance found for effect_ref {:#x}",
				effect_ref as usize
			);
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		};

		// The caller passes an *uninitialized* `PF_EffectWorld*` slot (see the SDK's
		// `PF_CheckoutLayerPixels` contract) and expects us to write a pointer to the
		// checked-out world into it -- not to dereference the slot. Hand back the
		// instance's persistent world for the layer this id checked out, mirroring
		// `checkout_output`; an unlinked layer parameter yields null.
		crate::strict::checkout(crate::CheckoutKind::CheckoutLayerPixels, _checkout_idL, 0);
		// SAFETY: `effect_ref` is the `PluginInstance` aexlo handed the plugin in `in_data`, and the plugin calls back during one of that instance's commands (see `PluginInstance::get_instance_ptr`). `pixels` is non-null (checked above).
		let world = unsafe { instance.as_mut() }.checked_out_world(_checkout_idL);
		// SAFETY: `pixels` is non-null (checked above) and is the plugin's out-slot for the world pointer.
		unsafe { *pixels = world.unwrap_or(null_mut()) };

		diag!("PF_SmartRenderCallbacks/checkout_layer_pixels",
			"effect_ref" => format!("{:#x}", effect_ref as usize),
			"checkout_idL" => _checkout_idL,
			"pixels (out)" => format!("{:#x}", pixels as usize);
			result: format!("{:?}", world),
		);

		PF_Err_NONE as PF_Err
	})
}

unsafe extern "C" fn checkin_layer_pixels_stub(_effect_ref: PF_ProgPtr, _checkout_idL: A_long) -> PF_Err {
	crate::core::ffi::guard("checkin_layer_pixels_stub", || {
		crate::strict::checkout(crate::CheckoutKind::CheckinLayerPixels, _checkout_idL, 0);
		diag!("PF_SmartRenderCallbacks/checkin_layer_pixels",
			"effect_ref" => format!("{:#x}", _effect_ref as usize),
			"checkout_idL" => _checkout_idL,
		);

		PF_Err_NONE as PF_Err
	})
}

unsafe extern "C" fn checkout_output_sys(effect_ref: PF_ProgPtr, output: *mut *mut PF_EffectWorld) -> PF_Err {
	crate::core::ffi::guard("checkout_output_sys", || {
		//== Validation ==//
		if effect_ref.is_null() {
			log::error!("checkout_output: effect_ref is null");
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		if output.is_null() {
			log::error!("checkout_output: output pointer is null");
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		//== Implementation ==//
		let Some(mut instance) = PluginInstance::get_instance_ptr(effect_ref) else {
			log::error!(
				"checkout_output: No instance found for effect_ref {:#x}",
				effect_ref as usize
			);
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		};

		// Hand back a pointer into the instance's persistent output world, not a
		// pointer to a temporary `as_sys()` value (which would dangle immediately).
		// SAFETY: `effect_ref` is the `PluginInstance` aexlo handed the plugin in `in_data`, and the plugin calls back during one of that instance's commands (see `PluginInstance::get_instance_ptr`). `output` is non-null (checked above).
		unsafe { *output = instance.as_mut().output_world_ptr() };

		diag!("PF_SmartRenderCallbacks/checkout_output",
			"effect_ref" => format!("{:#x}", effect_ref as usize),
			// SAFETY: `output` is non-null (checked above) and was just written.
			"output (out)" => format!("{:#x}", unsafe { *output } as usize);
			result: format!("`output` is set to internal output layer {:#x}", output as usize),
		);

		PF_Err_NONE as PF_Err
	})
}

/// A fresh `PF_PreRenderOutput`, as handed to every `PF_Cmd_SMART_PRE_RENDER`.
fn empty_pre_render_output() -> PF_PreRenderOutput {
	PF_PreRenderOutput {
		result_rect: PF_Rect {
			left: 0,
			top: 0,
			right: 0,
			bottom: 0,
		},
		max_result_rect: PF_Rect {
			left: -1,
			top: -1,
			right: -1,
			bottom: -1,
		},
		solid: 0,
		reserved: 0,
		flags: 0,
		pre_render_data: null_mut(),
		delete_pre_render_data_func: None,
	}
}

/// Data structure to hold smart render state and provide callbacks.
pub(crate) struct SmartRenderData {
	pre_input: Box<after_effects_sys::PF_PreRenderInput>,
	pre_output: Box<after_effects_sys::PF_PreRenderOutput>,
	pre_callbacks: Box<after_effects_sys::PF_PreRenderCallbacks>,

	input: Box<after_effects_sys::PF_SmartRenderInput>,
	callbacks: Box<after_effects_sys::PF_SmartRenderCallbacks>,

	/// Bits per channel of CPU renders: the depth of the instance's worlds.
	cpu_bitdepth: i16,
}

impl SmartRenderData {
	/// Creates a new SmartRenderData with default values.
	pub fn new() -> Self {
		Self {
			pre_input: Box::new(after_effects_sys::PF_PreRenderInput {
				bitdepth: 8,
				device_index: 4294967295,
				output_request: after_effects_sys::PF_RenderRequest {
					rect: after_effects_sys::PF_LRect {
						left: 0,
						top: 0,
						right: WIDTH as i32,
						bottom: HEIGHT as i32,
					},
					field: 0,
					channel_mask: 15,
					preserve_rgb_of_zero_alpha: 0,
					unused: [0; 3],
					reserved: [0; 4],
				},
				what_gpu: 0,
				gpu_data: null(),
			}),
			pre_output: Box::new(empty_pre_render_output()),
			pre_callbacks: Box::new(after_effects_sys::PF_PreRenderCallbacks {
				checkout_layer: Some(checkout_layer_stub),
				GuidMixInPtr: None,
			}),

			input: Box::new(after_effects_sys::PF_SmartRenderInput {
				output_request: PF_RenderRequest {
					rect: PF_LRect {
						left: 0,
						top: 0,
						right: WIDTH as i32,
						bottom: HEIGHT as i32,
					},
					field: 0,
					channel_mask: 15,
					preserve_rgb_of_zero_alpha: 0,
					unused: [0; 3],
					reserved: [0; 4],
				},
				bitdepth: 8,
				pre_render_data: null_mut(),
				gpu_data: null(),
				what_gpu: 0,
				device_index: 4294967295,
			}),
			callbacks: Box::new(after_effects_sys::PF_SmartRenderCallbacks {
				checkout_layer_pixels: Some(checkout_layer_pixels_stub),
				checkin_layer_pixels: Some(checkin_layer_pixels_stub),
				checkout_output: Some(checkout_output_sys),
			}),
			cpu_bitdepth: 8,
		}
	}

	/// Returns a pointer to the PF_PreRenderExtra struct for pre-render callbacks.
	pub fn pre_render_extra(&mut self) -> PF_PreRenderExtra {
		PF_PreRenderExtra {
			input: self.pre_input.as_mut() as *mut _,
			output: self.pre_output.as_mut() as *mut _,
			cb: self.pre_callbacks.as_mut() as *mut _,
		}
	}

	/// Returns a pointer to the PF_SmartRenderExtra struct for smart render callbacks.
	pub fn smart_render_extra(&mut self) -> PF_SmartRenderExtra {
		PF_SmartRenderExtra {
			input: self.input.as_mut() as *mut _,
			cb: self.callbacks.as_mut() as *mut _,
		}
	}

	/// Syncs the smart render input with the pre-render output. Call this at the end of your pre-render callback implementation to pass data to the smart render phase.
	pub fn sync(&mut self) {
		self.input.pre_render_data = self.pre_output.pre_render_data;
	}

	/// Point the pre-render and render output-request rects at a new frame size,
	/// keeping them in step with the instance's output world (see
	/// [`PluginInstance::set_render_size`](crate::PluginInstance::set_render_size)).
	pub fn set_output_rect(&mut self, width: i32, height: i32) {
		let rect = PF_LRect {
			left: 0,
			top: 0,
			right: width,
			bottom: height,
		};
		self.pre_input.output_request.rect = rect;
		self.input.output_request.rect = rect;
	}

	/// Configure the pre-render and render inputs for GPU rendering: advertise
	/// the framework (Metal or CUDA), device, plugin-owned GPU data, and
	/// 32-bit-float depth so the plugin dispatches its `PF_Cmd_SMART_RENDER_GPU` path.
	///
	/// `gpu_data` is the handle the plugin returned from `PF_Cmd_GPU_DEVICE_SETUP`;
	/// `framework` is the active backend's `PF_GPU_Framework` constant.
	pub fn configure_gpu(
		&mut self,
		gpu_data: *const std::os::raw::c_void,
		device_index: A_u_long,
		framework: PF_GPU_Framework,
	) {
		self.pre_input.what_gpu = framework;
		self.pre_input.device_index = device_index;
		self.pre_input.bitdepth = 32;
		self.pre_input.gpu_data = gpu_data;

		self.input.what_gpu = framework;
		self.input.device_index = device_index;
		self.input.bitdepth = 32;
		self.input.gpu_data = gpu_data;
	}

	/// Prepare for a new pre-render: release the previous frame's pre-render
	/// data and reset the output the plugin fills in.
	pub fn begin_pre_render(&mut self) {
		self.dispose_pre_render_data();
		*self.pre_output = empty_pre_render_output();
	}

	/// Release the plugin's pre-render data through the delete callback it
	/// registered, as After Effects does once the frame has rendered.
	pub fn dispose_pre_render_data(&mut self) {
		let data = std::mem::replace(&mut self.pre_output.pre_render_data, null_mut());
		let delete = self.pre_output.delete_pre_render_data_func.take();
		self.input.pre_render_data = null_mut();
		// A GPU frame's callback is not invoked. Universe Glow frees that
		// block itself when the device finishes, and the host's later call is
		// a double-free: `RtlFreeHeap` inside the plugin, reached from here,
		// aborts the process (`0xC0000374`). The heap is intact when the call
		// is skipped. CPU frames stay synchronous and the plugin does not
		// free the block, so the callback still runs. One host allocation per
		// GPU frame is leaked.
		if self.is_gpu() {
			return;
		}
		if let (false, Some(delete)) = (data.is_null(), delete) {
			// SAFETY: `data` is the plugin's own pre-render data, released once
			// through the callback it registered alongside it.
			unsafe { delete(data) };
		}
	}

	/// Whether the last pre-render declared the frame renderable on the GPU
	/// (`PF_RenderOutputFlag_GPU_RENDER_POSSIBLE`).
	pub fn gpu_render_possible(&self) -> bool {
		self.pre_output.flags as i64 & PF_RenderOutputFlag_GPU_RENDER_POSSIBLE as i64 != 0
	}

	/// Whether the current render is a GPU render (see [`Self::configure_gpu`]).
	pub fn is_gpu(&self) -> bool {
		self.input.what_gpu != PF_GPU_Framework_NONE as PF_GPU_Framework
	}

	/// Set the depth CPU renders advertise (8, 16 or 32), applying it now unless
	/// a GPU render is configured.
	pub fn set_cpu_bitdepth(&mut self, bits: i16) {
		self.cpu_bitdepth = bits;
		if !self.is_gpu() {
			self.pre_input.bitdepth = bits;
			self.input.bitdepth = bits;
		}
	}

	/// Reset the pre-render and render inputs to CPU (the instance's depth, no GPU framework).
	///
	/// Used when GPU render is unavailable or fails, so a subsequent CPU
	/// smart-render fallback does not leave the plugin believing it should still
	/// produce a GPU frame.
	pub fn configure_cpu(&mut self) {
		self.pre_input.what_gpu = PF_GPU_Framework_NONE as PF_GPU_Framework;
		self.pre_input.device_index = 0;
		self.pre_input.bitdepth = self.cpu_bitdepth;
		self.pre_input.gpu_data = null();

		self.input.what_gpu = PF_GPU_Framework_NONE as PF_GPU_Framework;
		self.input.device_index = 0;
		self.input.bitdepth = self.cpu_bitdepth;
		self.input.gpu_data = null();
	}
}