glycin-ng 0.1.0

Permissively-licensed Rust image decoder library with in-process sandboxing
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
//! C ABI surface exposed by the `cdylib` build of this crate.
//!
//! Every function is `#[no_mangle] extern "C"` and uses opaque
//! heap-allocated handles. Callers free the handles they created;
//! everything else is borrowed from those handles and remains valid
//! until the handle that owns it is freed.
//!
//! # Error handling
//!
//! Fallible functions return either a non-NULL handle on success and
//! NULL on error, or `0` on success and a non-zero error code on
//! failure. After a failed call, [`glycin_ng_last_error`] returns a
//! NUL-terminated message describing what went wrong, valid until
//! the next call that produces (or clears) an error on the same
//! thread.
//!
//! # Threads
//!
//! Handles are not thread-safe; do not share a single handle across
//! threads without external synchronization. The last-error message
//! is thread-local.
//!
//! Every `unsafe extern "C" fn` in this module requires its handle
//! arguments to be either NULL or valid pointers returned by an
//! earlier function in this module. Functions that may consume or
//! free a handle document the resulting ownership transfer in their
//! item docs.

#![allow(clippy::missing_safety_doc)]

use std::cell::RefCell;
use std::ffi::{CStr, CString, c_char, c_int, c_uint};
use std::path::PathBuf;
use std::ptr;
use std::slice;

use crate::{Error, Frame, Image, KnownFormat, Loader, MemoryFormat, SandboxSelector, Texture};

/// Opaque [`Loader`] handle.
#[repr(C)]
pub struct GlycinNgLoader {
    inner: Option<Loader>,
}

/// Opaque [`Image`] handle.
#[repr(C)]
pub struct GlycinNgImage {
    inner: Image,
}

thread_local! {
    static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
}

fn set_error<E: std::fmt::Display>(e: E) {
    let msg = CString::new(e.to_string()).unwrap_or_else(|_| CString::new("error").unwrap());
    LAST_ERROR.with(|cell| *cell.borrow_mut() = Some(msg));
}

fn clear_error() {
    LAST_ERROR.with(|cell| *cell.borrow_mut() = None);
}

/// Return the last error message produced on this thread, or NULL
/// if none. The pointer is valid until the next call that produces
/// or clears an error on the same thread.
#[unsafe(no_mangle)]
pub extern "C" fn glycin_ng_last_error() -> *const c_char {
    LAST_ERROR.with(|cell| {
        cell.borrow()
            .as_ref()
            .map(|s| s.as_ptr())
            .unwrap_or(ptr::null())
    })
}

/// Clear the last-error slot for this thread.
#[unsafe(no_mangle)]
pub extern "C" fn glycin_ng_clear_last_error() {
    clear_error();
}

/// Free a loader handle. Safe to call on NULL.
///
/// # Safety
///
/// `loader` must have been returned by a `glycin_ng_loader_new_*`
/// function and must not have already been freed or consumed by
/// `glycin_ng_loader_load`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_loader_free(loader: *mut GlycinNgLoader) {
    if !loader.is_null() {
        drop(unsafe { Box::from_raw(loader) });
    }
}

/// Construct a loader from a filesystem path. Returns NULL on error.
///
/// # Safety
///
/// `path` must be a valid pointer to a NUL-terminated string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_loader_new_path(path: *const c_char) -> *mut GlycinNgLoader {
    clear_error();
    if path.is_null() {
        set_error("path is null");
        return ptr::null_mut();
    }
    let cstr = unsafe { CStr::from_ptr(path) };
    let pb = PathBuf::from(cstr.to_string_lossy().as_ref());
    let loader = Loader::new_path(pb);
    Box::into_raw(Box::new(GlycinNgLoader {
        inner: Some(loader),
    }))
}

/// Construct a loader from an in-memory byte buffer. Returns NULL on
/// error. The bytes are copied; the caller may free `data` after the
/// call returns.
///
/// # Safety
///
/// `data` must be a valid pointer to at least `len` bytes, or `len`
/// must be `0`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_loader_new_bytes(
    data: *const u8,
    len: usize,
) -> *mut GlycinNgLoader {
    clear_error();
    if data.is_null() && len != 0 {
        set_error("data is null but len is non-zero");
        return ptr::null_mut();
    }
    let bytes: Vec<u8> = if len == 0 {
        Vec::new()
    } else {
        unsafe { slice::from_raw_parts(data, len) }.to_vec()
    };
    let loader = Loader::new_bytes(bytes);
    Box::into_raw(Box::new(GlycinNgLoader {
        inner: Some(loader),
    }))
}

