Skip to main content

rustduck_sys/
bridge.rs

1//! The sole CXX bridge for version-matched native adapters.
2//!
3//! Every `Result`-returning operation includes the native exception membrane
4//! from `native/exception_boundary.h`; standard and unknown C++ exceptions are
5//! contained before control returns to Rust.
6//!
7//! CXX generates safe Rust functions for these declarations. Each native
8//! adapter validates caller-controlled inputs and reports violations through
9//! its result membrane. A declaration uses `unsafe fn` when its adapter cannot
10//! establish that contract. The raw C ABI leaves caller obligations explicit.
11//!
12//! Native owners retain their reports, contexts, and registered handlers.
13//! Dependent allocations stay alive through native destruction, including when
14//! an upstream bridge handle is dropped first. The raw C ABI in [`crate::raw`]
15//! keeps its caller-managed ownership contract.
16
17use std::panic::{AssertUnwindSafe, catch_unwind};
18use std::sync::OnceLock;
19
20/// Pure-Rust dispatcher installed by the safe facade for private memory events.
21pub type MemoryCallbackDispatcher =
22    fn(u32, &[u8], &[u8], usize, bool, u8) -> ffi::RustDuckMemoryCallbackResult;
23pub type MemoryCallbackErrorReporter = fn(u32);
24/// Pure-Rust dispatcher installed by the safe facade for report forwarding.
25pub type ReportCallbackDispatcher = fn(i32, &[u8], bool);
26
27static MEMORY_CALLBACK_DISPATCHER: OnceLock<MemoryCallbackDispatcher> = OnceLock::new();
28static MEMORY_CALLBACK_ERROR_REPORTER: OnceLock<MemoryCallbackErrorReporter> = OnceLock::new();
29static REPORT_CALLBACK_DISPATCHER: OnceLock<ReportCallbackDispatcher> = OnceLock::new();
30
31/// Installs the process-wide private memory dispatcher.
32///
33/// The safe facade always supplies the same function; a mismatched second
34/// installation is rejected rather than silently changing callback routing.
35/// `error_reporter` runs on a native callback thread. Its panics are contained
36/// before control returns to native code.
37pub fn install_memory_callback_dispatcher(
38    dispatcher: MemoryCallbackDispatcher,
39    error_reporter: MemoryCallbackErrorReporter,
40) -> bool {
41    let dispatcher_matches = match MEMORY_CALLBACK_DISPATCHER.set(dispatcher) {
42        Ok(()) => true,
43        Err(existing) => std::ptr::fn_addr_eq(existing, dispatcher),
44    };
45    let reporter_matches = match MEMORY_CALLBACK_ERROR_REPORTER.set(error_reporter) {
46        Ok(()) => true,
47        Err(existing) => std::ptr::fn_addr_eq(existing, error_reporter),
48    };
49    dispatcher_matches && reporter_matches
50}
51
52/// Installs the process-wide private report callback dispatcher.
53///
54/// The safe facade always supplies the same function; a mismatched second
55/// installation is rejected rather than silently changing callback routing.
56pub fn install_report_callback_dispatcher(dispatcher: ReportCallbackDispatcher) -> bool {
57    match REPORT_CALLBACK_DISPATCHER.set(dispatcher) {
58        Ok(()) => true,
59        Err(existing) => std::ptr::fn_addr_eq(existing, dispatcher),
60    }
61}
62
63fn rustduck_memory_callback_writeback_failure(event_code: u32) {
64    let Some(reporter) = MEMORY_CALLBACK_ERROR_REPORTER.get() else {
65        return;
66    };
67    let _ = catch_unwind(AssertUnwindSafe(|| reporter(event_code)));
68}
69
70fn rustduck_memory_callback(
71    event_code: u32,
72    plugin_name: &[u8],
73    data: &[u8],
74    data_max_size: usize,
75    data_read_only: bool,
76    validity: u8,
77) -> ffi::RustDuckMemoryCallbackResult {
78    let Some(dispatcher) = MEMORY_CALLBACK_DISPATCHER.get() else {
79        return ffi::RustDuckMemoryCallbackResult {
80            ok: false,
81            data: Vec::new(),
82        };
83    };
84    catch_unwind(AssertUnwindSafe(|| {
85        dispatcher(
86            event_code,
87            plugin_name,
88            data,
89            data_max_size,
90            data_read_only,
91            validity,
92        )
93    }))
94    .unwrap_or(ffi::RustDuckMemoryCallbackResult {
95        ok: false,
96        data: Vec::new(),
97    })
98}
99
100fn rustduck_report_forward_callback(severity: i32, message: &[u8], message_valid: bool) {
101    let Some(dispatcher) = REPORT_CALLBACK_DISPATCHER.get() else {
102        return;
103    };
104    let _ = catch_unwind(AssertUnwindSafe(|| {
105        dispatcher(severity, message, message_valid);
106    }));
107}
108
109#[cxx::bridge]
110pub mod ffi {
111    struct RustDuckProcessorConfig {
112        ignore_joint_termination: i64,
113        buffer_size: i64,
114        max_flushed_packets: i64,
115        max_input_packets: i64,
116        max_output_packets: i64,
117        initial_input_packets: i64,
118        add_input_stuffing_0: i64,
119        add_input_stuffing_1: i64,
120        add_start_stuffing: i64,
121        add_stop_stuffing: i64,
122        bitrate: i64,
123        bitrate_adjust_interval: i64,
124        receive_timeout: i64,
125        log_plugin_index: bool,
126        plugins: Vec<u8>,
127    }
128
129    struct RustDuckInputSwitcherConfig {
130        fast_switch: bool,
131        delayed_switch: bool,
132        terminate: bool,
133        reuse_port: bool,
134        first_input: i64,
135        primary_input: i64,
136        cycle_count: i64,
137        buffered_packets: i64,
138        max_input_packets: i64,
139        max_output_packets: i64,
140        sock_buffer: i64,
141        remote_server_port: i64,
142        receive_timeout: i64,
143        event_udp_port: i64,
144        event_ttl: i64,
145        plugins: Vec<u8>,
146        event_command: Vec<u8>,
147        event_udp_address: Vec<u8>,
148        event_local_address: Vec<u8>,
149    }
150
151    struct RustDuckMemoryCallbackResult {
152        ok: bool,
153        data: Vec<u8>,
154    }
155
156    struct RustDuckAnalyzerSummary {
157        packet_count: u64,
158        ts_bitrate: f64,
159        ts_pcr_bitrate_188: f64,
160        invalid_sync_count: u64,
161        transport_error_count: u64,
162        pcr_pid_count: u64,
163    }
164
165    struct RustDuckAnalyzerCaDescriptor {
166        cas_id: u16,
167        ca_pid: u16,
168        program_level: bool,
169        has_elementary_pid: bool,
170        elementary_pid: u16,
171    }
172
173    struct RustDuckAnalyzerService {
174        service_id: u16,
175        name: String,
176        provider: String,
177        pid_count: u64,
178        pmt_pid: u16,
179        pcr_pid: u16,
180        bitrate: f64,
181        packet_count: u64,
182        scrambled_pid_count: u64,
183        ca_descriptors: Vec<RustDuckAnalyzerCaDescriptor>,
184    }
185
186    struct RustDuckAnalyzerPid {
187        pid: u16,
188        services: Vec<u16>,
189        carries_video: bool,
190        carries_audio: bool,
191        scrambled: bool,
192        description: String,
193        packet_count: u64,
194        scrambled_packet_count: u64,
195        invalid_pes_count: u64,
196        invalid_pes_start_count: u64,
197        bitrate: f64,
198        ts_pcr_bitrate: f64,
199        current_continuity: u8,
200        unexpected_discontinuity_count: u64,
201        duplicated_packet_count: u64,
202        invalid_scrambling_control_count: u64,
203        cas_id: u16,
204        cas_operators: Vec<u32>,
205        current_scrambling_control: u8,
206    }
207
208    struct RustDuckAnalyzerReport {
209        summary: RustDuckAnalyzerSummary,
210        services: Vec<RustDuckAnalyzerService>,
211        pids: Vec<RustDuckAnalyzerPid>,
212    }
213
214    extern "Rust" {
215        fn rustduck_memory_callback_writeback_failure(event_code: u32);
216        fn rustduck_memory_callback(
217            event_code: u32,
218            plugin_name: &[u8],
219            data: &[u8],
220            data_max_size: usize,
221            data_read_only: bool,
222            validity: u8,
223        ) -> RustDuckMemoryCallbackResult;
224        fn rustduck_report_forward_callback(severity: i32, message: &[u8], message_valid: bool);
225    }
226
227    unsafe extern "C++" {
228        include!("rustduck-sys/native/exception_boundary.h");
229        include!("rustduck-sys/native/bridge/report.h");
230        include!("rustduck-sys/native/bridge/context.h");
231        include!("rustduck-sys/native/bridge/section_file.h");
232        include!("rustduck-sys/native/bridge/memory_handler.h");
233        include!("rustduck-sys/native/bridge/processor.h");
234        include!("rustduck-sys/native/bridge/analyzer.h");
235        include!("rustduck-sys/native/bridge/input_switcher.h");
236        include!("rustduck-sys/native/bridge/system_monitor.h");
237        include!("rustduck-sys/native/bridge/test_hooks.h");
238
239        type RustDuckReport;
240        type RustDuckDuckContext;
241        type RustDuckSectionFile;
242        type RustDuckMemoryHandler;
243        type RustDuckTSProcessor;
244        type RustDuckProcessorAbortToken;
245        type RustDuckTSAnalyzer;
246        type RustDuckInputSwitcher;
247        type RustDuckSystemMonitor;
248
249        fn rustduck_memory_handler_new() -> Result<UniquePtr<RustDuckMemoryHandler>>;
250        fn rustduck_processor_new(
251            report: &RustDuckReport,
252        ) -> Result<UniquePtr<RustDuckTSProcessor>>;
253        fn rustduck_processor_register_input(
254            processor: Pin<&mut RustDuckTSProcessor>,
255            handler: &RustDuckMemoryHandler,
256        ) -> Result<()>;
257        fn rustduck_processor_register_output(
258            processor: Pin<&mut RustDuckTSProcessor>,
259            handler: &RustDuckMemoryHandler,
260        ) -> Result<()>;
261        fn rustduck_processor_start(
262            processor: Pin<&mut RustDuckTSProcessor>,
263            config: &RustDuckProcessorConfig,
264        ) -> Result<bool>;
265        fn rustduck_processor_abort(processor: Pin<&mut RustDuckTSProcessor>) -> Result<()>;
266        fn rustduck_processor_wait(processor: Pin<&mut RustDuckTSProcessor>) -> Result<()>;
267        fn rustduck_processor_is_started(processor: &RustDuckTSProcessor) -> Result<bool>;
268        fn rustduck_processor_abort_token(
269            processor: &RustDuckTSProcessor,
270        ) -> SharedPtr<RustDuckProcessorAbortToken>;
271        fn rustduck_processor_abort_token_request(
272            token: &RustDuckProcessorAbortToken,
273        ) -> Result<()>;
274
275        fn rustduck_analyzer_new(
276            context: &RustDuckDuckContext,
277        ) -> Result<UniquePtr<RustDuckTSAnalyzer>>;
278        fn rustduck_analyzer_feed(
279            analyzer: Pin<&mut RustDuckTSAnalyzer>,
280            packets: &[u8],
281        ) -> Result<()>;
282        fn rustduck_analyzer_set_bitrate_hint(
283            analyzer: Pin<&mut RustDuckTSAnalyzer>,
284            bitrate: f64,
285            confidence: u8,
286        ) -> Result<()>;
287        fn rustduck_analyzer_snapshot(
288            analyzer: Pin<&mut RustDuckTSAnalyzer>,
289        ) -> Result<RustDuckAnalyzerReport>;
290        fn rustduck_analyzer_reset(analyzer: Pin<&mut RustDuckTSAnalyzer>) -> Result<()>;
291
292        fn rustduck_input_switcher_new(
293            report: &RustDuckReport,
294        ) -> Result<UniquePtr<RustDuckInputSwitcher>>;
295        fn rustduck_input_switcher_register_input(
296            switcher: Pin<&mut RustDuckInputSwitcher>,
297            handler: &RustDuckMemoryHandler,
298        ) -> Result<()>;
299        fn rustduck_input_switcher_register_output(
300            switcher: Pin<&mut RustDuckInputSwitcher>,
301            handler: &RustDuckMemoryHandler,
302        ) -> Result<()>;
303        fn rustduck_input_switcher_start(
304            switcher: Pin<&mut RustDuckInputSwitcher>,
305            config: &RustDuckInputSwitcherConfig,
306        ) -> Result<bool>;
307        fn rustduck_input_switcher_stop(switcher: Pin<&mut RustDuckInputSwitcher>) -> Result<()>;
308        fn rustduck_input_switcher_wait(switcher: Pin<&mut RustDuckInputSwitcher>) -> Result<()>;
309
310        fn rustduck_system_monitor_new(
311            report: &RustDuckReport,
312            config: &[u8],
313        ) -> Result<UniquePtr<RustDuckSystemMonitor>>;
314        fn rustduck_system_monitor_start(monitor: Pin<&mut RustDuckSystemMonitor>) -> Result<()>;
315        fn rustduck_system_monitor_stop(monitor: Pin<&mut RustDuckSystemMonitor>) -> Result<()>;
316        fn rustduck_system_monitor_wait(monitor: Pin<&mut RustDuckSystemMonitor>) -> Result<()>;
317
318        fn rustduck_report_null() -> Result<UniquePtr<RustDuckReport>>;
319        fn rustduck_report_stderr() -> Result<UniquePtr<RustDuckReport>>;
320        fn rustduck_report_asynchronous(
321            severity: i32,
322            synchronous_log: bool,
323            timed_log: bool,
324            log_message_count: usize,
325        ) -> Result<UniquePtr<RustDuckReport>>;
326        fn rustduck_report_asynchronous_with_forwarder(
327            severity: i32,
328            synchronous_log: bool,
329            log_message_count: usize,
330        ) -> Result<UniquePtr<RustDuckReport>>;
331        fn rustduck_report_set_max_severity(
332            report: Pin<&mut RustDuckReport>,
333            severity: i32,
334        ) -> Result<()>;
335        fn rustduck_report_log(
336            report: &RustDuckReport,
337            severity: i32,
338            message: &[u8],
339        ) -> Result<()>;
340        fn rustduck_report_terminate(report: Pin<&mut RustDuckReport>) -> Result<()>;
341
342        fn rustduck_context_new(report: &RustDuckReport) -> Result<UniquePtr<RustDuckDuckContext>>;
343        fn rustduck_context_set_default_charset(
344            context: Pin<&mut RustDuckDuckContext>,
345            charset: &[u8],
346        ) -> Result<bool>;
347        fn rustduck_context_set_default_cas_id(
348            context: Pin<&mut RustDuckDuckContext>,
349            cas_id: u16,
350        ) -> Result<()>;
351        fn rustduck_context_set_default_pds(
352            context: Pin<&mut RustDuckDuckContext>,
353            pds: u32,
354        ) -> Result<()>;
355        fn rustduck_context_add_standards(
356            context: Pin<&mut RustDuckDuckContext>,
357            standards: u32,
358        ) -> Result<()>;
359        fn rustduck_context_standards(context: &RustDuckDuckContext) -> Result<u32>;
360        fn rustduck_context_reset_standards(
361            context: Pin<&mut RustDuckDuckContext>,
362            standards: u32,
363        ) -> Result<()>;
364        fn rustduck_context_set_time_reference_offset(
365            context: Pin<&mut RustDuckDuckContext>,
366            offset_millis: i64,
367        ) -> Result<()>;
368        fn rustduck_context_set_time_reference(
369            context: Pin<&mut RustDuckDuckContext>,
370            name: &[u8],
371        ) -> Result<bool>;
372
373        fn rustduck_section_file_new(
374            context: &RustDuckDuckContext,
375        ) -> Result<UniquePtr<RustDuckSectionFile>>;
376        fn rustduck_section_file_clear(section_file: Pin<&mut RustDuckSectionFile>) -> Result<()>;
377        fn rustduck_section_file_binary_size(section_file: &RustDuckSectionFile) -> Result<usize>;
378        fn rustduck_section_file_sections_count(
379            section_file: &RustDuckSectionFile,
380        ) -> Result<usize>;
381        fn rustduck_section_file_tables_count(section_file: &RustDuckSectionFile) -> Result<usize>;
382        fn rustduck_section_file_set_crc_validation(
383            section_file: Pin<&mut RustDuckSectionFile>,
384            mode: i32,
385        ) -> Result<()>;
386        fn rustduck_section_file_load_binary_buffer(
387            section_file: Pin<&mut RustDuckSectionFile>,
388            data: &[u8],
389        ) -> Result<bool>;
390        fn rustduck_section_file_to_binary(section_file: &RustDuckSectionFile) -> Result<Vec<u8>>;
391        fn rustduck_section_file_load_binary(
392            section_file: Pin<&mut RustDuckSectionFile>,
393            path: &[u8],
394        ) -> Result<bool>;
395        fn rustduck_section_file_save_binary(
396            section_file: &RustDuckSectionFile,
397            path: &[u8],
398        ) -> Result<bool>;
399        fn rustduck_section_file_load_xml(
400            section_file: Pin<&mut RustDuckSectionFile>,
401            source: &[u8],
402        ) -> Result<bool>;
403        fn rustduck_section_file_save_xml(
404            section_file: &RustDuckSectionFile,
405            path: &[u8],
406        ) -> Result<bool>;
407        fn rustduck_section_file_save_json(
408            section_file: &RustDuckSectionFile,
409            path: &[u8],
410        ) -> Result<bool>;
411        fn rustduck_section_file_to_xml_utf16(
412            section_file: &RustDuckSectionFile,
413        ) -> Result<Vec<u8>>;
414        fn rustduck_section_file_to_json_utf16(
415            section_file: &RustDuckSectionFile,
416        ) -> Result<Vec<u8>>;
417
418        // Fault-injection seams for this workspace's native tests. The
419        // `native_test_hooks` feature both declares these symbols and defines the
420        // matching native macro, so default builds expose no test surface.
421        #[cfg(feature = "native_test_hooks")]
422        #[doc(hidden)]
423        fn rustduck_test_set_failure(point: i32, trigger_after: i32, unknown: bool) -> Result<()>;
424        #[cfg(feature = "native_test_hooks")]
425        #[doc(hidden)]
426        fn rustduck_test_clear_failure() -> Result<()>;
427        #[cfg(feature = "native_test_hooks")]
428        #[doc(hidden)]
429        fn rustduck_test_throw_standard() -> Result<()>;
430        #[cfg(feature = "native_test_hooks")]
431        #[doc(hidden)]
432        fn rustduck_test_throw_unknown() -> Result<()>;
433    }
434}