Skip to main content

rustduck_sys/
raw.rs

1//! Raw declarations for TSDuck's exported application ABI.
2//!
3//! TSDuck is implemented in C++. Its complete C++ class API does not have a
4//! stable C ABI. The `tspy*` layer is the official C-compatible high-level ABI
5//! used by TSDuck's Python module.
6//!
7//! # Safety
8//!
9//! These declarations are an unsafe ABI escape hatch. Callers are responsible
10//! for native ownership, nullability, buffer lifetime, thread affinity,
11//! callback containment, error interpretation, and matching every allocation
12//! with its TSDuck delete operation. Prefer `rustduck` or `rustduck-core`'s safe API.
13//!
14//! # Deprecated callback contracts
15//!
16//! [`LogCallback`](crate::raw::LogCallback) and
17//! [`PluginCallback`](crate::raw::PluginCallback) retain their original
18//! declarations for source compatibility, but those declarations do not match
19//! TSDuck's callback ABI. Calling the corresponding legacy constructors can
20//! cause undefined behavior. Use [`LogCallbackUtf16`](crate::raw::LogCallbackUtf16),
21//! [`PluginCallbackUtf16`](crate::raw::PluginCallbackUtf16), and the `Utf16`
22//! constructors instead. The deprecated declarations retain this risk.
23
24use std::mem::MaybeUninit;
25use std::os::raw::{c_long, c_void};
26
27include!(concat!(env!("OUT_DIR"), "/tsduck_version.rs"));
28
29/// Rust representation of TSDuck's 16-bit `UChar` code unit.
30pub type UChar = u16;
31
32/// Callback with the ABI expected by synchronous and asynchronous TSDuck reports.
33///
34/// `message` borrows `message_bytes` bytes of native-endian UTF-16 for the
35/// duration of the call. TSDuck 3.44 ignores the return value; return a null
36/// pointer. Contain panics before returning to native code.
37pub type LogCallbackUtf16 =
38    unsafe extern "C" fn(severity: i32, message: *const UChar, message_bytes: usize) -> *mut c_void;
39
40/// Plugin callback with the ABI expected by TSDuck's Python-compatible handler.
41///
42/// `plugin_name` borrows `plugin_name_bytes` bytes of native-endian UTF-16 for
43/// the duration of the call. `data` remains a byte buffer with its own explicit
44/// lengths. Return `false` to report callback failure and contain all panics.
45pub type PluginCallbackUtf16 = unsafe extern "C" fn(
46    event_code: u32,
47    plugin_name: *const UChar,
48    plugin_name_bytes: usize,
49    plugin_index: usize,
50    plugin_count: usize,
51    bitrate: usize,
52    plugin_packets: usize,
53    total_packets: usize,
54    data: *const u8,
55    data_size: usize,
56    data_max_size: usize,
57    data_read_only: bool,
58    event_data: *mut c_void,
59) -> bool;
60
61/// Legacy callback declaration with an incompatible return type and message pointer.
62///
63/// This declaration does not match TSDuck's `void* (*)(int, const UChar*,
64/// size_t)` callback ABI. Using it can cause undefined behavior. Use
65/// [`LogCallbackUtf16`] instead.
66#[deprecated(
67    since = "1.1.0",
68    note = "incompatible with TSDuck's callback ABI and can cause undefined behavior; use LogCallbackUtf16"
69)]
70pub type LogCallback = unsafe extern "C" fn(severity: i32, message: *const u8, size: usize);
71
72/// Legacy plugin callback declaration with an incompatible plugin-name pointer.
73///
74/// This declaration does not match TSDuck's `const UChar*` plugin-name ABI. Use
75/// [`PluginCallbackUtf16`] instead.
76#[deprecated(
77    since = "1.1.0",
78    note = "incompatible with TSDuck's plugin-name ABI; use PluginCallbackUtf16"
79)]
80pub type PluginCallback = unsafe extern "C" fn(
81    event_code: u32,
82    plugin_name: *const u8,
83    plugin_name_size: usize,
84    plugin_index: usize,
85    plugin_count: usize,
86    bitrate: usize,
87    plugin_packets: usize,
88    total_packets: usize,
89    data: *const u8,
90    data_size: usize,
91    data_max_size: usize,
92    data_read_only: bool,
93    event_data: *mut c_void,
94) -> bool;
95
96/// Target-specific layout measurements for the repository-owned `tspy` mirror.
97///
98/// The native probe is compiled with the same TSDuck headers as the bridge.
99/// This layout contains mirror measurements. Callback integration tests execute
100/// the corrected declarations against the installed TSDuck library.
101#[repr(C)]
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct TspyAbiLayout {
104    /// Major version from the TSDuck headers seen by the native compiler.
105    pub tsduck_header_version_major: u32,
106    /// Minor version from the TSDuck headers seen by the native compiler.
107    pub tsduck_header_version_minor: u32,
108    /// `sizeof(tspyTSProcessorArgs)`.
109    pub ts_processor_args_size: usize,
110    /// `alignof(tspyTSProcessorArgs)`.
111    pub ts_processor_args_align: usize,
112    /// Field offsets in declaration order.
113    pub ts_processor_args_offsets: [usize; 16],
114    /// `sizeof(tspyInputSwitcherArgs)`.
115    pub input_switcher_args_size: usize,
116    /// `alignof(tspyInputSwitcherArgs)`.
117    pub input_switcher_args_align: usize,
118    /// Field offsets in declaration order.
119    pub input_switcher_args_offsets: [usize; 23],
120    /// `sizeof(uint32_t)`.
121    pub uint32_size: usize,
122    /// `alignof(uint32_t)`.
123    pub uint32_align: usize,
124    /// `sizeof(size_t)`.
125    pub size_t_size: usize,
126    /// `alignof(size_t)`.
127    pub size_t_align: usize,
128    /// `sizeof(bool)`.
129    pub bool_size: usize,
130    /// `alignof(bool)`.
131    pub bool_align: usize,
132    /// `sizeof(long)`.
133    pub long_size: usize,
134    /// `alignof(long)`.
135    pub long_align: usize,
136}
137
138/// Returns the native layout of the repository-owned raw ABI mirror.
139#[must_use]
140pub fn tspy_abi_layout() -> TspyAbiLayout {
141    let mut layout = MaybeUninit::<TspyAbiLayout>::uninit();
142
143    // SAFETY: `layout` is non-null aligned writable storage for the complete
144    // result. The native probe initializes every field and does not retain it.
145    unsafe {
146        rustduck_tspy_query_abi_layout(layout.as_mut_ptr());
147        layout.assume_init()
148    }
149}
150
151/// Arguments passed to `tspyStartTSProcessor`.
152#[repr(C)]
153#[derive(Clone, Copy)]
154pub struct TSProcessorArgs {
155    pub ignore_joint_termination: c_long,
156    pub buffer_size: c_long,
157    pub max_flushed_packets: c_long,
158    pub max_input_packets: c_long,
159    pub max_output_packets: c_long,
160    pub initial_input_packets: c_long,
161    pub add_input_stuffing_0: c_long,
162    pub add_input_stuffing_1: c_long,
163    pub add_start_stuffing: c_long,
164    pub add_stop_stuffing: c_long,
165    pub bitrate: c_long,
166    pub bitrate_adjust_interval: c_long,
167    pub receive_timeout: c_long,
168    pub log_plugin_index: c_long,
169    pub plugins: *mut u8,
170    pub plugins_size: usize,
171}
172
173/// Arguments passed to `tspyStartInputSwitcher`.
174#[repr(C)]
175#[derive(Clone, Copy)]
176pub struct InputSwitcherArgs {
177    pub fast_switch: c_long,
178    pub delayed_switch: c_long,
179    pub terminate: c_long,
180    pub reuse_port: c_long,
181    pub first_input: c_long,
182    pub primary_input: c_long,
183    pub cycle_count: c_long,
184    pub buffered_packets: c_long,
185    pub max_input_packets: c_long,
186    pub max_output_packets: c_long,
187    pub sock_buffer: c_long,
188    pub remote_server_port: c_long,
189    pub receive_timeout: c_long,
190    pub plugins: *mut u8,
191    pub plugins_size: usize,
192    pub event_command: *mut u8,
193    pub event_command_size: usize,
194    pub event_udp_addr: *mut u8,
195    pub event_udp_addr_size: usize,
196    pub event_udp_port: c_long,
197    pub local_addr: *mut u8,
198    pub local_addr_size: usize,
199    pub event_ttl: c_long,
200}
201
202struct RedactedPointer<T>(*const T);
203
204impl<T> RedactedPointer<T> {
205    fn new(pointer: *mut T) -> Self {
206        Self(pointer)
207    }
208}
209
210impl<T> std::fmt::Debug for RedactedPointer<T> {
211    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212        formatter.write_str(if self.0.is_null() { "null" } else { "non-null" })
213    }
214}
215
216impl std::fmt::Debug for TSProcessorArgs {
217    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        formatter
219            .debug_struct("TSProcessorArgs")
220            .field("ignore_joint_termination", &self.ignore_joint_termination)
221            .field("buffer_size", &self.buffer_size)
222            .field("max_flushed_packets", &self.max_flushed_packets)
223            .field("max_input_packets", &self.max_input_packets)
224            .field("max_output_packets", &self.max_output_packets)
225            .field("initial_input_packets", &self.initial_input_packets)
226            .field("add_input_stuffing_0", &self.add_input_stuffing_0)
227            .field("add_input_stuffing_1", &self.add_input_stuffing_1)
228            .field("add_start_stuffing", &self.add_start_stuffing)
229            .field("add_stop_stuffing", &self.add_stop_stuffing)
230            .field("bitrate", &self.bitrate)
231            .field("bitrate_adjust_interval", &self.bitrate_adjust_interval)
232            .field("receive_timeout", &self.receive_timeout)
233            .field("log_plugin_index", &self.log_plugin_index)
234            .field("plugins", &RedactedPointer::new(self.plugins))
235            .field("plugins_size", &self.plugins_size)
236            .finish()
237    }
238}
239
240impl std::fmt::Debug for InputSwitcherArgs {
241    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        formatter
243            .debug_struct("InputSwitcherArgs")
244            .field("fast_switch", &self.fast_switch)
245            .field("delayed_switch", &self.delayed_switch)
246            .field("terminate", &self.terminate)
247            .field("reuse_port", &self.reuse_port)
248            .field("first_input", &self.first_input)
249            .field("primary_input", &self.primary_input)
250            .field("cycle_count", &self.cycle_count)
251            .field("buffered_packets", &self.buffered_packets)
252            .field("max_input_packets", &self.max_input_packets)
253            .field("max_output_packets", &self.max_output_packets)
254            .field("sock_buffer", &self.sock_buffer)
255            .field("remote_server_port", &self.remote_server_port)
256            .field("receive_timeout", &self.receive_timeout)
257            .field("plugins", &RedactedPointer::new(self.plugins))
258            .field("plugins_size", &self.plugins_size)
259            .field("event_command", &RedactedPointer::new(self.event_command))
260            .field("event_command_size", &self.event_command_size)
261            .field("event_udp_addr", &RedactedPointer::new(self.event_udp_addr))
262            .field("event_udp_addr_size", &self.event_udp_addr_size)
263            .field("event_udp_port", &self.event_udp_port)
264            .field("local_addr", &RedactedPointer::new(self.local_addr))
265            .field("local_addr_size", &self.local_addr_size)
266            .field("event_ttl", &self.event_ttl)
267            .finish()
268    }
269}
270
271unsafe extern "C" {
272    fn rustduck_tspy_query_abi_layout(layout: *mut TspyAbiLayout);
273
274    pub fn tspyVersionInteger() -> u32;
275    pub fn tspyVersionString(buffer: *mut u8, size: *mut usize);
276
277    pub fn tspyNullReport() -> *mut c_void;
278    pub fn tspyStdErrReport() -> *mut c_void;
279    pub fn tspyNewAsyncReport(
280        severity: i32,
281        sync_log: bool,
282        timed_log: bool,
283        log_msg_count: usize,
284    ) -> *mut c_void;
285    /// Legacy synchronous report constructor with an incompatible callback ABI.
286    #[allow(deprecated)]
287    #[deprecated(
288        since = "1.1.0",
289        note = "uses an incompatible callback ABI; use tspyNewPySyncReportUtf16"
290    )]
291    pub fn tspyNewPySyncReport(callback: LogCallback, severity: i32) -> *mut c_void;
292    /// Creates a synchronous report using TSDuck's UTF-16 callback ABI.
293    #[allow(clashing_extern_declarations)]
294    #[link_name = "tspyNewPySyncReport"]
295    pub fn tspyNewPySyncReportUtf16(callback: LogCallbackUtf16, severity: i32) -> *mut c_void;
296    /// Legacy asynchronous report constructor with an incompatible callback ABI.
297    #[allow(deprecated)]
298    #[deprecated(
299        since = "1.1.0",
300        note = "uses an incompatible callback ABI; use tspyNewPyAsyncReportUtf16"
301    )]
302    pub fn tspyNewPyAsyncReport(
303        callback: LogCallback,
304        severity: i32,
305        sync_log: bool,
306        log_msg_count: usize,
307    ) -> *mut c_void;
308    /// Creates an asynchronous report using TSDuck's UTF-16 callback ABI.
309    #[allow(clashing_extern_declarations)]
310    #[link_name = "tspyNewPyAsyncReport"]
311    pub fn tspyNewPyAsyncReportUtf16(
312        callback: LogCallbackUtf16,
313        severity: i32,
314        sync_log: bool,
315        log_msg_count: usize,
316    ) -> *mut c_void;
317    pub fn tspyDeleteReport(report: *mut c_void);
318    pub fn tspyTerminateAsyncReport(report: *mut c_void);
319    pub fn tspySetMaxSeverity(report: *mut c_void, severity: i32);
320    pub fn tspyLogReport(report: *mut c_void, severity: i32, message: *const u8, size: usize);
321    pub fn tspyReportHeader(severity: i32, buffer: *mut u8, size: *mut usize);
322
323    pub fn tspyNewDuckContext(report: *mut c_void) -> *mut c_void;
324    pub fn tspyDeleteDuckContext(duck: *mut c_void);
325    pub fn tspyDuckContextSetDefaultCharset(
326        duck: *mut c_void,
327        name: *const u8,
328        size: usize,
329    ) -> bool;
330    pub fn tspyDuckContextSetDefaultCASId(duck: *mut c_void, cas: u16);
331    pub fn tspyDuckContextSetDefaultPDS(duck: *mut c_void, pds: u32);
332    pub fn tspyDuckContextAddStandards(duck: *mut c_void, mask: u32);
333    pub fn tspyDuckContextStandards(duck: *mut c_void) -> u32;
334    pub fn tspyDuckContextResetStandards(duck: *mut c_void, mask: u32);
335    pub fn tspyDuckContextSetTimeReferenceOffset(duck: *mut c_void, offset: i64);
336    pub fn tspyDuckContextSetTimeReference(duck: *mut c_void, name: *const u8, size: usize)
337    -> bool;
338
339    /// Legacy plugin handler constructor with an incompatible plugin-name ABI.
340    #[allow(deprecated)]
341    #[deprecated(
342        since = "1.1.0",
343        note = "uses an incompatible plugin-name ABI; use tspyNewPyPluginEventHandlerUtf16"
344    )]
345    pub fn tspyNewPyPluginEventHandler(callback: PluginCallback) -> *mut c_void;
346    /// Creates a plugin event handler using TSDuck's UTF-16 callback ABI.
347    #[allow(clashing_extern_declarations)]
348    #[link_name = "tspyNewPyPluginEventHandler"]
349    pub fn tspyNewPyPluginEventHandlerUtf16(callback: PluginCallbackUtf16) -> *mut c_void;
350    pub fn tspyDeletePyPluginEventHandler(handler: *mut c_void);
351    pub fn tspyPyPluginEventHandlerUpdateData(
352        event_data: *mut c_void,
353        data: *mut c_void,
354        size: usize,
355    );
356
357    pub fn tspyNewSectionFile(duck: *mut c_void) -> *mut c_void;
358    pub fn tspyDeleteSectionFile(section_file: *mut c_void);
359    pub fn tspySectionFileClear(section_file: *mut c_void);
360    pub fn tspySectionFileBinarySize(section_file: *mut c_void) -> usize;
361    pub fn tspySectionFileSectionsCount(section_file: *mut c_void) -> usize;
362    pub fn tspySectionFileTablesCount(section_file: *mut c_void) -> usize;
363    pub fn tspySectionFileSetCRCValidation(section_file: *mut c_void, mode: i32);
364    pub fn tspySectionLoadBuffer(section_file: *mut c_void, buffer: *const u8, size: usize)
365    -> bool;
366    pub fn tspySectionSaveBuffer(section_file: *mut c_void, buffer: *mut u8, size: *mut usize);
367    pub fn tspySectionFileLoadBinary(
368        section_file: *mut c_void,
369        name: *const u8,
370        size: usize,
371    ) -> bool;
372    pub fn tspySectionFileSaveBinary(
373        section_file: *mut c_void,
374        name: *const u8,
375        size: usize,
376    ) -> bool;
377    pub fn tspySectionFileLoadXML(section_file: *mut c_void, name: *const u8, size: usize) -> bool;
378    pub fn tspySectionFileSaveXML(section_file: *mut c_void, name: *const u8, size: usize) -> bool;
379    pub fn tspySectionFileSaveJSON(section_file: *mut c_void, name: *const u8, size: usize)
380    -> bool;
381    pub fn tspySectionFileToXML(
382        section_file: *mut c_void,
383        buffer: *mut u8,
384        size: *mut usize,
385    ) -> usize;
386    pub fn tspySectionFileToJSON(
387        section_file: *mut c_void,
388        buffer: *mut u8,
389        size: *mut usize,
390    ) -> usize;
391    pub fn tspySectionFileReorganizeEITs(
392        section_file: *mut c_void,
393        year: i32,
394        month: i32,
395        day: i32,
396    );
397
398    pub fn tspyNewSystemMonitor(
399        report: *mut c_void,
400        config: *const u8,
401        config_size: usize,
402    ) -> *mut c_void;
403    pub fn tspyDeleteSystemMonitor(monitor: *mut c_void);
404    pub fn tspyStartSystemMonitor(monitor: *mut c_void);
405    pub fn tspyStopSystemMonitor(monitor: *mut c_void);
406    pub fn tspyWaitSystemMonitor(monitor: *mut c_void);
407
408    pub fn tspyPluginEventHandlerRegister(
409        registry: *mut c_void,
410        handler: *mut c_void,
411        event_code: u32,
412    );
413    pub fn tspyPluginEventHandlerRegisterInput(registry: *mut c_void, handler: *mut c_void);
414    pub fn tspyPluginEventHandlerRegisterOutput(registry: *mut c_void, handler: *mut c_void);
415
416    pub fn tspyNewTSProcessor(report: *mut c_void) -> *mut c_void;
417    pub fn tspyDeleteTSProcessor(processor: *mut c_void);
418    pub fn tspyStartTSProcessor(processor: *mut c_void, args: *const TSProcessorArgs) -> bool;
419    pub fn tspyAbortTSProcessor(processor: *mut c_void);
420    pub fn tspyWaitTSProcessor(processor: *mut c_void);
421
422    pub fn tspyNewInputSwitcher(report: *mut c_void) -> *mut c_void;
423    pub fn tspyDeleteInputSwitcher(switcher: *mut c_void);
424    pub fn tspyStartInputSwitcher(switcher: *mut c_void, args: *const InputSwitcherArgs) -> bool;
425    pub fn tspyInputSwitcherSetInput(switcher: *mut c_void, index: usize);
426    pub fn tspyInputSwitcherNextInput(switcher: *mut c_void);
427    pub fn tspyInputSwitcherPreviousInput(switcher: *mut c_void);
428    pub fn tspyInputSwitcherCurrentInput(switcher: *mut c_void) -> usize;
429    pub fn tspyStopInputSwitcher(switcher: *mut c_void);
430    pub fn tspyWaitInputSwitcher(switcher: *mut c_void);
431
432}