/// Toggle the sandbox layers on the loader.
///
/// # Safety
///
/// `loader` must be a valid pointer returned by
/// `glycin_ng_loader_new_*` and must not have been consumed or freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_loader_sandbox(
    loader: *mut GlycinNgLoader,
    landlock: c_int,
    seccomp: c_int,
    rlimit: c_int,
    strict: c_int,
) -> c_int {
    clear_error();
    let Some(handle) = (unsafe { loader.as_mut() }) else {
        set_error("loader is null");
        return -1;
    };
    let Some(inner) = handle.inner.take() else {
        set_error("loader has already been consumed");
        return -1;
    };
    let selector = SandboxSelector {
        landlock: landlock != 0,
        seccomp: seccomp != 0,
        rlimit: rlimit != 0,
        strict: strict != 0,
    };
    handle.inner = Some(inner.sandbox_selector(selector));
    0
}

/// Override the format-detection step with an explicit hint.
///
/// `format` must be one of the `GLYCIN_NG_FORMAT_*` constants.
///
/// # Safety
///
/// `loader` must be a valid pointer returned by
/// `glycin_ng_loader_new_*` and must not have been consumed or freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_loader_format_hint(
    loader: *mut GlycinNgLoader,
    format: c_uint,
) -> c_int {
    clear_error();
    let Some(handle) = (unsafe { loader.as_mut() }) else {
        set_error("loader is null");
        return -1;
    };
    let Some(inner) = handle.inner.take() else {
        set_error("loader has already been consumed");
        return -1;
    };
    let f = match c_uint_to_format(format) {
        Some(f) => f,
        None => {
            handle.inner = Some(inner);
            set_error("unknown format constant");
            return -1;
        }
    };
    handle.inner = Some(inner.format_hint(f));
    0
}

/// Consume the loader and decode the image.
///
/// On success returns a non-NULL [`GlycinNgImage`] handle and the
/// loader is freed. On failure returns NULL and the loader is also
/// freed. Either way the caller must not use `loader` after this
/// call.
///
/// # Safety
///
/// `loader` must be a valid pointer returned by
/// `glycin_ng_loader_new_*` and must not have been consumed or freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_loader_load(loader: *mut GlycinNgLoader) -> *mut GlycinNgImage {
    clear_error();
    if loader.is_null() {
        set_error("loader is null");
        return ptr::null_mut();
    }
    let mut handle = unsafe { Box::from_raw(loader) };
    let Some(inner) = handle.inner.take() else {
        set_error("loader has already been consumed");
        return ptr::null_mut();
    };
    match inner.load() {
        Ok(image) => Box::into_raw(Box::new(GlycinNgImage { inner: image })),
        Err(e) => {
            set_error(e);
            ptr::null_mut()
        }
    }
}

/// Free an image handle. Safe to call on NULL.
///
/// # Safety
///
/// `image` must have been returned by `glycin_ng_loader_load` and
/// must not have already been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_image_free(image: *mut GlycinNgImage) {
    if !image.is_null() {
        drop(unsafe { Box::from_raw(image) });
    }
}

fn image_ref<'a>(image: *const GlycinNgImage) -> Option<&'a Image> {
    unsafe { image.as_ref() }.map(|h| &h.inner)
}

/// Width of the image in pixels (0 if `image` is NULL).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_image_width(image: *const GlycinNgImage) -> u32 {
    image_ref(image).map(|i| i.width()).unwrap_or(0)
}

/// Height of the image in pixels (0 if `image` is NULL).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_image_height(image: *const GlycinNgImage) -> u32 {
    image_ref(image).map(|i| i.height()).unwrap_or(0)
}

/// Number of frames in the image (0 if `image` is NULL).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_image_frame_count(image: *const GlycinNgImage) -> usize {
    image_ref(image).map(|i| i.frames().len()).unwrap_or(0)
}

