Skip to main content

openjp2/
openjpeg.rs

1/*
2 * The copyright in this software is being made available under the 2-clauses
3 * BSD License, included below. This software may be subject to other third
4 * party and contributor rights, including patent rights, and no such rights
5 * are granted under this license.
6 *
7 * Copyright (c) 2005, Herve Drolon, FreeImage Team
8 * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR
9 * Copyright (c) 2012, CS Systemes d'Information, France
10 * All rights reserved.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
25 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 * POSSIBILITY OF SUCH DAMAGE.
32 */
33
34// This module is the C ABI shim; it moves wholesale to the `openjp2-capi` crate in phase 6.
35#![allow(unsafe_op_in_unsafe_fn)]
36
37use crate::image::*;
38use crate::params::opj_cparameters_t;
39use crate::cstr_info::{opj_codestream_index_t, opj_codestream_info_v2_t};
40use openjp2_ctypes::*;
41
42use crate::codec::Codec;
43use openjp2_core::Stream as opj_stream_private_t;
44
45#[cfg(feature = "file-io")]
46use ::libc::FILE;
47
48/* ---------------------------------------------------------------------- */
49/* Functions to set the message handlers */
50
51/// The C `opj_msg_callback` type from openjpeg.h, declared here on the ABI side: the core only
52/// sees the Rust closures these functions wrap around it.
53pub type opj_msg_callback_fn =
54  unsafe extern "C" fn(_: *const core::ffi::c_char, _: *mut core::ffi::c_void) -> ();
55pub type opj_msg_callback = Option<opj_msg_callback_fn>;
56
57/// A `Send` carrier for the C callback's user-data pointer: moving the address
58/// across threads is fine; using it is the C caller's responsibility.
59struct SendPtr(*mut core::ffi::c_void);
60// SAFETY: the pointer is only passed through to the C callback; the core's event
61// manager never dereferences it.
62unsafe impl Send for SendPtr {}
63
64/// Wrap a C callback + user data in the core's `FnMut(&str)` sink.
65fn wrap_callback(
66  callback: opj_msg_callback,
67  user_data: *mut core::ffi::c_void,
68) -> impl FnMut(&str) + Send {
69  let user_data = SendPtr(user_data);
70  move |msg: &str| {
71    let Some(callback) = callback else {
72      return;
73    };
74    if let Ok(c_msg) = std::ffi::CString::new(msg) {
75      // SAFETY: the callback is the one the caller installed, invoked with the caller's data.
76      unsafe { callback(c_msg.as_ptr(), user_data.0) };
77    }
78  }
79}
80
81/// Runs `f`, converting any panic into the C-style failure value.
82///
83/// A panic must NEVER unwind across the C ABI: that is undefined behaviour
84/// in C callers.  The failure default (OPJ_FALSE / NULL / 0) signals the
85/// error the same way the core's error events do.
86fn ffi_guard<T: Default>(f: impl FnOnce() -> T) -> T {
87  match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
88    Ok(v) => v,
89    Err(payload) => {
90      let detail = payload
91        .downcast_ref::<&str>()
92        .map(|s| s.to_string())
93        .or_else(|| payload.downcast_ref::<String>().cloned())
94        .unwrap_or_else(|| "unknown panic".to_string());
95      eprintln!("openjp2: internal panic caught at the C ABI boundary: {detail}");
96      T::default()
97    }
98  }
99}
100
101#[no_mangle]
102pub unsafe fn opj_set_info_handler(
103  p_codec: *mut opj_codec_t,
104  p_callback: opj_msg_callback,
105  p_user_data: *mut core::ffi::c_void,
106) -> OPJ_BOOL {ffi_guard(|| {
107  if p_codec.is_null() {
108    return 0i32;
109  }
110  let l_codec = &mut *(p_codec as *mut Codec);
111  l_codec.set_info_handler(wrap_callback(p_callback, p_user_data))
112})}
113
114#[no_mangle]
115pub unsafe fn opj_set_warning_handler(
116  p_codec: *mut opj_codec_t,
117  p_callback: opj_msg_callback,
118  p_user_data: *mut core::ffi::c_void,
119) -> OPJ_BOOL {ffi_guard(|| {
120  if p_codec.is_null() {
121    return 0i32;
122  }
123  let l_codec = &mut *(p_codec as *mut Codec);
124  l_codec.set_warning_handler(wrap_callback(p_callback, p_user_data))
125})}
126
127#[no_mangle]
128pub unsafe fn opj_set_error_handler(
129  p_codec: *mut opj_codec_t,
130  p_callback: opj_msg_callback,
131  p_user_data: *mut core::ffi::c_void,
132) -> OPJ_BOOL {ffi_guard(|| {
133  if p_codec.is_null() {
134    return 0i32;
135  }
136  let l_codec = &mut *(p_codec as *mut Codec);
137  l_codec.set_error_handler(wrap_callback(p_callback, p_user_data))
138})}
139
140/* ---------------------------------------------------------------------- */
141pub const OPJ_VERSION: &str = "2.5.4";
142pub const OPJ_VERSION_C: *const u8 = b"2.5.4\x00" as *const u8;
143
144#[no_mangle]
145pub fn opj_version() -> *const core::ffi::c_char {ffi_guard(|| {
146  OPJ_VERSION_C as *const core::ffi::c_char
147})}
148
149/* ---------------------------------------------------------------------- */
150/* DECOMPRESSION FUNCTIONS*/
151#[no_mangle]
152pub fn opj_create_decompress(p_format: OPJ_CODEC_FORMAT) -> *mut opj_codec_t {ffi_guard(|| {
153  if let Some(codec) = Codec::new_decoder(p_format) {
154    let l_codec = Box::new(codec);
155    Box::into_raw(l_codec) as *mut opj_codec_t
156  } else {
157    core::ptr::null_mut()
158  }
159})}
160
161#[no_mangle]
162pub unsafe fn opj_set_default_decoder_parameters(parameters: *mut opj_dparameters_t) {ffi_guard(|| {
163  if parameters.is_null() {
164    return;
165  }
166  let parameters = &mut *parameters;
167  parameters.set_defaults();
168})}
169
170#[no_mangle]
171pub unsafe fn opj_codec_set_threads(
172  p_codec: *mut opj_codec_t,
173  num_threads: core::ffi::c_int,
174) -> OPJ_BOOL {ffi_guard(|| {
175  if p_codec.is_null() {
176    return 0i32;
177  }
178  let l_codec = &mut *(p_codec as *mut Codec);
179  l_codec.set_threads(num_threads)
180})}
181
182#[no_mangle]
183pub unsafe fn opj_setup_decoder(
184  p_codec: *mut opj_codec_t,
185  parameters: *mut opj_dparameters_t,
186) -> OPJ_BOOL {ffi_guard(|| {
187  if p_codec.is_null() || parameters.is_null() {
188    return 0i32;
189  }
190  let l_codec = &mut *(p_codec as *mut Codec);
191  let parameters = &mut *parameters;
192  l_codec.setup_decoder(parameters)
193})}
194
195#[no_mangle]
196pub unsafe fn opj_decoder_set_strict_mode(
197  p_codec: *mut opj_codec_t,
198  strict: OPJ_BOOL,
199) -> OPJ_BOOL {ffi_guard(|| {
200  if p_codec.is_null() {
201    return 0i32;
202  }
203  let l_codec = &mut *(p_codec as *mut Codec);
204  l_codec.decoder_set_strict_mode(strict)
205})}
206
207#[no_mangle]
208pub unsafe fn opj_read_header(
209  p_stream: *mut opj_stream_t,
210  p_codec: *mut opj_codec_t,
211  p_image: *mut *mut opj_image_t,
212) -> OPJ_BOOL {ffi_guard(|| {
213  if p_codec.is_null() | p_stream.is_null() | p_image.is_null() {
214    return 0i32;
215  }
216  let p_stream = unsafe { &mut *(p_stream as *mut opj_stream_private_t) };
217  let l_codec = &mut *(p_codec as *mut Codec);
218  match l_codec.read_header(p_stream) {
219    Some(image) => {
220      *p_image = Box::into_raw(core_into_opj(image));
221      1
222    }
223    None => 0,
224  }
225})}
226
227#[no_mangle]
228pub unsafe fn opj_set_decoded_components(
229  p_codec: *mut opj_codec_t,
230  numcomps: OPJ_UINT32,
231  comps_indices: *const OPJ_UINT32,
232  apply_color_transforms: OPJ_BOOL,
233) -> OPJ_BOOL {ffi_guard(|| {
234  if p_codec.is_null() {
235    return 0i32;
236  }
237  let l_codec = &mut *(p_codec as *mut Codec);
238  let components = unsafe { core::slice::from_raw_parts(comps_indices, numcomps as usize) };
239  l_codec.set_decoded_components(components, apply_color_transforms)
240})}
241
242#[no_mangle]
243pub unsafe fn opj_decode(
244  p_codec: *mut opj_codec_t,
245  p_stream: *mut opj_stream_t,
246  p_image: *mut opj_image_t,
247) -> OPJ_BOOL {ffi_guard(|| {
248  if p_codec.is_null() | p_stream.is_null() | p_image.is_null() {
249    return 0i32;
250  }
251  let p_image = unsafe { &mut *p_image };
252  let p_stream = unsafe { &mut *(p_stream as *mut opj_stream_private_t) };
253  let l_codec = &mut *(p_codec as *mut Codec);
254  match l_codec.decode(p_stream) {
255    Some(core) => {
256      let fresh = core_into_opj(core);
257      p_image.clear_comps();
258      p_image.clear_icc_profile();
259      *p_image = *fresh;
260      1
261    }
262    None => 0,
263  }
264})}
265
266#[no_mangle]
267pub unsafe fn opj_set_decode_area(
268  p_codec: *mut opj_codec_t,
269  p_image: *mut opj_image_t,
270  p_start_x: OPJ_INT32,
271  p_start_y: OPJ_INT32,
272  p_end_x: OPJ_INT32,
273  p_end_y: OPJ_INT32,
274) -> OPJ_BOOL {ffi_guard(|| {
275  if p_codec.is_null() | p_image.is_null() {
276    return 0i32;
277  }
278  let p_image = unsafe { &mut *p_image };
279  let l_codec = &mut *(p_codec as *mut Codec);
280  let mut core = core_from_opj(p_image);
281  // set_decode_area only adjusts the component geometry; the caller's data
282  // buffers are stale at this point (C leaves them alone and opj_decode
283  // replaces them), so do not carry them through the round-trip.
284  for comp in &mut core.comps {
285    comp.data.clear();
286  }
287  let ret = l_codec.set_decode_area(&mut core, p_start_x, p_start_y, p_end_x, p_end_y);
288  let fresh = core_into_opj(core);
289  p_image.clear_comps();
290  p_image.clear_icc_profile();
291  *p_image = *fresh;
292  ret
293})}
294
295#[no_mangle]
296pub unsafe fn opj_read_tile_header(
297  p_codec: *mut opj_codec_t,
298  p_stream: *mut opj_stream_t,
299  p_tile_index: *mut OPJ_UINT32,
300  p_data_size: *mut OPJ_UINT32,
301  p_tile_x0: *mut OPJ_INT32,
302  p_tile_y0: *mut OPJ_INT32,
303  p_tile_x1: *mut OPJ_INT32,
304  p_tile_y1: *mut OPJ_INT32,
305  p_nb_comps: *mut OPJ_UINT32,
306  p_should_go_on: *mut OPJ_BOOL,
307) -> OPJ_BOOL {ffi_guard(|| {
308  if p_codec.is_null() | p_stream.is_null() {
309    return 0i32;
310  }
311  let p_stream = unsafe { &mut *(p_stream as *mut opj_stream_private_t) };
312  let l_codec = &mut *(p_codec as *mut Codec);
313  match l_codec.read_tile_header(p_stream) {
314    Some(tile_info) => {
315      unsafe {
316        if !p_tile_index.is_null() {
317          *p_tile_index = tile_info.index;
318        }
319        if !p_data_size.is_null() {
320          *p_data_size = tile_info.data_size.unwrap_or_default();
321        }
322        if !p_tile_x0.is_null() {
323          *p_tile_x0 = tile_info.x0;
324        }
325        if !p_tile_y0.is_null() {
326          *p_tile_y0 = tile_info.y0;
327        }
328        if !p_tile_x1.is_null() {
329          *p_tile_x1 = tile_info.x1;
330        }
331        if !p_tile_y1.is_null() {
332          *p_tile_y1 = tile_info.y1;
333        }
334        if !p_nb_comps.is_null() {
335          *p_nb_comps = tile_info.nb_comps;
336        }
337        if !p_should_go_on.is_null() {
338          *p_should_go_on = tile_info.go_on as _;
339        }
340      }
341      1
342    }
343    None => 0,
344  }
345})}
346
347#[no_mangle]
348pub unsafe fn opj_decode_tile_data(
349  p_codec: *mut opj_codec_t,
350  p_tile_index: OPJ_UINT32,
351  p_data: *mut OPJ_BYTE,
352  p_data_size: OPJ_UINT32,
353  p_stream: *mut opj_stream_t,
354) -> OPJ_BOOL {ffi_guard(|| {
355  if p_codec.is_null() | p_stream.is_null() {
356    return 0i32;
357  }
358  let p_stream = unsafe { &mut *(p_stream as *mut opj_stream_private_t) };
359  let l_codec = &mut *(p_codec as *mut Codec);
360  let p_data = if p_data.is_null() {
361    None
362  } else {
363    Some(unsafe { core::slice::from_raw_parts_mut(p_data, p_data_size as usize) })
364  };
365  l_codec.decode_tile_data(p_stream, p_tile_index, p_data)
366})}
367
368#[no_mangle]
369pub unsafe fn opj_get_decoded_tile(
370  p_codec: *mut opj_codec_t,
371  p_stream: *mut opj_stream_t,
372  p_image: *mut opj_image_t,
373  tile_index: OPJ_UINT32,
374) -> OPJ_BOOL {ffi_guard(|| {
375  if p_codec.is_null() | p_stream.is_null() | p_image.is_null() {
376    return 0i32;
377  }
378  let p_image = unsafe { &mut *p_image };
379  let p_stream = unsafe { &mut *(p_stream as *mut opj_stream_private_t) };
380  let l_codec = &mut *(p_codec as *mut Codec);
381  match l_codec.get_decoded_tile(p_stream, tile_index) {
382    Some(core) => {
383      let fresh = core_into_opj(core);
384      p_image.clear_comps();
385      p_image.clear_icc_profile();
386      *p_image = *fresh;
387      1
388    }
389    None => 0,
390  }
391})}
392
393#[no_mangle]
394pub unsafe fn opj_set_decoded_resolution_factor(
395  p_codec: *mut opj_codec_t,
396  res_factor: OPJ_UINT32,
397) -> OPJ_BOOL {ffi_guard(|| {
398  if p_codec.is_null() {
399    return 0i32;
400  }
401  let l_codec = &mut *(p_codec as *mut Codec);
402  l_codec.set_decoded_resolution_factor(res_factor)
403})}
404
405/* default decoding parameters */
406/* ---------------------------------------------------------------------- */
407/* COMPRESSION FUNCTIONS*/
408#[no_mangle]
409pub unsafe fn opj_create_compress(p_format: OPJ_CODEC_FORMAT) -> *mut opj_codec_t {ffi_guard(|| {
410  if let Some(codec) = Codec::new_encoder(p_format) {
411    let l_codec = Box::new(codec);
412    Box::into_raw(l_codec) as *mut opj_codec_t
413  } else {
414    core::ptr::null_mut()
415  }
416})}
417
418/* default coding parameters */
419#[no_mangle]
420pub unsafe fn opj_set_default_encoder_parameters(parameters: *mut opj_cparameters_t) {ffi_guard(|| {
421  if parameters.is_null() {
422    return;
423  }
424  unsafe {
425    parameters.write_bytes(0, 1);
426  }
427  let parameters = &mut *parameters;
428  parameters.set_defaults();
429})}
430
431#[no_mangle]
432pub unsafe fn opj_setup_encoder(
433  p_codec: *mut opj_codec_t,
434  parameters: *mut opj_cparameters_t,
435  p_image: *mut opj_image_t,
436) -> OPJ_BOOL {ffi_guard(|| {
437  if p_codec.is_null() | parameters.is_null() | p_image.is_null() {
438    return 0i32;
439  }
440  let p_image = unsafe { &mut *p_image };
441  let l_codec = &mut *(p_codec as *mut Codec);
442  let parameters = &mut *parameters;
443  /* The C's setup_encoder validates the progression order (0..=4); the
444  core's native enum cannot hold invalid values, so validate here and
445  fail the encode like the C does. */
446  if !(0..=4).contains(&parameters.prog_order) {
447    match l_codec {
448      Codec::Dec(dec) => dec.emit_error_event("Invalid progression order\n"),
449      Codec::Enc(enc) => enc.emit_error_event("Invalid progression order\n"),
450    }
451    return 0i32;
452  }
453  let mut core = core_from_opj(p_image);
454  let mut safe = encoder_params_from_c(parameters, core.numcomps);
455  let ret = l_codec.setup_encoder(&mut safe, &mut core);
456  // The codec used to free the caller's MCT buffer here; the C caller hands
457  // ownership of it to opj_setup_encoder.
458  if !parameters.mct_data.is_null() {
459    // SAFETY: allocated with opj_malloc in opj_set_MCT.
460    crate::params::c_free(parameters.mct_data);
461    parameters.mct_data = core::ptr::null_mut();
462  }
463  let fresh = core_into_opj(core);
464  p_image.clear_comps();
465  p_image.clear_icc_profile();
466  *p_image = *fresh;
467  ret
468})}
469
470/// Converts the C-ABI encoder parameters into the core's safe owned struct.
471fn encoder_params_from_c(
472  parameters: &opj_cparameters_t,
473  numcomps: u32,
474) -> openjp2_core::EncoderParameters {
475  let mut safe = openjp2_core::EncoderParameters {
476    tile_size_on: parameters.tile_size_on != 0,
477    cp_tx0: parameters.cp_tx0,
478    cp_ty0: parameters.cp_ty0,
479    cp_tdx: parameters.cp_tdx,
480    cp_tdy: parameters.cp_tdy,
481    cp_disto_alloc: parameters.cp_disto_alloc,
482    cp_fixed_alloc: parameters.cp_fixed_alloc,
483    cp_fixed_quality: parameters.cp_fixed_quality,
484    csty: parameters.csty,
485    prog_order: openjp2_core::ProgressionOrder::from(parameters.prog_order),
486    pocs: parameters.POC.map(|p| openjp2_core::Poc {
487      resno0: p.resno0,
488      compno0: p.compno0,
489      layno1: p.layno1,
490      resno1: p.resno1,
491      compno1: p.compno1,
492      layno0: p.layno0,
493      precno0: p.precno0,
494      precno1: p.precno1,
495      prg1: openjp2_core::ProgressionOrder::from(p.prg1),
496      prg: openjp2_core::ProgressionOrder::from(p.prg),
497      tile: p.tile,
498      tx0: p.tx0,
499      tx1: p.tx1,
500      ty0: p.ty0,
501      ty1: p.ty1,
502      lay_s: p.layS,
503      res_s: p.resS,
504      comp_s: p.compS,
505      prc_s: p.prcS,
506      lay_e: p.layE,
507      res_e: p.resE,
508      comp_e: p.compE,
509      prc_e: p.prcE,
510      tx_s: p.txS,
511      tx_e: p.txE,
512      ty_s: p.tyS,
513      ty_e: p.tyE,
514      dx: p.dx,
515      dy: p.dy,
516      lay_t: p.lay_t,
517      res_t: p.res_t,
518      comp_t: p.comp_t,
519      prc_t: p.prc_t,
520      tx0_t: p.tx0_t,
521      ty0_t: p.ty0_t,
522    }),
523    numpocs: parameters.numpocs,
524    tcp_numlayers: parameters.tcp_numlayers,
525    tcp_rates: parameters.tcp_rates,
526    tcp_distoratio: parameters.tcp_distoratio,
527    numresolution: parameters.numresolution,
528    cblockw_init: parameters.cblockw_init,
529    cblockh_init: parameters.cblockh_init,
530    mode: parameters.mode,
531    irreversible: parameters.irreversible,
532    roi_compno: parameters.roi_compno,
533    roi_shift: parameters.roi_shift,
534    res_spec: parameters.res_spec,
535    prcw_init: parameters.prcw_init,
536    prch_init: parameters.prch_init,
537    index_on: parameters.index_on,
538    image_offset_x0: parameters.image_offset_x0,
539    image_offset_y0: parameters.image_offset_y0,
540    subsampling_dx: parameters.subsampling_dx,
541    subsampling_dy: parameters.subsampling_dy,
542    decod_format: parameters.decod_format,
543    cod_format: parameters.cod_format,
544    cp_cinema: parameters.cp_cinema,
545    max_comp_size: parameters.max_comp_size,
546    cp_rsiz: parameters.cp_rsiz as u16,
547    tp_on: parameters.tp_on,
548    tp_flag: parameters.tp_flag,
549    tcp_mct: parameters.tcp_mct,
550    jpip_on: parameters.jpip_on,
551    max_cs_size: parameters.max_cs_size,
552    rsiz: parameters.rsiz,
553    ..Default::default()
554  };
555  safe.cp_matrice = if parameters.cp_matrice.is_null() {
556    None
557  } else {
558    let array_len = (parameters.tcp_numlayers as usize)
559      .wrapping_mul(parameters.numresolution as usize)
560      .wrapping_mul(3);
561    // SAFETY: cp_matrice is the caller's matrix of `array_len` ints.
562    Some(unsafe { core::slice::from_raw_parts(parameters.cp_matrice, array_len) }.to_vec())
563  };
564  safe.cp_comment = if parameters.cp_comment.is_null() {
565    None
566  } else {
567    // SAFETY: cp_comment is a caller-provided NUL-terminated string.
568    Some(unsafe { core::ffi::CStr::from_ptr(parameters.cp_comment) }.to_bytes().to_vec())
569  };
570  safe.mct_data = if parameters.mct_data.is_null() {
571    None
572  } else {
573    let l_mct_len = (numcomps * numcomps) as usize;
574    // SAFETY: mct_data holds l_mct_len floats followed by numcomps ints.
575    unsafe {
576      let matrix: Vec<f32> =
577        core::slice::from_raw_parts(parameters.mct_data as *const f32, l_mct_len).to_vec();
578      let dc_shift: Vec<i32> = core::slice::from_raw_parts(
579        (parameters.mct_data as *mut u8).add(l_mct_len * core::mem::size_of::<f32>()) as *const i32,
580        numcomps as usize,
581      )
582      .to_vec();
583      Some((matrix, dc_shift))
584    }
585  };
586  safe
587}
588
589/* ----------------------------------------------------------------------- */
590#[no_mangle]
591pub unsafe fn opj_encoder_set_extra_options(
592  p_codec: *mut opj_codec_t,
593  options: *const *const core::ffi::c_char,
594) -> OPJ_BOOL {ffi_guard(|| {
595  if options.is_null() {
596    return 1;
597  }
598  if p_codec.is_null() {
599    return 0;
600  }
601  let l_codec = &mut *(p_codec as *mut Codec);
602  let mut p_option_iter = options;
603  let mut options = Vec::new();
604  while !(*p_option_iter).is_null() {
605    match core::ffi::CStr::from_ptr(*p_option_iter).to_str() {
606      Ok(option) => {
607        options.push(option);
608      }
609      Err(err) => {
610        log::error!("Failed to convert C string to Rust string: {err}");
611        return 0;
612      }
613    }
614    p_option_iter = p_option_iter.offset(1);
615  }
616  l_codec.encoder_set_extra_options(options.as_slice()) as _
617})}
618
619/* ----------------------------------------------------------------------- */
620#[no_mangle]
621pub unsafe fn opj_start_compress(
622  p_codec: *mut opj_codec_t,
623  p_image: *mut opj_image_t,
624  p_stream: *mut opj_stream_t,
625) -> OPJ_BOOL {ffi_guard(|| {
626  if p_codec.is_null() | p_stream.is_null() | p_image.is_null() {
627    return 0i32;
628  }
629  let p_image = unsafe { &mut *p_image };
630  let p_stream = unsafe { &mut *(p_stream as *mut opj_stream_private_t) };
631  let l_codec = &mut *(p_codec as *mut Codec);
632  let mut core = core_from_opj(p_image);
633  let ret = l_codec.start_compress(&mut core, p_stream);
634  let fresh = core_into_opj(core);
635  p_image.clear_comps();
636  p_image.clear_icc_profile();
637  *p_image = *fresh;
638  ret
639})}
640
641#[no_mangle]
642pub unsafe fn opj_encode(
643  p_codec: *mut opj_codec_t,
644  p_stream: *mut opj_stream_t,
645) -> OPJ_BOOL {ffi_guard(|| {
646  if p_codec.is_null() | p_stream.is_null() {
647    return 0i32;
648  }
649  let p_stream = unsafe { &mut *(p_stream as *mut opj_stream_private_t) };
650  let l_codec = &mut *(p_codec as *mut Codec);
651  l_codec.encode(p_stream)
652})}
653
654#[no_mangle]
655pub unsafe fn opj_end_compress(
656  p_codec: *mut opj_codec_t,
657  p_stream: *mut opj_stream_t,
658) -> OPJ_BOOL {ffi_guard(|| {
659  if p_codec.is_null() | p_stream.is_null() {
660    return 0i32;
661  }
662  let p_stream = unsafe { &mut *(p_stream as *mut opj_stream_private_t) };
663  let l_codec = &mut *(p_codec as *mut Codec);
664  l_codec.end_compress(p_stream)
665})}
666
667#[no_mangle]
668pub unsafe fn opj_end_decompress(
669  p_codec: *mut opj_codec_t,
670  p_stream: *mut opj_stream_t,
671) -> OPJ_BOOL {ffi_guard(|| {
672  if p_codec.is_null() | p_stream.is_null() {
673    return 0i32;
674  }
675  let p_stream = unsafe { &mut *(p_stream as *mut opj_stream_private_t) };
676  let l_codec = &mut *(p_codec as *mut Codec);
677  l_codec.end_decompress(p_stream)
678})}
679
680#[no_mangle]
681pub unsafe fn opj_set_MCT(
682  parameters: *mut opj_cparameters_t,
683  pEncodingMatrix: *mut OPJ_FLOAT32,
684  p_dc_shift: *mut OPJ_INT32,
685  nb_comps: OPJ_UINT32,
686) -> OPJ_BOOL {ffi_guard(|| {
687  let l_matrix_size = nb_comps * nb_comps;
688  let l_dc_shift_size = nb_comps;
689  let encoding_matrix =
690    unsafe { core::slice::from_raw_parts(pEncodingMatrix, l_matrix_size as usize) };
691  let dc_shift = unsafe { core::slice::from_raw_parts(p_dc_shift, l_dc_shift_size as usize) };
692  let parameters = &mut *parameters;
693  parameters.set_MCT(encoding_matrix, dc_shift, nb_comps) as _
694})}
695
696#[no_mangle]
697pub unsafe fn opj_write_tile(
698  p_codec: *mut opj_codec_t,
699  p_tile_index: OPJ_UINT32,
700  p_data: *mut OPJ_BYTE,
701  p_data_size: OPJ_UINT32,
702  p_stream: *mut opj_stream_t,
703) -> OPJ_BOOL {ffi_guard(|| {
704  if p_codec.is_null() | p_stream.is_null() | p_data.is_null() {
705    return 0i32;
706  }
707  let p_stream = unsafe { &mut *(p_stream as *mut opj_stream_private_t) };
708  let l_codec = &mut *(p_codec as *mut Codec);
709  let p_data = unsafe { core::slice::from_raw_parts(p_data as *const u8, p_data_size as usize) };
710  l_codec.write_tile(p_tile_index, p_data, p_stream)
711})}
712
713/* ---------------------------------------------------------------------- */
714#[no_mangle]
715pub unsafe fn opj_destroy_codec(p_codec: *mut opj_codec_t) {ffi_guard(|| {
716  if p_codec.is_null() {
717    return;
718  }
719  let _ = Box::from_raw(p_codec as *mut Codec);
720})}
721
722/* ---------------------------------------------------------------------- */
723#[cfg(feature = "file-io")]
724#[no_mangle]
725pub unsafe fn opj_dump_codec(
726  p_codec: *mut opj_codec_t,
727  info_flag: OPJ_INT32,
728  output_stream: *mut FILE,
729) {ffi_guard(|| {
730  if p_codec.is_null() {
731    return;
732  }
733  let l_codec = &mut *(p_codec as *mut Codec);
734  if output_stream.is_null() {
735    return;
736  }
737  let mut writer = CFile(output_stream);
738  l_codec.dump_codec(info_flag, &mut writer)
739})}
740
741/// A `Write` adapter over the caller's `FILE*` for opj_dump_codec.
742#[cfg(feature = "file-io")]
743struct CFile(*mut FILE);
744
745#[cfg(feature = "file-io")]
746impl std::io::Write for CFile {
747  fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
748    // SAFETY: the FILE* is the caller's open output stream.
749    let n = unsafe { libc::fwrite(buf.as_ptr() as *const libc::c_void, 1, buf.len(), self.0) };
750    if n == libc::size_t::MAX {
751      Ok(0)
752    } else {
753      Ok(n)
754    }
755  }
756
757  fn flush(&mut self) -> std::io::Result<()> {
758    Ok(())
759  }
760}
761
762#[cfg(feature = "file-io")]
763impl openjp2_core::StringWriter for CFile {
764  fn write_string(&mut self, s: &str) -> usize {
765    use std::io::Write;
766    self.write(s.as_bytes()).unwrap_or(0)
767  }
768}
769
770#[no_mangle]
771pub unsafe fn opj_get_cstr_info(p_codec: *mut opj_codec_t) -> *mut opj_codestream_info_v2_t {ffi_guard(|| {
772  if p_codec.is_null() {
773    return core::ptr::null_mut::<opj_codestream_info_v2_t>();
774  }
775  let l_codec = &*(p_codec as *mut Codec);
776  match l_codec.get_cstr_info_v2() {
777    Some(info) => crate::cstr_info::build_cstr_info_v2(&info),
778    None => core::ptr::null_mut::<opj_codestream_info_v2_t>(),
779  }
780})}
781
782#[no_mangle]
783pub unsafe fn opj_destroy_cstr_info(cstr_info: *mut *mut opj_codestream_info_v2_t) {ffi_guard(|| {
784  crate::cstr_info::destroy_cstr_info_v2(cstr_info);
785})}
786
787#[no_mangle]
788pub unsafe fn opj_get_cstr_index(p_codec: *mut opj_codec_t) -> *mut opj_codestream_index_t {ffi_guard(|| {
789  if p_codec.is_null() {
790    return core::ptr::null_mut::<opj_codestream_index_t>();
791  }
792  let l_codec = &*(p_codec as *mut Codec);
793  match l_codec.get_cstr_index_owned() {
794    Some(index) => crate::cstr_info::build_cstr_index(&index),
795    None => core::ptr::null_mut::<opj_codestream_index_t>(),
796  }
797})}
798
799#[no_mangle]
800pub unsafe fn opj_destroy_cstr_index(p_cstr_index: *mut *mut opj_codestream_index_t) {ffi_guard(|| {
801  if p_cstr_index.is_null() {
802    return;
803  }
804  crate::cstr_info::destroy_cstr_index(*p_cstr_index);
805  *p_cstr_index = core::ptr::null_mut::<opj_codestream_index_t>();
806})}
807
808/* ----------------------------------------------------------------------- */
809/* C stream objects (Phase 5.e: the C-callback adapter lives here; the    */
810/* core Stream only knows about Read/Write/Seek sources).                 */
811
812use std::cell::RefCell;
813use std::io::{self as io, Error as IoError, Read, Seek, Write};
814use std::rc::Rc;
815
816/// Shared, mutable C callback set for a C-created stream.
817#[derive(Default)]
818pub struct CustomCallbacks {
819  pub m_user_data: *mut core::ffi::c_void,
820  pub m_free_user_data_fn: opj_stream_free_user_data_fn,
821  pub m_read_fn: opj_stream_read_fn,
822  pub m_write_fn: opj_stream_write_fn,
823  pub m_skip_fn: opj_stream_skip_fn,
824  pub m_seek_fn: opj_stream_seek_fn,
825}
826
827/// Forwards core Stream I/O to the C callbacks held in a shared handle, so
828/// the opj_stream_set_* functions can mutate them after creation.
829pub struct CustomStream {
830  callbacks: Rc<RefCell<CustomCallbacks>>,
831  m_byte_offset: OPJ_OFF_T,
832}
833
834impl CustomStream {
835  pub fn has_seek(&self) -> bool {
836    self.callbacks.borrow().m_seek_fn.is_some()
837  }
838}
839
840impl Read for CustomStream {
841  fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
842    let callbacks = self.callbacks.borrow();
843    let res = if let Some(read) = callbacks.m_read_fn {
844      unsafe {
845        read(
846          buf.as_mut_ptr() as *mut core::ffi::c_void,
847          buf.len(),
848          callbacks.m_user_data,
849        ) as isize
850      }
851    } else {
852      return Err(IoError::other("Custom stream doesn't have a read function"));
853    };
854    drop(callbacks);
855    if res >= 0 {
856      self.m_byte_offset += res as i64;
857      Ok(res as usize)
858    } else {
859      Err(IoError::other("read failed"))
860    }
861  }
862}
863
864impl Write for CustomStream {
865  fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
866    let callbacks = self.callbacks.borrow();
867    let res = if let Some(write) = callbacks.m_write_fn {
868      unsafe {
869        write(
870          buf.as_ptr() as *mut core::ffi::c_void,
871          buf.len(),
872          callbacks.m_user_data,
873        ) as isize
874      }
875    } else {
876      return Err(IoError::other(
877        "Custom stream doesn't have a write function",
878      ));
879    };
880    drop(callbacks);
881    if res >= 0 {
882      self.m_byte_offset += res as i64;
883      Ok(res as usize)
884    } else {
885      Err(IoError::other("write failed"))
886    }
887  }
888
889  fn flush(&mut self) -> io::Result<()> {
890    Ok(())
891  }
892}
893
894impl Seek for CustomStream {
895  fn seek(&mut self, pos: std::io::SeekFrom) -> io::Result<u64> {
896    log::trace!("-- CustomStream.seek({pos:?})");
897    match pos {
898      std::io::SeekFrom::Start(offset) => {
899        let callbacks = self.callbacks.borrow();
900        let res = if let Some(seek) = callbacks.m_seek_fn {
901          unsafe { seek(offset as i64, callbacks.m_user_data) }
902        } else {
903          return Err(IoError::other(
904            "Custom stream doesn't have a seek function",
905          ));
906        };
907        drop(callbacks);
908        if res != 0 {
909          self.m_byte_offset = offset as i64;
910          Ok(offset)
911        } else {
912          Err(IoError::other("seek failed"))
913        }
914      }
915      std::io::SeekFrom::Current(offset) => {
916        let callbacks = self.callbacks.borrow();
917        let res = if let Some(skip) = callbacks.m_skip_fn {
918          unsafe { skip(offset, callbacks.m_user_data) }
919        } else {
920          return Err(IoError::other(
921            "Custom stream doesn't have a skip function",
922          ));
923        };
924        drop(callbacks);
925        if res != -1 {
926          self.m_byte_offset += offset;
927          Ok(self.m_byte_offset as u64)
928        } else {
929          Err(IoError::other("skip failed"))
930        }
931      }
932      std::io::SeekFrom::End(_offset) => Err(IoError::other("Unsupported seek from end")),
933    }
934  }
935}
936
937/// A C-visible stream: the core `Stream` plus (for C-callback streams) the
938/// shared callback handle the opj_stream_set_* functions mutate.
939pub struct OpjStream {
940  stream: openjp2_core::Stream,
941  callbacks: Option<Rc<RefCell<CustomCallbacks>>>,
942  is_input: bool,
943}
944
945impl Drop for OpjStream {
946  fn drop(&mut self) {
947    if let Some(callbacks) = &self.callbacks {
948      let callbacks = callbacks.borrow();
949      if let Some(free) = callbacks.m_free_user_data_fn {
950        unsafe {
951          free(callbacks.m_user_data);
952        }
953      }
954    }
955  }
956}
957
958fn new_custom_stream(buffer_size: OPJ_SIZE_T, is_input: bool) -> Box<OpjStream> {
959  let callbacks = Rc::new(RefCell::new(CustomCallbacks::default()));
960  let custom = CustomStream {
961    callbacks: callbacks.clone(),
962    m_byte_offset: 0,
963  };
964  let stream = if is_input {
965    openjp2_core::Stream::new_input(buffer_size, custom, 0)
966  } else {
967    openjp2_core::Stream::new_output(buffer_size, custom)
968  };
969  Box::new(OpjStream {
970    stream,
971    callbacks: Some(callbacks),
972    is_input,
973  })
974}
975
976#[no_mangle]
977pub unsafe extern "C" fn opj_stream_create(
978  p_buffer_size: OPJ_SIZE_T,
979  l_is_input: OPJ_BOOL,
980) -> *mut opj_stream_t {ffi_guard(|| {
981  let p_stream = Box::into_raw(new_custom_stream(p_buffer_size, l_is_input != 0)) as *mut opj_stream_t;
982  log::trace!("-- create stream: {:?}", p_stream);
983  p_stream
984})}
985
986#[no_mangle]
987pub unsafe extern "C" fn opj_stream_default_create(l_is_input: OPJ_BOOL) -> *mut opj_stream_t {ffi_guard(|| {
988  opj_stream_create(openjp2_ctypes::consts::opj::OPJ_J2K_STREAM_CHUNK_SIZE as OPJ_SIZE_T, l_is_input)
989})}
990
991#[no_mangle]
992pub unsafe extern "C" fn opj_stream_destroy(p_stream: *mut opj_stream_t) {ffi_guard(|| {
993  if !p_stream.is_null() {
994    let _ = Box::from_raw(p_stream as *mut OpjStream);
995  }
996})}
997
998#[no_mangle]
999pub unsafe extern "C" fn opj_stream_set_read_function(
1000  p_stream: *mut opj_stream_t,
1001  p_function: opj_stream_read_fn,
1002) {ffi_guard(|| {
1003  if p_stream.is_null() {
1004    return;
1005  }
1006  let p_stream = unsafe { &mut *(p_stream as *mut OpjStream) };
1007  if !p_stream.is_input {
1008    return;
1009  }
1010  if let Some(callbacks) = &p_stream.callbacks {
1011    callbacks.borrow_mut().m_read_fn = p_function;
1012  }
1013})}
1014
1015#[no_mangle]
1016pub unsafe extern "C" fn opj_stream_set_seek_function(
1017  p_stream: *mut opj_stream_t,
1018  p_function: opj_stream_seek_fn,
1019) {ffi_guard(|| {
1020  if p_stream.is_null() {
1021    return;
1022  }
1023  let p_stream = unsafe { &mut *(p_stream as *mut OpjStream) };
1024  if let Some(callbacks) = &p_stream.callbacks {
1025    callbacks.borrow_mut().m_seek_fn = p_function;
1026  }
1027})}
1028
1029#[no_mangle]
1030pub unsafe extern "C" fn opj_stream_set_write_function(
1031  p_stream: *mut opj_stream_t,
1032  p_function: opj_stream_write_fn,
1033) {ffi_guard(|| {
1034  if p_stream.is_null() {
1035    return;
1036  }
1037  let p_stream = unsafe { &mut *(p_stream as *mut OpjStream) };
1038  if p_stream.is_input {
1039    return;
1040  }
1041  if let Some(callbacks) = &p_stream.callbacks {
1042    callbacks.borrow_mut().m_write_fn = p_function;
1043  }
1044})}
1045
1046#[no_mangle]
1047pub unsafe extern "C" fn opj_stream_set_skip_function(
1048  p_stream: *mut opj_stream_t,
1049  p_function: opj_stream_skip_fn,
1050) {ffi_guard(|| {
1051  if p_stream.is_null() {
1052    return;
1053  }
1054  let p_stream = unsafe { &mut *(p_stream as *mut OpjStream) };
1055  if let Some(callbacks) = &p_stream.callbacks {
1056    callbacks.borrow_mut().m_skip_fn = p_function;
1057  }
1058})}
1059
1060#[no_mangle]
1061pub unsafe extern "C" fn opj_stream_set_user_data(
1062  p_stream: *mut opj_stream_t,
1063  p_data: *mut core::ffi::c_void,
1064  p_function: opj_stream_free_user_data_fn,
1065) {ffi_guard(|| {
1066  if p_stream.is_null() {
1067    return;
1068  }
1069  let p_stream = unsafe { &mut *(p_stream as *mut OpjStream) };
1070  if let Some(callbacks) = &p_stream.callbacks {
1071    let mut callbacks = callbacks.borrow_mut();
1072    callbacks.m_user_data = p_data;
1073    callbacks.m_free_user_data_fn = p_function;
1074  }
1075})}
1076
1077#[no_mangle]
1078pub unsafe extern "C" fn opj_stream_set_user_data_length(
1079  p_stream: *mut opj_stream_t,
1080  data_length: OPJ_UINT64,
1081) {ffi_guard(|| {
1082  if p_stream.is_null() {
1083    return;
1084  }
1085  let p_stream = unsafe { &mut *(p_stream as *mut OpjStream) };
1086  p_stream.stream.set_stream_length(data_length);
1087})}
1088
1089#[cfg(feature = "file-io")]
1090#[no_mangle]
1091pub unsafe fn opj_stream_create_default_file_stream(
1092  fname: *const core::ffi::c_char,
1093  p_is_read_stream: OPJ_BOOL,
1094) -> *mut opj_stream_t {ffi_guard(|| {
1095  opj_stream_create_file_stream(fname, 0x100000 as OPJ_SIZE_T, p_is_read_stream)
1096})}
1097
1098#[cfg(feature = "file-io")]
1099#[no_mangle]
1100pub unsafe fn opj_stream_create_file_stream(
1101  fname: *const core::ffi::c_char,
1102  p_size: OPJ_SIZE_T,
1103  p_is_read_stream: OPJ_BOOL,
1104) -> *mut opj_stream_t {ffi_guard(|| {
1105  if fname.is_null() {
1106    return core::ptr::null_mut::<opj_stream_t>();
1107  }
1108  match core::ffi::CStr::from_ptr(fname).to_str() {
1109    Ok(name) => {
1110      let is_input = p_is_read_stream != 0;
1111      let stream = match openjp2_core::Stream::new_file(name, p_size, is_input) {
1112        Ok(stream) => stream,
1113        Err(err) => {
1114          log::error!("Failed to open file stream: {err}");
1115          return core::ptr::null_mut::<opj_stream_t>();
1116        }
1117      };
1118      Box::into_raw(Box::new(OpjStream {
1119        stream,
1120        callbacks: None,
1121        is_input,
1122      })) as *mut opj_stream_t
1123    }
1124    Err(err) => {
1125      log::error!("Failed to convert C filename to Rust String: {err}");
1126      core::ptr::null_mut::<opj_stream_t>()
1127    }
1128  }
1129})}
1130
1131#[no_mangle]
1132pub unsafe fn opj_image_data_alloc(size: OPJ_SIZE_T) -> *mut core::ffi::c_void {ffi_guard(|| {
1133  crate::image::opj_image_data_alloc(size)
1134})}
1135
1136#[no_mangle]
1137pub unsafe fn opj_image_data_free(ptr: *mut core::ffi::c_void) {ffi_guard(|| {
1138  crate::image::opj_image_data_free(ptr);
1139})}
1140
1141#[no_mangle]
1142pub fn opj_has_thread_support() -> OPJ_BOOL {ffi_guard(|| {
1143  openjp2_core::has_thread_support() as OPJ_BOOL
1144})}
1145
1146#[no_mangle]
1147pub fn opj_get_num_cpus() -> core::ffi::c_int {ffi_guard(|| {
1148  std::thread::available_parallelism()
1149    .map(|n| n.get() as core::ffi::c_int)
1150    .unwrap_or(1i32)
1151})}
1152
1153/* ----------------------------------------------------------------------- */
1154/* Image object exports (moved from the core crate in Phase 6)             */
1155
1156#[no_mangle]
1157pub fn opj_image_create(
1158  numcmpts: OPJ_UINT32,
1159  cmptparms: *mut opj_image_cmptparm_t,
1160  clrspc: OPJ_COLOR_SPACE,
1161) -> *mut opj_image_t {ffi_guard(|| {
1162  crate::image::opj_image_create(numcmpts, cmptparms, clrspc)
1163})}
1164
1165#[no_mangle]
1166pub fn opj_image_destroy(image: *mut opj_image_t) {ffi_guard(|| {
1167  crate::image::opj_image_destroy(image);
1168})}
1169
1170#[no_mangle]
1171pub fn opj_image_tile_create(
1172  numcmpts: OPJ_UINT32,
1173  cmptparms: *mut opj_image_cmptparm_t,
1174  clrspc: OPJ_COLOR_SPACE,
1175) -> *mut opj_image_t {ffi_guard(|| {
1176  crate::image::opj_image_tile_create(numcmpts, cmptparms, clrspc)
1177})}