rsmediainfo 0.2.0

Rust wrapper for MediaInfo library
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
//! FFI bindings for the MediaInfo C library.
//!
//! This module provides safe wrappers around the raw MediaInfo C API functions.
//! It handles dynamic library loading, wchar_t string conversion, and proper
//! resource management through RAII patterns.

use crate::error::{MediaInfoError, Result};
use libloading::{Library, Symbol};
use std::ffi::c_void;
use std::path::Path;
use std::sync::Arc;

/// Inherits the user's `LC_CTYPE` locale from the environment, once per
/// process. libmediainfo's path-fallback for non-content-detected files
/// (e.g. `.txt`) calls `mbstowcs` internally, which silently mangles
/// non-ASCII bytes when the process locale is the POSIX default `C`.
/// Rust binaries do not call `setlocale` at startup, so on Linux/macOS
/// we must do it ourselves before any libmediainfo entry point.
#[cfg(unix)]
fn ensure_locale_initialized() {
    use std::sync::OnceLock;
    static INIT: OnceLock<()> = OnceLock::new();
    INIT.get_or_init(|| unsafe {
        libc::setlocale(libc::LC_CTYPE, c"".as_ptr());
    });
}

#[cfg(not(unix))]
fn ensure_locale_initialized() {}

// Platform-specific wchar_t string types
#[cfg(windows)]
use widestring::{U16CStr, U16CString};
#[cfg(not(windows))]
use widestring::{U32CStr, U32CString};

/// Type alias for wchar_t pointer used in MediaInfo API.
/// On Windows, wchar_t is 16-bit (UTF-16). On Unix, it's 32-bit (UTF-32).
#[cfg(windows)]
type WCharPtr = *const u16;
#[cfg(not(windows))]
type WCharPtr = *const u32;

/// Function pointer types for MediaInfo C API functions.
/// These match the signatures from the MediaInfo DLL/shared library.
///
/// On Windows, use the system calling convention to match the DLL exports.
#[cfg(windows)]
type MediaInfoNew = unsafe extern "system" fn() -> *mut c_void;
#[cfg(not(windows))]
type MediaInfoNew = unsafe extern "C" fn() -> *mut c_void;

#[cfg(windows)]
type MediaInfoDelete = unsafe extern "system" fn(handle: *mut c_void);
#[cfg(not(windows))]
type MediaInfoDelete = unsafe extern "C" fn(handle: *mut c_void);

#[cfg(windows)]
type MediaInfoClose = unsafe extern "system" fn(handle: *mut c_void);
#[cfg(not(windows))]
type MediaInfoClose = unsafe extern "C" fn(handle: *mut c_void);

#[cfg(windows)]
type MediaInfoOpen = unsafe extern "system" fn(handle: *mut c_void, file: WCharPtr) -> usize;
#[cfg(not(windows))]
type MediaInfoOpen = unsafe extern "C" fn(handle: *mut c_void, file: WCharPtr) -> usize;

#[cfg(windows)]
type MediaInfoOption =
    unsafe extern "system" fn(handle: *mut c_void, option: WCharPtr, value: WCharPtr) -> WCharPtr;
#[cfg(not(windows))]
type MediaInfoOption =
    unsafe extern "C" fn(handle: *mut c_void, option: WCharPtr, value: WCharPtr) -> WCharPtr;

#[cfg(windows)]
type MediaInfoInform = unsafe extern "system" fn(handle: *mut c_void, reserved: usize) -> WCharPtr;
#[cfg(not(windows))]
type MediaInfoInform = unsafe extern "C" fn(handle: *mut c_void, reserved: usize) -> WCharPtr;

#[cfg(windows)]
type MediaInfoOpenBufferInit =
    unsafe extern "system" fn(handle: *mut c_void, file_size: u64, file_offset: u64) -> usize;
#[cfg(not(windows))]
type MediaInfoOpenBufferInit =
    unsafe extern "C" fn(handle: *mut c_void, file_size: u64, file_offset: u64) -> usize;

#[cfg(windows)]
type MediaInfoOpenBufferContinue =
    unsafe extern "system" fn(handle: *mut c_void, buffer: *const u8, buffer_size: usize) -> usize;