/// Short lowercase format name (e.g. "png"). Returns NULL if
/// `image` is NULL. The pointer is valid for the lifetime of the
/// image handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_image_format_name(image: *const GlycinNgImage) -> *const c_char {
    let Some(img) = image_ref(image) else {
        return ptr::null();
    };
    // The format-name strings are 'static and ASCII; we can return a
    // pointer into the byte buffer plus a trailing NUL via a small
    // lookup table.
    format_name_cstr(img.format_name())
}

fn format_name_cstr(name: &'static str) -> *const c_char {
    // The names are static ASCII, but Rust string slices are not
    // NUL-terminated. Lookup table of every value the decoders return.
    const NAMES: &[(&str, &CStr)] = &[
        ("png", c"png"),
        ("jpeg", c"jpeg"),
        ("gif", c"gif"),
        ("webp", c"webp"),
        ("tiff", c"tiff"),
        ("bmp", c"bmp"),
        ("ico", c"ico"),
        ("tga", c"tga"),
        ("qoi", c"qoi"),
        ("exr", c"exr"),
        ("pnm", c"pnm"),
        ("dds", c"dds"),
        ("jxl", c"jxl"),
    ];
    for (rust, cstr) in NAMES {
        if *rust == name {
            return cstr.as_ptr();
        }
    }
    ptr::null()
}

fn frame_ref<'a>(image: *const GlycinNgImage, index: usize) -> Option<&'a Frame> {
    let img = image_ref(image)?;
    img.frames().get(index)
}

/// Texture of the frame at `index` (NULL on out-of-bounds or NULL
/// image). The pointer remains valid for the lifetime of the image
/// handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_image_texture(
    image: *const GlycinNgImage,
    index: usize,
) -> *const Texture {
    match frame_ref(image, index) {
        Some(frame) => frame.texture() as *const Texture,
        None => ptr::null(),
    }
}

/// Frame delay for animation, in milliseconds (0 if the frame is
/// not animated or `image` is NULL).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_image_frame_delay_ms(
    image: *const GlycinNgImage,
    index: usize,
) -> u64 {
    frame_ref(image, index)
        .and_then(|f| f.delay())
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

/// Width of the texture in pixels.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_texture_width(texture: *const Texture) -> u32 {
    unsafe { texture.as_ref() }.map(|t| t.width()).unwrap_or(0)
}

/// Height of the texture in pixels.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_texture_height(texture: *const Texture) -> u32 {
    unsafe { texture.as_ref() }.map(|t| t.height()).unwrap_or(0)
}

/// Stride in bytes between successive rows.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_texture_stride(texture: *const Texture) -> u32 {
    unsafe { texture.as_ref() }.map(|t| t.stride()).unwrap_or(0)
}

/// Pixel memory format, encoded as one of the `GLYCIN_NG_FORMAT_*`
/// constants.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_texture_format(texture: *const Texture) -> c_uint {
    let Some(t) = (unsafe { texture.as_ref() }) else {
        return GLYCIN_NG_FORMAT_UNKNOWN;
    };
    memory_format_to_c_uint(t.format())
}

/// Raw pixel data pointer (length is
/// `glycin_ng_texture_data_len`). Returns NULL if `texture` is
/// NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_texture_data(texture: *const Texture) -> *const u8 {
    unsafe { texture.as_ref() }
        .map(|t| t.data().as_ptr())
        .unwrap_or(ptr::null())
}

/// Length in bytes of the texture's pixel data.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn glycin_ng_texture_data_len(texture: *const Texture) -> usize {
    unsafe { texture.as_ref() }
        .map(|t| t.data().len())
        .unwrap_or(0)
}

