aviutl2 0.44.0

AviUtl2 SDKのRustラッパー
Documentation
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
use std::num::NonZeroIsize;

use crate::{
    common::{AnyResult, LeakManager, format_file_filters},
    output::{FromRawAudioSamples, OutputInfo, OutputPlugin},
};

use aviutl2_sys::common::{WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};

pub struct InternalOutputPluginState<T: Send + Sync + OutputPlugin> {
    leak_manager: LeakManager,
    global_leak_manager: LeakManager,

    instance: T,
}

impl<T: Send + Sync + OutputPlugin> InternalOutputPluginState<T> {
    pub fn new(instance: T) -> Self {
        Self {
            leak_manager: LeakManager::new(),
            global_leak_manager: LeakManager::new(),
            instance,
        }
    }
}

impl FromRawAudioSamples for f32 {
    const FORMAT: u32 = WAVE_FORMAT_IEEE_FLOAT;

    unsafe fn from_raw(length: i32, num_channels: u32, frame_data_ptr: *const u8) -> Vec<Self> {
        let frame_data_slice = unsafe {
            std::slice::from_raw_parts(
                frame_data_ptr as *const f32,
                length as usize * num_channels as usize,
            )
        };
        frame_data_slice.to_vec()
    }
}
impl FromRawAudioSamples for i16 {
    const FORMAT: u32 = WAVE_FORMAT_PCM;

    unsafe fn from_raw(length: i32, num_channels: u32, frame_data_ptr: *const u8) -> Vec<Self> {
        let frame_data_slice = unsafe {
            std::slice::from_raw_parts(
                frame_data_ptr as *const i16,
                length as usize * num_channels as usize,
            )
        };
        frame_data_slice.to_vec()
    }
}

pub unsafe fn initialize_plugin_c<T: OutputSingleton>(version: u32) -> bool {
    match initialize_plugin::<T>(version) {
        Ok(_) => true,
        Err(e) => {
            tracing::error!("Failed to initialize plugin: {}", e);
            let _ = crate::logger::write_error_log(&format!("{e}"));
            false
        }
    }
}

pub unsafe fn initialize_plugin_c_unwind<T: OutputSingleton>(version: u32) -> bool {
    match crate::utils::catch_unwind_with_panic_info(|| unsafe {
        initialize_plugin_c::<T>(version)
    }) {
        Ok(result) => result,
        Err(panic_info) => {
            tracing::error!(
                "Panic occurred during plugin initialization: {}",
                panic_info
            );
            let _ = crate::logger::write_error_log(&panic_info);
            false
        }
    }
}

pub(crate) fn initialize_plugin<T: OutputSingleton>(version: u32) -> AnyResult<()> {
    crate::common::ensure_minimum_aviutl2_version(version.into())?;
    let plugin_state = T::__get_singleton_state();
    let info = crate::common::AviUtl2Info {
        version: version.into(),
    };
    let internal = T::new(info)?;
    let plugin = InternalOutputPluginState::new(internal);
    *plugin_state.write().unwrap() = Some(plugin);

    Ok(())
}

pub unsafe fn uninitialize_plugin<T: OutputSingleton>() {
    let plugin_state = T::__get_singleton_state();
    let mut plugin_state = plugin_state.write().unwrap();
    *plugin_state = None;
}

pub unsafe fn uninitialize_plugin_c_unwind<T: OutputSingleton>() {
    match crate::utils::catch_unwind_with_panic_info(|| unsafe { uninitialize_plugin::<T>() }) {
        Ok(()) => {}
        Err(panic_info) => {
            tracing::error!(
                "Panic occurred during plugin uninitialization: {}",
                panic_info
            );
            let _ = crate::logger::write_error_log(&panic_info);
        }
    }
}