#[cfg(not(windows))]
type MediaInfoOpenBufferContinue =
    unsafe extern "C" fn(handle: *mut c_void, buffer: *const u8, buffer_size: usize) -> usize;

#[cfg(windows)]
type MediaInfoOpenBufferContinueGoToGet = unsafe extern "system" fn(handle: *mut c_void) -> u64;
#[cfg(not(windows))]
type MediaInfoOpenBufferContinueGoToGet = unsafe extern "C" fn(handle: *mut c_void) -> u64;

#[cfg(windows)]
type MediaInfoOpenBufferFinalize = unsafe extern "system" fn(handle: *mut c_void) -> usize;
#[cfg(not(windows))]
type MediaInfoOpenBufferFinalize = unsafe extern "C" fn(handle: *mut c_void) -> usize;

/// Container holding all loaded MediaInfo function pointers.
///
/// This struct keeps the library loaded and provides access to all
/// MediaInfo C API functions through their function pointers.
pub struct MediaInfoLib {
    /// The loaded dynamic library. Must be kept alive while functions are in use.
    #[allow(dead_code)]
    library: Library,

    /// Function pointers to the MediaInfo API
    new: MediaInfoNew,
    delete: MediaInfoDelete,
    close: MediaInfoClose,
    open: MediaInfoOpen,
    option: MediaInfoOption,
    inform: MediaInfoInform,
    open_buffer_init: MediaInfoOpenBufferInit,
    open_buffer_continue: MediaInfoOpenBufferContinue,
    open_buffer_continue_goto_get: MediaInfoOpenBufferContinueGoToGet,
    open_buffer_finalize: MediaInfoOpenBufferFinalize,
}

impl MediaInfoLib {
    /// Loads the MediaInfo library from the specified path.
    ///
    /// This function attempts to load the library and resolve all required
    /// function symbols. If any symbol cannot be found, an error is returned.
    pub fn load<P: AsRef<Path>>(library_path: P) -> Result<Self> {
        ensure_locale_initialized();

        let path = library_path.as_ref();

        let library = unsafe { Library::new(path) }.map_err(|e| {
            MediaInfoError::library_not_found(&[path.display().to_string()], &[e.to_string()])
        })?;

        macro_rules! load_symbol {
            ($lib:expr, $name:literal, $type:ty) => {{
                let sym: Symbol<$type> = unsafe { $lib.get($name) }.map_err(|e| {
                    MediaInfoError::library_not_found(
                        &[path.display().to_string()],
                        &[e.to_string()],
                    )
                })?;
                // Copy the raw function pointer out before `sym` (which holds
                // a borrow of the library) is dropped at the end of this expr.
                *sym
            }};
        }

        // Load all function symbols and extract their raw pointers
        let new_fn = load_symbol!(library, b"MediaInfo_New\0", MediaInfoNew);
        let delete_fn = load_symbol!(library, b"MediaInfo_Delete\0", MediaInfoDelete);
        let close_fn = load_symbol!(library, b"MediaInfo_Close\0", MediaInfoClose);
        let open_fn = load_symbol!(library, b"MediaInfo_Open\0", MediaInfoOpen);
        let option_fn = load_symbol!(library, b"MediaInfo_Option\0", MediaInfoOption);
        let inform_fn = load_symbol!(library, b"MediaInfo_Inform\0", MediaInfoInform);
        let open_buffer_init_fn = load_symbol!(
            library,
            b"MediaInfo_Open_Buffer_Init\0",
            MediaInfoOpenBufferInit
        );
        let open_buffer_continue_fn = load_symbol!(
            library,
            b"MediaInfo_Open_Buffer_Continue\0",
            MediaInfoOpenBufferContinue
        );
        let open_buffer_continue_goto_get_fn = load_symbol!(
            library,
            b"MediaInfo_Open_Buffer_Continue_GoTo_Get\0",
            MediaInfoOpenBufferContinueGoToGet
        );
        let open_buffer_finalize_fn = load_symbol!(
            library,
            b"MediaInfo_Open_Buffer_Finalize\0",
            MediaInfoOpenBufferFinalize
        );

        Ok(MediaInfoLib {
            library,
            new: new_fn,
            delete: delete_fn,
            close: close_fn,
            open: open_fn,
            option: option_fn,
            inform: inform_fn,
            open_buffer_init: open_buffer_init_fn,
            open_buffer_continue: open_buffer_continue_fn,
            open_buffer_continue_goto_get: open_buffer_continue_goto_get_fn,
            open_buffer_finalize: open_buffer_finalize_fn,
        })
    }