/// Texture format constant: unknown (returned only for NULL inputs).
pub const GLYCIN_NG_FORMAT_UNKNOWN: c_uint = 0;
/// 8 bit grayscale.
pub const GLYCIN_NG_FORMAT_G8: c_uint = 1;
/// 8 bit grayscale with straight alpha.
pub const GLYCIN_NG_FORMAT_G8A8: c_uint = 2;
/// 8 bit grayscale with premultiplied alpha.
pub const GLYCIN_NG_FORMAT_G8A8_PRE: c_uint = 3;
/// 16 bit grayscale.
pub const GLYCIN_NG_FORMAT_G16: c_uint = 4;
/// 16 bit grayscale with straight alpha.
pub const GLYCIN_NG_FORMAT_G16A16: c_uint = 5;
/// 16 bit grayscale with premultiplied alpha.
pub const GLYCIN_NG_FORMAT_G16A16_PRE: c_uint = 6;
/// 8 bit per channel RGB.
pub const GLYCIN_NG_FORMAT_R8G8B8: c_uint = 10;
/// 8 bit per channel RGBA with straight alpha.
pub const GLYCIN_NG_FORMAT_R8G8B8A8: c_uint = 11;
/// 8 bit per channel RGBA with premultiplied alpha.
pub const GLYCIN_NG_FORMAT_R8G8B8A8_PRE: c_uint = 12;
/// 8 bit per channel BGR.
pub const GLYCIN_NG_FORMAT_B8G8R8: c_uint = 13;
/// 8 bit per channel BGRA with straight alpha.
pub const GLYCIN_NG_FORMAT_B8G8R8A8: c_uint = 14;
/// 8 bit per channel BGRA with premultiplied alpha.
pub const GLYCIN_NG_FORMAT_B8G8R8A8_PRE: c_uint = 15;
/// 8 bit per channel ARGB with straight alpha.
pub const GLYCIN_NG_FORMAT_A8R8G8B8: c_uint = 16;
/// 8 bit per channel ARGB with premultiplied alpha.
pub const GLYCIN_NG_FORMAT_A8R8G8B8_PRE: c_uint = 17;
/// 8 bit per channel ABGR with straight alpha.
pub const GLYCIN_NG_FORMAT_A8B8G8R8: c_uint = 18;
/// 16 bit per channel RGB.
pub const GLYCIN_NG_FORMAT_R16G16B16: c_uint = 20;
/// 16 bit per channel RGBA with straight alpha.
pub const GLYCIN_NG_FORMAT_R16G16B16A16: c_uint = 21;
/// 16 bit per channel RGBA with premultiplied alpha.
pub const GLYCIN_NG_FORMAT_R16G16B16A16_PRE: c_uint = 22;
/// IEEE 754 binary16 per channel RGB.
pub const GLYCIN_NG_FORMAT_R16G16B16_F: c_uint = 23;
/// IEEE 754 binary16 per channel RGBA.
pub const GLYCIN_NG_FORMAT_R16G16B16A16_F: c_uint = 24;
/// IEEE 754 binary32 per channel RGB.
pub const GLYCIN_NG_FORMAT_R32G32B32_F: c_uint = 25;
/// IEEE 754 binary32 per channel RGBA with straight alpha.
pub const GLYCIN_NG_FORMAT_R32G32B32A32_F: c_uint = 26;
/// IEEE 754 binary32 per channel RGBA with premultiplied alpha.
pub const GLYCIN_NG_FORMAT_R32G32B32A32_F_PRE: c_uint = 27;