fn create_table_impl<T: OutputSingleton>(
    unwind: bool,
) -> *mut aviutl2_sys::output2::OUTPUT_PLUGIN_TABLE {
    let plugin_state = T::__get_singleton_state();
    let mut plugin_state = plugin_state.write().unwrap();
    let plugin_state = plugin_state.as_mut().expect("Plugin not initialized");
    tracing::info!("Creating OUTPUT_PLUGIN_TABLE");
    plugin_state.leak_manager.free_leaked_memory();
    let plugin = &plugin_state.instance;
    let plugin_info = plugin.plugin_info();
    let filefilter = format_file_filters(&plugin_info.file_filters);

    let name = plugin_info.name.clone();
    let information = plugin_info.information.clone();

    let func_output = if unwind {
        func_output_unwind::<T>
    } else {
        func_output::<T>
    };
    let func_config = if unwind {
        func_config_unwind::<T>
    } else {
        func_config::<T>
    };
    let func_get_config_text = if unwind {
        func_get_config_text_unwind::<T>
    } else {
        func_get_config_text::<T>
    };
    let func_load_project_config = if unwind {
        func_load_project_config_unwind::<T>
    } else {
        func_load_project_config::<T>
    };
    let func_save_project_config = if unwind {
        func_save_project_config_unwind::<T>
    } else {
        func_save_project_config::<T>
    };

    // NOTE: プラグイン名などの文字列はAviUtlが終了するまで解放しない
    let table = aviutl2_sys::output2::OUTPUT_PLUGIN_TABLE {
        flag: plugin_info.output_type.to_bits()
            | if plugin_info.project_config {
                aviutl2_sys::output2::OUTPUT_PLUGIN_TABLE::FLAG_PROJECT_CONFIG
            } else {
                0
            },
        name: plugin_state.global_leak_manager.leak_as_wide_string(&name),
        filefilter: plugin_state
            .global_leak_manager
            .leak_as_wide_string(&filefilter),
        information: plugin_state
            .global_leak_manager
            .leak_as_wide_string(&information),
        func_output: Some(func_output),
        func_config: plugin_info.can_config.then_some(func_config),
        func_get_config_text: Some(func_get_config_text),
        func_load_project_config: plugin_info
            .project_config
            .then_some(func_load_project_config),
        func_save_project_config: plugin_info
            .project_config
            .then_some(func_save_project_config),
    };
    let table = Box::new(table);
    Box::leak(table)
}

pub unsafe fn create_table<T: OutputSingleton>() -> *mut aviutl2_sys::output2::OUTPUT_PLUGIN_TABLE {
    create_table_impl::<T>(false)
}

pub unsafe fn create_table_unwind<T: OutputSingleton>()
-> *mut aviutl2_sys::output2::OUTPUT_PLUGIN_TABLE {
    match crate::utils::catch_unwind_with_panic_info(|| create_table_impl::<T>(true)) {
        Ok(table) => table,
        Err(panic_info) => {
            tracing::error!("Panic occurred during create_table: {}", panic_info);
            let _ = crate::logger::write_error_log(&panic_info);
            std::ptr::null_mut()
        }
    }
}

extern "C" fn func_output<T: OutputSingleton>(oip: *mut aviutl2_sys::output2::OUTPUT_INFO) -> bool {
    let plugin_state = T::__get_singleton_state();
    let plugin_state = plugin_state.read().unwrap();
    let plugin_state = plugin_state.as_ref().expect("Plugin not initialized");
    plugin_state.leak_manager.free_leaked_memory();
    let plugin = &plugin_state.instance;
    let oip = unsafe { &mut *oip };
    let output_info = OutputInfo::from_raw(oip);
    match plugin.output(output_info) {
        Ok(()) => true,
        Err(e) => {
            tracing::error!("Error during func_output: {}", e);
            let _ = crate::logger::write_error_log(&format!("{e}"));
            false
        }
    }
}
extern "C" fn func_output_unwind<T: OutputSingleton>(
    oip: *mut aviutl2_sys::output2::OUTPUT_INFO,
) -> bool {
    match crate::utils::catch_unwind_with_panic_info(|| func_output::<T>(oip)) {
        Ok(result) => result,
        Err(panic_info) => {
            tracing::error!("Panic occurred during func_output: {}", panic_info);
            let _ = crate::logger::write_error_log(&panic_info);
            false
        }
    }
}

extern "C" fn func_config<T: OutputSingleton>(
    hwnd: aviutl2_sys::output2::HWND,
    dll_hinst: aviutl2_sys::output2::HINSTANCE,
) -> bool {
    let plugin_state = T::__get_singleton_state();
    let plugin_state = plugin_state.read().unwrap();
    let plugin_state = plugin_state.as_ref().expect("Plugin not initialized");
    plugin_state.leak_manager.free_leaked_memory();
    let plugin = &plugin_state.instance;
    let mut handle =
        raw_window_handle::Win32WindowHandle::new(NonZeroIsize::new(hwnd as isize).unwrap());
    handle.hinstance = Some(NonZeroIsize::new(dll_hinst as isize).unwrap());
    match plugin.config(handle) {
        Ok(()) => true,
        Err(e) => {
            tracing::error!("Error during func_config: {}", e);
            let _ = crate::logger::write_error_log(&format!("{e}"));
            false
        }
    }
}
extern "C" fn func_config_unwind<T: OutputSingleton>(
    hwnd: aviutl2_sys::output2::HWND,
    dll_hinst: aviutl2_sys::output2::HINSTANCE,
) -> bool {
    match crate::utils::catch_unwind_with_panic_info(|| func_config::<T>(hwnd, dll_hinst)) {
        Ok(result) => result,
        Err(panic_info) => {
            tracing::error!("Panic occurred during func_config: {}", panic_info);
            let _ = crate::logger::write_error_log(&panic_info);
            false
        }
    }
}