    /// Attempts to load the MediaInfo library from multiple paths.
    ///
    /// Tries each path in order and returns the first successful load.
    /// If all paths fail, returns an error with all attempted paths and their errors.
    pub fn load_from_paths(paths: &[std::path::PathBuf]) -> Result<Self> {
        let mut attempted_paths = Vec::new();
        let mut errors = Vec::new();

        for path in paths {
            match Self::load(path) {
                Ok(lib) => return Ok(lib),
                Err(e) => {
                    attempted_paths.push(path.display().to_string());
                    let message = match e {
                        MediaInfoError::LibraryNotFound {
                            errors: error_message,
                            ..
                        } => error_message,
                        other => other.to_string(),
                    };
                    errors.push(message);
                }
            }
        }

        // If we get here, all paths failed
        Err(MediaInfoError::library_not_found(&attempted_paths, &errors))
    }

    /// Creates a new MediaInfo handle.
    pub fn new_handle(&self) -> *mut c_void {
        unsafe { (self.new)() }
    }

    /// Deletes a MediaInfo handle.
    ///
    /// This must be called to free resources when done with a handle.
    pub fn delete_handle(&self, handle: *mut c_void) {
        unsafe { (self.delete)(handle) }
    }

    /// Closes a MediaInfo handle.
    ///
    /// This releases the file/stream but does not delete the handle.
    pub fn close_handle(&self, handle: *mut c_void) {
        unsafe { (self.close)(handle) }
    }

    /// Opens a file for analysis.
    ///
    /// Returns the number of streams found, or 0 on error.
    pub fn open(&self, handle: *mut c_void, filename: &str) -> usize {
        let wchar_filename = str_to_wchar(filename);
        unsafe { (self.open)(handle, wchar_filename.as_ptr()) }
    }

    /// Sets or retrieves a MediaInfo option.
    ///
    /// Returns the option value (may be empty string for set operations).
    pub fn option(&self, handle: *mut c_void, option_name: &str, option_value: &str) -> String {
        let wchar_option = str_to_wchar(option_name);
        let wchar_value = str_to_wchar(option_value);
        let result = unsafe { (self.option)(handle, wchar_option.as_ptr(), wchar_value.as_ptr()) };
        wchar_ptr_to_string(result)
    }

    /// Gets information about the analyzed file.
    ///
    /// The format depends on the "Inform" option setting.
    /// The `reserved` parameter should always be 0.
    pub fn inform(&self, handle: *mut c_void) -> String {
        let result = unsafe { (self.inform)(handle, 0) };
        wchar_ptr_to_string(result)
    }

    /// Initializes buffer-based parsing.
    ///
    /// Used for parsing from file-like objects instead of file paths.
    pub fn open_buffer_init(&self, handle: *mut c_void, file_size: u64, file_offset: u64) -> usize {
        unsafe { (self.open_buffer_init)(handle, file_size, file_offset) }
    }

    /// Continues buffer-based parsing with more data.
    ///
    /// Returns a bitfield status:
    /// - Bit 0 (0x01): Accepted - the buffer was processed
    /// - Bit 1 (0x02): Filled - enough data has been received
    /// - Bit 2 (0x04): Updated - information was updated
    /// - Bit 3 (0x08): Finalized - parsing is complete, no more data needed
    pub fn open_buffer_continue(&self, handle: *mut c_void, buffer: &[u8]) -> usize {
        unsafe { (self.open_buffer_continue)(handle, buffer.as_ptr(), buffer.len()) }
    }

    /// Gets the seek position requested by MediaInfo.
    ///
    /// Returns u64::MAX if no seek is needed, otherwise returns the
    /// position to seek to.
    pub fn open_buffer_continue_goto_get(&self, handle: *mut c_void) -> u64 {
        unsafe { (self.open_buffer_continue_goto_get)(handle) }
    }

    /// Finalizes buffer-based parsing.
    ///
    /// Must be called after all data has been provided.
    pub fn open_buffer_finalize(&self, handle: *mut c_void) -> usize {
        unsafe { (self.open_buffer_finalize)(handle) }
    }
}