fn memory_format_to_c_uint(f: MemoryFormat) -> c_uint {
    match f {
        MemoryFormat::G8 => GLYCIN_NG_FORMAT_G8,
        MemoryFormat::G8a8 => GLYCIN_NG_FORMAT_G8A8,
        MemoryFormat::G8a8Premultiplied => GLYCIN_NG_FORMAT_G8A8_PRE,
        MemoryFormat::G16 => GLYCIN_NG_FORMAT_G16,
        MemoryFormat::G16a16 => GLYCIN_NG_FORMAT_G16A16,
        MemoryFormat::G16a16Premultiplied => GLYCIN_NG_FORMAT_G16A16_PRE,
        MemoryFormat::R8g8b8 => GLYCIN_NG_FORMAT_R8G8B8,
        MemoryFormat::R8g8b8a8 => GLYCIN_NG_FORMAT_R8G8B8A8,
        MemoryFormat::R8g8b8a8Premultiplied => GLYCIN_NG_FORMAT_R8G8B8A8_PRE,
        MemoryFormat::B8g8r8 => GLYCIN_NG_FORMAT_B8G8R8,
        MemoryFormat::B8g8r8a8 => GLYCIN_NG_FORMAT_B8G8R8A8,
        MemoryFormat::B8g8r8a8Premultiplied => GLYCIN_NG_FORMAT_B8G8R8A8_PRE,
        MemoryFormat::A8r8g8b8 => GLYCIN_NG_FORMAT_A8R8G8B8,
        MemoryFormat::A8r8g8b8Premultiplied => GLYCIN_NG_FORMAT_A8R8G8B8_PRE,
        MemoryFormat::A8b8g8r8 => GLYCIN_NG_FORMAT_A8B8G8R8,
        MemoryFormat::R16g16b16 => GLYCIN_NG_FORMAT_R16G16B16,
        MemoryFormat::R16g16b16a16 => GLYCIN_NG_FORMAT_R16G16B16A16,
        MemoryFormat::R16g16b16a16Premultiplied => GLYCIN_NG_FORMAT_R16G16B16A16_PRE,
        MemoryFormat::R16g16b16Float => GLYCIN_NG_FORMAT_R16G16B16_F,
        MemoryFormat::R16g16b16a16Float => GLYCIN_NG_FORMAT_R16G16B16A16_F,
        MemoryFormat::R32g32b32Float => GLYCIN_NG_FORMAT_R32G32B32_F,
        MemoryFormat::R32g32b32a32Float => GLYCIN_NG_FORMAT_R32G32B32A32_F,
        MemoryFormat::R32g32b32a32FloatPremultiplied => GLYCIN_NG_FORMAT_R32G32B32A32_F_PRE,
    }
}

/// Known-format constant: PNG / APNG.
pub const GLYCIN_NG_KFMT_PNG: c_uint = 1;
/// Known-format constant: JPEG.
pub const GLYCIN_NG_KFMT_JPEG: c_uint = 2;
/// Known-format constant: GIF.
pub const GLYCIN_NG_KFMT_GIF: c_uint = 3;
/// Known-format constant: WebP.
pub const GLYCIN_NG_KFMT_WEBP: c_uint = 4;
/// Known-format constant: TIFF.
pub const GLYCIN_NG_KFMT_TIFF: c_uint = 5;
/// Known-format constant: BMP.
pub const GLYCIN_NG_KFMT_BMP: c_uint = 6;
/// Known-format constant: ICO / CUR.
pub const GLYCIN_NG_KFMT_ICO: c_uint = 7;
/// Known-format constant: TGA.
pub const GLYCIN_NG_KFMT_TGA: c_uint = 8;
/// Known-format constant: QOI.
pub const GLYCIN_NG_KFMT_QOI: c_uint = 9;
/// Known-format constant: OpenEXR.
pub const GLYCIN_NG_KFMT_EXR: c_uint = 10;
/// Known-format constant: PNM family.
pub const GLYCIN_NG_KFMT_PNM: c_uint = 11;
/// Known-format constant: DDS.
pub const GLYCIN_NG_KFMT_DDS: c_uint = 12;
/// Known-format constant: JPEG XL.
pub const GLYCIN_NG_KFMT_JXL: c_uint = 13;

fn c_uint_to_format(value: c_uint) -> Option<KnownFormat> {
    Some(match value {
        GLYCIN_NG_KFMT_PNG => KnownFormat::Png,
        GLYCIN_NG_KFMT_JPEG => KnownFormat::Jpeg,
        GLYCIN_NG_KFMT_GIF => KnownFormat::Gif,
        GLYCIN_NG_KFMT_WEBP => KnownFormat::WebP,
        GLYCIN_NG_KFMT_TIFF => KnownFormat::Tiff,
        GLYCIN_NG_KFMT_BMP => KnownFormat::Bmp,
        GLYCIN_NG_KFMT_ICO => KnownFormat::Ico,
        GLYCIN_NG_KFMT_TGA => KnownFormat::Tga,
        GLYCIN_NG_KFMT_QOI => KnownFormat::Qoi,
        GLYCIN_NG_KFMT_EXR => KnownFormat::Exr,
        GLYCIN_NG_KFMT_PNM => KnownFormat::Pnm,
        GLYCIN_NG_KFMT_DDS => KnownFormat::Dds,
        GLYCIN_NG_KFMT_JXL => KnownFormat::Jxl,
        _ => return None,
    })
}

// Silence the unused-import warning when the Error variant is only
// used inside set_error().
#[allow(dead_code)]
fn _dummy(_: &Error) {}