extern "C" fn func_get_config_text<T: OutputSingleton>() -> *const u16 {
    let plugin_state = T::__get_singleton_state();
    let plugin_state = plugin_state.read().unwrap();
    let plugin_state = plugin_state.as_ref().expect("Plugin not initialized");
    plugin_state.leak_manager.free_leaked_memory();
    let plugin = &plugin_state.instance;
    let text = plugin.config_text();
    match text {
        Ok(text) => plugin_state.leak_manager.leak_as_wide_string(&text),
        Err(e) => {
            tracing::error!("Error during func_get_config_text: {}", e);
            plugin_state
                .leak_manager
                .leak_as_wide_string(format!("エラー:{}", e).as_str())
        }
    }
}
extern "C" fn func_get_config_text_unwind<T: OutputSingleton>() -> *const u16 {
    match crate::utils::catch_unwind_with_panic_info(|| func_get_config_text::<T>()) {
        Ok(text) => text,
        Err(panic_info) => {
            tracing::error!("Panic occurred during func_get_config_text: {}", panic_info);
            let _ = crate::logger::write_error_log(&panic_info);
            std::ptr::null()
        }
    }
}

extern "C" fn func_load_project_config<T: OutputSingleton>(
    project: *mut aviutl2_sys::plugin2::PROJECT_FILE,
) -> bool {
    let plugin_state = T::__get_singleton_state();
    let plugin_state = plugin_state.read().unwrap();
    let plugin_state = plugin_state.as_ref().expect("Plugin not initialized");
    plugin_state.leak_manager.free_leaked_memory();
    let plugin = &plugin_state.instance;
    let mut project = unsafe { crate::generic::ProjectFile::from_raw(project) };
    match plugin.load_project_config(&mut project) {
        Ok(()) => true,
        Err(e) => {
            tracing::error!("Error during func_load_project_config: {}", e);
            let _ = crate::logger::write_error_log(&format!("{e}"));
            false
        }
    }
}

extern "C" fn func_save_project_config<T: OutputSingleton>(
    project: *mut aviutl2_sys::plugin2::PROJECT_FILE,
) -> bool {
    let plugin_state = T::__get_singleton_state();
    let plugin_state = plugin_state.read().unwrap();
    let plugin_state = plugin_state.as_ref().expect("Plugin not initialized");
    plugin_state.leak_manager.free_leaked_memory();
    let plugin = &plugin_state.instance;
    let mut project = unsafe { crate::generic::ProjectFile::from_raw(project) };
    match plugin.save_project_config(&mut project) {
        Ok(()) => true,
        Err(e) => {
            tracing::error!("Error during func_save_project_config: {}", e);
            let _ = crate::logger::write_error_log(&format!("{e}"));
            false
        }
    }
}

extern "C" fn func_load_project_config_unwind<T: OutputSingleton>(
    project: *mut aviutl2_sys::plugin2::PROJECT_FILE,
) -> bool {
    match crate::utils::catch_unwind_with_panic_info(|| func_load_project_config::<T>(project)) {
        Ok(result) => result,
        Err(panic_info) => {
            tracing::error!(
                "Panic occurred during func_load_project_config: {}",
                panic_info
            );
            let _ = crate::logger::write_error_log(&panic_info);
            false
        }
    }
}

extern "C" fn func_save_project_config_unwind<T: OutputSingleton>(
    project: *mut aviutl2_sys::plugin2::PROJECT_FILE,
) -> bool {
    match crate::utils::catch_unwind_with_panic_info(|| func_save_project_config::<T>(project)) {
        Ok(result) => result,
        Err(panic_info) => {
            tracing::error!(
                "Panic occurred during func_save_project_config: {}",
                panic_info
            );
            let _ = crate::logger::write_error_log(&panic_info);
            false
        }
    }
}

