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