/// RAII wrapper for a MediaInfo handle.
///
/// Ensures proper cleanup when the handle goes out of scope.
pub struct MediaInfoHandle {
    /// Reference to the loaded library
    lib: Arc<MediaInfoLib>,
    /// The raw handle pointer
    handle: *mut c_void,
}

impl MediaInfoHandle {
    /// Creates a new MediaInfo handle using the provided library.
    pub fn new(lib: Arc<MediaInfoLib>) -> Self {
        let handle = lib.new_handle();
        MediaInfoHandle { lib, handle }
    }

    /// Returns the raw handle pointer for FFI calls.
    #[allow(dead_code)]
    pub fn as_ptr(&self) -> *mut c_void {
        self.handle
    }

    /// Opens a file for analysis.
    pub fn open(&self, filename: &str) -> usize {
        self.lib.open(self.handle, filename)
    }

    /// Sets or retrieves a MediaInfo option.
    pub fn option(&self, option_name: &str, option_value: &str) -> String {
        self.lib.option(self.handle, option_name, option_value)
    }

    /// Gets information about the analyzed file.
    pub fn inform(&self) -> String {
        self.lib.inform(self.handle)
    }

    /// Initializes buffer-based parsing.
    pub fn open_buffer_init(&self, file_size: u64, file_offset: u64) -> usize {
        self.lib
            .open_buffer_init(self.handle, file_size, file_offset)
    }

    /// Continues buffer-based parsing.
    pub fn open_buffer_continue(&self, buffer: &[u8]) -> usize {
        self.lib.open_buffer_continue(self.handle, buffer)
    }

    /// Gets the requested seek position.
    pub fn open_buffer_continue_goto_get(&self) -> u64 {
        self.lib.open_buffer_continue_goto_get(self.handle)
    }

    /// Finalizes buffer-based parsing.
    pub fn open_buffer_finalize(&self) -> usize {
        self.lib.open_buffer_finalize(self.handle)
    }

    /// Closes the handle (releases file/stream).
    #[allow(dead_code)]
    pub fn close(&self) {
        self.lib.close_handle(self.handle);
    }
}

impl Drop for MediaInfoHandle {
    fn drop(&mut self) {
        self.lib.close_handle(self.handle);
        self.lib.delete_handle(self.handle);
    }
}

/// Converts a Rust string to a platform-specific wide character string.
///
/// On Windows, this produces UTF-16. On Unix, this produces UTF-32.
#[cfg(windows)]
fn str_to_wchar(s: &str) -> U16CString {
    U16CString::from_str(s).unwrap_or_else(|_| U16CString::default())
}

#[cfg(not(windows))]
fn str_to_wchar(s: &str) -> U32CString {
    U32CString::from_str(s).unwrap_or_else(|_| U32CString::default())
}

/// Converts a wchar_t pointer to a Rust String.
///
/// Returns an empty string if the pointer is null. This conversion is lossy
/// and will replace invalid sequences to keep parsing deterministic.
#[cfg(windows)]
fn wchar_ptr_to_string(ptr: WCharPtr) -> String {
    if ptr.is_null() {
        return String::new();
    }
    unsafe { U16CStr::from_ptr_str(ptr).to_string_lossy() }
}

#[cfg(not(windows))]
fn wchar_ptr_to_string(ptr: WCharPtr) -> String {
    if ptr.is_null() {
        return String::new();
    }
    unsafe { U32CStr::from_ptr_str(ptr).to_string_lossy() }
}

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

    #[test]
    fn test_str_to_wchar_empty() {
        let wchar = str_to_wchar("");
        assert_eq!(wchar.len(), 0);
    }

    #[test]
    fn test_str_to_wchar_ascii() {
        let wchar = str_to_wchar("hello");
        assert_eq!(wchar.len(), 5);
    }

    #[test]
    fn test_str_to_wchar_unicode() {
        // Exercises a non-ASCII string with combining accents to make sure
        // the wide-string conversion does not silently drop characters.
        let wchar = str_to_wchar("accentué");
        assert!(!wchar.is_empty());
    }

    #[test]
    fn test_wchar_ptr_null() {
        let result = wchar_ptr_to_string(std::ptr::null());
        assert!(result.is_empty());
    }
}