pub trait OutputSingleton
where
    Self: 'static + Send + Sync + crate::output::OutputPlugin,
{
    fn __get_singleton_state()
    -> &'static std::sync::RwLock<Option<crate::output::__bridge::InternalOutputPluginState<Self>>>;
    fn with_instance<R>(f: impl FnOnce(&Self) -> R) -> R {
        let lock = Self::__get_singleton_state();
        let guard = lock.read().unwrap();
        let state = guard.as_ref().expect("Plugin not initialized");
        f(&state.instance)
    }
    fn with_instance_mut<R>(f: impl FnOnce(&mut Self) -> R) -> R {
        let lock = Self::__get_singleton_state();
        let mut guard = lock.write().unwrap();
        let state = guard.as_mut().expect("Plugin not initialized");
        f(&mut state.instance)
    }
}

/// 出力プラグインを登録するマクロ。
///
/// # Arguments
///
/// - `unwind`: panic時にunwindするかどうか。デフォルトは`true`。
#[macro_export]
macro_rules! register_output_plugin {
    ($struct:ident, $($key:ident = $value:expr),* $(,)?) => {
        $crate::__internal_module! {
            #[unsafe(no_mangle)]
            unsafe extern "C" fn RequiredVersion() -> u32 {
                $crate::MINIMUM_AVIUTL2_VERSION.into()
            }

            #[unsafe(no_mangle)]
            unsafe extern "C" fn InitializeLogger(logger: *mut $crate::sys::logger2::LOG_HANDLE) {
                $crate::comptime_if::comptime_if! {
                    if unwind where (unwind = true, $( $key = $value ),* ) {
                        $crate::logger::__initialize_logger_unwind(logger)
                    } else {
                        $crate::logger::__initialize_logger(logger)
                    }
                }
            }

            #[unsafe(no_mangle)]
            unsafe extern "C" fn InitializeConfig(
                config: *mut $crate::sys::config2::CONFIG_HANDLE
            ) {
                $crate::comptime_if::comptime_if! {
                    if unwind where (unwind = true, $( $key = $value ),* ) {
                        $crate::config::__initialize_config_handle_unwind(config)
                    } else {
                        $crate::config::__initialize_config_handle(config)
                    }
                }
            }

            #[unsafe(no_mangle)]
            unsafe extern "C" fn InitializeCache(
                cache: *mut $crate::sys::cache2::CACHE_HANDLE
            ) {
                $crate::comptime_if::comptime_if! {
                    if unwind where (unwind = true, $( $key = $value ),* ) {
                        $crate::cache::__initialize_cache_unwind(cache)
                    } else {
                        $crate::cache::__initialize_cache(cache)
                    }
                }
            }

            #[unsafe(no_mangle)]
            unsafe extern "C" fn InitializePlugin(version: u32) -> bool {
                unsafe {
                    $crate::comptime_if::comptime_if! {
                        if unwind where (unwind = true, $( $key = $value ),* ) {
                            $crate::output::__bridge::initialize_plugin_c_unwind::<$struct>(version)
                        } else {
                            $crate::output::__bridge::initialize_plugin_c::<$struct>(version)
                        }
                    }
                }
            }

            #[unsafe(no_mangle)]
            unsafe extern "C" fn UninitializePlugin() {
                unsafe {
                    $crate::comptime_if::comptime_if! {
                        if unwind where (unwind = true, $( $key = $value ),* ) {
                            $crate::output::__bridge::uninitialize_plugin_c_unwind::<$struct>()
                        } else {
                            $crate::output::__bridge::uninitialize_plugin::<$struct>()
                        }
                    }
                }
            }

            #[unsafe(no_mangle)]
            unsafe extern "C" fn GetOutputPluginTable()
            -> *mut aviutl2::sys::output2::OUTPUT_PLUGIN_TABLE {
                $crate::comptime_if::comptime_if! {
                    if unwind where (unwind = true, $( $key = $value ),* ) {
                        unsafe { $crate::output::__bridge::create_table_unwind::<$struct>() }
                    } else {
                        unsafe { $crate::output::__bridge::create_table::<$struct>() }
                    }
                }
            }
        }
    };
    ($struct:ident, $($key:ident),* $(,)?) => {
        $crate::register_output_plugin!($struct, $( $key = true ),* );
    };
    ($struct:ident) => {
        $crate::register_output_plugin!($struct, );
    };
}