rustduck-sys 1.1.0

Raw Rust FFI bindings to the C ABI used by TSDuck's Python API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! The sole CXX bridge for version-matched native adapters.
//!
//! Every `Result`-returning operation includes the native exception membrane
//! from `native/exception_boundary.h`; standard and unknown C++ exceptions are
//! contained before control returns to Rust.
//!
//! CXX generates safe Rust functions for these declarations. Each native
//! adapter validates caller-controlled inputs and reports violations through
//! its result membrane. A declaration uses `unsafe fn` when its adapter cannot
//! establish that contract. The raw C ABI leaves caller obligations explicit.
//!
//! Native owners retain their reports, contexts, and registered handlers.
//! Dependent allocations stay alive through native destruction, including when
//! an upstream bridge handle is dropped first. The raw C ABI in [`crate::raw`]
//! keeps its caller-managed ownership contract.

use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::OnceLock;

/// Pure-Rust dispatcher installed by the safe facade for private memory events.
pub type MemoryCallbackDispatcher =
    fn(u32, &[u8], &[u8], usize, bool, u8) -> ffi::RustDuckMemoryCallbackResult;
pub type MemoryCallbackErrorReporter = fn(u32);
/// Pure-Rust dispatcher installed by the safe facade for report forwarding.
pub type ReportCallbackDispatcher = fn(i32, &[u8], bool);

static MEMORY_CALLBACK_DISPATCHER: OnceLock<MemoryCallbackDispatcher> = OnceLock::new();
static MEMORY_CALLBACK_ERROR_REPORTER: OnceLock<MemoryCallbackErrorReporter> = OnceLock::new();
static REPORT_CALLBACK_DISPATCHER: OnceLock<ReportCallbackDispatcher> = OnceLock::new();

/// Installs the process-wide private memory dispatcher.
///
/// The safe facade always supplies the same function; a mismatched second
/// installation is rejected rather than silently changing callback routing.
/// `error_reporter` runs on a native callback thread. Its panics are contained
/// before control returns to native code.
pub fn install_memory_callback_dispatcher(
    dispatcher: MemoryCallbackDispatcher,
    error_reporter: MemoryCallbackErrorReporter,
) -> bool {
    let dispatcher_matches = match MEMORY_CALLBACK_DISPATCHER.set(dispatcher) {
        Ok(()) => true,
        Err(existing) => std::ptr::fn_addr_eq(existing, dispatcher),
    };
    let reporter_matches = match MEMORY_CALLBACK_ERROR_REPORTER.set(error_reporter) {
        Ok(()) => true,
        Err(existing) => std::ptr::fn_addr_eq(existing, error_reporter),
    };
    dispatcher_matches && reporter_matches
}

/// Installs the process-wide private report callback dispatcher.
///
/// The safe facade always supplies the same function; a mismatched second
/// installation is rejected rather than silently changing callback routing.
pub fn install_report_callback_dispatcher(dispatcher: ReportCallbackDispatcher) -> bool {
    match REPORT_CALLBACK_DISPATCHER.set(dispatcher) {
        Ok(()) => true,
        Err(existing) => std::ptr::fn_addr_eq(existing, dispatcher),
    }
}

fn rustduck_memory_callback_writeback_failure(event_code: u32) {
    let Some(reporter) = MEMORY_CALLBACK_ERROR_REPORTER.get() else {
        return;
    };
    let _ = catch_unwind(AssertUnwindSafe(|| reporter(event_code)));
}

fn rustduck_memory_callback(
    event_code: u32,
    plugin_name: &[u8],
    data: &[u8],
    data_max_size: usize,
    data_read_only: bool,
    validity: u8,
) -> ffi::RustDuckMemoryCallbackResult {
    let Some(dispatcher) = MEMORY_CALLBACK_DISPATCHER.get() else {
        return ffi::RustDuckMemoryCallbackResult {
            ok: false,
            data: Vec::new(),
        };
    };
    catch_unwind(AssertUnwindSafe(|| {
        dispatcher(
            event_code,
            plugin_name,
            data,
            data_max_size,
            data_read_only,
            validity,
        )
    }))
    .unwrap_or(ffi::RustDuckMemoryCallbackResult {
        ok: false,
        data: Vec::new(),
    })
}

fn rustduck_report_forward_callback(severity: i32, message: &[u8], message_valid: bool) {
    let Some(dispatcher) = REPORT_CALLBACK_DISPATCHER.get() else {
        return;
    };
    let _ = catch_unwind(AssertUnwindSafe(|| {
        dispatcher(severity, message, message_valid);
    }));
}

#[cxx::bridge]
pub mod ffi {
    struct RustDuckProcessorConfig {
        ignore_joint_termination: i64,
        buffer_size: i64,
        max_flushed_packets: i64,
        max_input_packets: i64,
        max_output_packets: i64,
        initial_input_packets: i64,
        add_input_stuffing_0: i64,
        add_input_stuffing_1: i64,
        add_start_stuffing: i64,
        add_stop_stuffing: i64,
        bitrate: i64,
        bitrate_adjust_interval: i64,
        receive_timeout: i64,
        log_plugin_index: bool,
        plugins: Vec<u8>,
    }

    struct RustDuckInputSwitcherConfig {
        fast_switch: bool,
        delayed_switch: bool,
        terminate: bool,
        reuse_port: bool,
        first_input: i64,
        primary_input: i64,
        cycle_count: i64,
        buffered_packets: i64,
        max_input_packets: i64,
        max_output_packets: i64,
        sock_buffer: i64,
        remote_server_port: i64,
        receive_timeout: i64,
        event_udp_port: i64,
        event_ttl: i64,
        plugins: Vec<u8>,
        event_command: Vec<u8>,
        event_udp_address: Vec<u8>,
        event_local_address: Vec<u8>,
    }

    struct RustDuckMemoryCallbackResult {
        ok: bool,
        data: Vec<u8>,
    }

    struct RustDuckAnalyzerSummary {
        packet_count: u64,
        ts_bitrate: f64,
        ts_pcr_bitrate_188: f64,
        invalid_sync_count: u64,
        transport_error_count: u64,
        pcr_pid_count: u64,
    }

    struct RustDuckAnalyzerCaDescriptor {
        cas_id: u16,
        ca_pid: u16,
        program_level: bool,
        has_elementary_pid: bool,
        elementary_pid: u16,
    }

    struct RustDuckAnalyzerService {
        service_id: u16,
        name: String,
        provider: String,
        pid_count: u64,
        pmt_pid: u16,
        pcr_pid: u16,
        bitrate: f64,
        packet_count: u64,
        scrambled_pid_count: u64,
        ca_descriptors: Vec<RustDuckAnalyzerCaDescriptor>,
    }

    struct RustDuckAnalyzerPid {
        pid: u16,
        services: Vec<u16>,
        carries_video: bool,
        carries_audio: bool,
        scrambled: bool,
        description: String,
        packet_count: u64,
        scrambled_packet_count: u64,
        invalid_pes_count: u64,
        invalid_pes_start_count: u64,
        bitrate: f64,
        ts_pcr_bitrate: f64,
        current_continuity: u8,
        unexpected_discontinuity_count: u64,
        duplicated_packet_count: u64,
        invalid_scrambling_control_count: u64,
        cas_id: u16,
        cas_operators: Vec<u32>,
        current_scrambling_control: u8,
    }

    struct RustDuckAnalyzerReport {
        summary: RustDuckAnalyzerSummary,
        services: Vec<RustDuckAnalyzerService>,
        pids: Vec<RustDuckAnalyzerPid>,
    }

    extern "Rust" {
        fn rustduck_memory_callback_writeback_failure(event_code: u32);
        fn rustduck_memory_callback(
            event_code: u32,
            plugin_name: &[u8],
            data: &[u8],
            data_max_size: usize,
            data_read_only: bool,
            validity: u8,
        ) -> RustDuckMemoryCallbackResult;
        fn rustduck_report_forward_callback(severity: i32, message: &[u8], message_valid: bool);
    }

    unsafe extern "C++" {
        include!("rustduck-sys/native/exception_boundary.h");
        include!("rustduck-sys/native/bridge/report.h");
        include!("rustduck-sys/native/bridge/context.h");
        include!("rustduck-sys/native/bridge/section_file.h");
        include!("rustduck-sys/native/bridge/memory_handler.h");
        include!("rustduck-sys/native/bridge/processor.h");
        include!("rustduck-sys/native/bridge/analyzer.h");
        include!("rustduck-sys/native/bridge/input_switcher.h");
        include!("rustduck-sys/native/bridge/system_monitor.h");
        include!("rustduck-sys/native/bridge/test_hooks.h");

        type RustDuckReport;
        type RustDuckDuckContext;
        type RustDuckSectionFile;
        type RustDuckMemoryHandler;
        type RustDuckTSProcessor;
        type RustDuckProcessorAbortToken;
        type RustDuckTSAnalyzer;
        type RustDuckInputSwitcher;
        type RustDuckSystemMonitor;

        fn rustduck_memory_handler_new() -> Result<UniquePtr<RustDuckMemoryHandler>>;
        fn rustduck_processor_new(
            report: &RustDuckReport,
        ) -> Result<UniquePtr<RustDuckTSProcessor>>;
        fn rustduck_processor_register_input(
            processor: Pin<&mut RustDuckTSProcessor>,
            handler: &RustDuckMemoryHandler,
        ) -> Result<()>;
        fn rustduck_processor_register_output(
            processor: Pin<&mut RustDuckTSProcessor>,
            handler: &RustDuckMemoryHandler,
        ) -> Result<()>;
        fn rustduck_processor_start(
            processor: Pin<&mut RustDuckTSProcessor>,
            config: &RustDuckProcessorConfig,
        ) -> Result<bool>;
        fn rustduck_processor_abort(processor: Pin<&mut RustDuckTSProcessor>) -> Result<()>;
        fn rustduck_processor_wait(processor: Pin<&mut RustDuckTSProcessor>) -> Result<()>;
        fn rustduck_processor_is_started(processor: &RustDuckTSProcessor) -> Result<bool>;
        fn rustduck_processor_abort_token(
            processor: &RustDuckTSProcessor,
        ) -> SharedPtr<RustDuckProcessorAbortToken>;
        fn rustduck_processor_abort_token_request(
            token: &RustDuckProcessorAbortToken,
        ) -> Result<()>;

        fn rustduck_analyzer_new(
            context: &RustDuckDuckContext,
        ) -> Result<UniquePtr<RustDuckTSAnalyzer>>;
        fn rustduck_analyzer_feed(
            analyzer: Pin<&mut RustDuckTSAnalyzer>,
            packets: &[u8],
        ) -> Result<()>;
        fn rustduck_analyzer_set_bitrate_hint(
            analyzer: Pin<&mut RustDuckTSAnalyzer>,
            bitrate: f64,
            confidence: u8,
        ) -> Result<()>;
        fn rustduck_analyzer_snapshot(
            analyzer: Pin<&mut RustDuckTSAnalyzer>,
        ) -> Result<RustDuckAnalyzerReport>;
        fn rustduck_analyzer_reset(analyzer: Pin<&mut RustDuckTSAnalyzer>) -> Result<()>;

        fn rustduck_input_switcher_new(
            report: &RustDuckReport,
        ) -> Result<UniquePtr<RustDuckInputSwitcher>>;
        fn rustduck_input_switcher_register_input(
            switcher: Pin<&mut RustDuckInputSwitcher>,
            handler: &RustDuckMemoryHandler,
        ) -> Result<()>;
        fn rustduck_input_switcher_register_output(
            switcher: Pin<&mut RustDuckInputSwitcher>,
            handler: &RustDuckMemoryHandler,
        ) -> Result<()>;
        fn rustduck_input_switcher_start(
            switcher: Pin<&mut RustDuckInputSwitcher>,
            config: &RustDuckInputSwitcherConfig,
        ) -> Result<bool>;
        fn rustduck_input_switcher_stop(switcher: Pin<&mut RustDuckInputSwitcher>) -> Result<()>;
        fn rustduck_input_switcher_wait(switcher: Pin<&mut RustDuckInputSwitcher>) -> Result<()>;

        fn rustduck_system_monitor_new(
            report: &RustDuckReport,
            config: &[u8],
        ) -> Result<UniquePtr<RustDuckSystemMonitor>>;
        fn rustduck_system_monitor_start(monitor: Pin<&mut RustDuckSystemMonitor>) -> Result<()>;
        fn rustduck_system_monitor_stop(monitor: Pin<&mut RustDuckSystemMonitor>) -> Result<()>;
        fn rustduck_system_monitor_wait(monitor: Pin<&mut RustDuckSystemMonitor>) -> Result<()>;

        fn rustduck_report_null() -> Result<UniquePtr<RustDuckReport>>;
        fn rustduck_report_stderr() -> Result<UniquePtr<RustDuckReport>>;
        fn rustduck_report_asynchronous(
            severity: i32,
            synchronous_log: bool,
            timed_log: bool,
            log_message_count: usize,
        ) -> Result<UniquePtr<RustDuckReport>>;
        fn rustduck_report_asynchronous_with_forwarder(
            severity: i32,
            synchronous_log: bool,
            log_message_count: usize,
        ) -> Result<UniquePtr<RustDuckReport>>;
        fn rustduck_report_set_max_severity(
            report: Pin<&mut RustDuckReport>,
            severity: i32,
        ) -> Result<()>;
        fn rustduck_report_log(
            report: &RustDuckReport,
            severity: i32,
            message: &[u8],
        ) -> Result<()>;
        fn rustduck_report_terminate(report: Pin<&mut RustDuckReport>) -> Result<()>;

        fn rustduck_context_new(report: &RustDuckReport) -> Result<UniquePtr<RustDuckDuckContext>>;
        fn rustduck_context_set_default_charset(
            context: Pin<&mut RustDuckDuckContext>,
            charset: &[u8],
        ) -> Result<bool>;
        fn rustduck_context_set_default_cas_id(
            context: Pin<&mut RustDuckDuckContext>,
            cas_id: u16,
        ) -> Result<()>;
        fn rustduck_context_set_default_pds(
            context: Pin<&mut RustDuckDuckContext>,
            pds: u32,
        ) -> Result<()>;
        fn rustduck_context_add_standards(
            context: Pin<&mut RustDuckDuckContext>,
            standards: u32,
        ) -> Result<()>;
        fn rustduck_context_standards(context: &RustDuckDuckContext) -> Result<u32>;
        fn rustduck_context_reset_standards(
            context: Pin<&mut RustDuckDuckContext>,
            standards: u32,
        ) -> Result<()>;
        fn rustduck_context_set_time_reference_offset(
            context: Pin<&mut RustDuckDuckContext>,
            offset_millis: i64,
        ) -> Result<()>;
        fn rustduck_context_set_time_reference(
            context: Pin<&mut RustDuckDuckContext>,
            name: &[u8],
        ) -> Result<bool>;

        fn rustduck_section_file_new(
            context: &RustDuckDuckContext,
        ) -> Result<UniquePtr<RustDuckSectionFile>>;
        fn rustduck_section_file_clear(section_file: Pin<&mut RustDuckSectionFile>) -> Result<()>;
        fn rustduck_section_file_binary_size(section_file: &RustDuckSectionFile) -> Result<usize>;
        fn rustduck_section_file_sections_count(
            section_file: &RustDuckSectionFile,
        ) -> Result<usize>;
        fn rustduck_section_file_tables_count(section_file: &RustDuckSectionFile) -> Result<usize>;
        fn rustduck_section_file_set_crc_validation(
            section_file: Pin<&mut RustDuckSectionFile>,
            mode: i32,
        ) -> Result<()>;
        fn rustduck_section_file_load_binary_buffer(
            section_file: Pin<&mut RustDuckSectionFile>,
            data: &[u8],
        ) -> Result<bool>;
        fn rustduck_section_file_to_binary(section_file: &RustDuckSectionFile) -> Result<Vec<u8>>;
        fn rustduck_section_file_load_binary(
            section_file: Pin<&mut RustDuckSectionFile>,
            path: &[u8],
        ) -> Result<bool>;
        fn rustduck_section_file_save_binary(
            section_file: &RustDuckSectionFile,
            path: &[u8],
        ) -> Result<bool>;
        fn rustduck_section_file_load_xml(
            section_file: Pin<&mut RustDuckSectionFile>,
            source: &[u8],
        ) -> Result<bool>;
        fn rustduck_section_file_save_xml(
            section_file: &RustDuckSectionFile,
            path: &[u8],
        ) -> Result<bool>;
        fn rustduck_section_file_save_json(
            section_file: &RustDuckSectionFile,
            path: &[u8],
        ) -> Result<bool>;
        fn rustduck_section_file_to_xml_utf16(
            section_file: &RustDuckSectionFile,
        ) -> Result<Vec<u8>>;
        fn rustduck_section_file_to_json_utf16(
            section_file: &RustDuckSectionFile,
        ) -> Result<Vec<u8>>;

        // Fault-injection seams for this workspace's native tests. The
        // `native_test_hooks` feature both declares these symbols and defines the
        // matching native macro, so default builds expose no test surface.
        #[cfg(feature = "native_test_hooks")]
        #[doc(hidden)]
        fn rustduck_test_set_failure(point: i32, trigger_after: i32, unknown: bool) -> Result<()>;
        #[cfg(feature = "native_test_hooks")]
        #[doc(hidden)]
        fn rustduck_test_clear_failure() -> Result<()>;
        #[cfg(feature = "native_test_hooks")]
        #[doc(hidden)]
        fn rustduck_test_throw_standard() -> Result<()>;
        #[cfg(feature = "native_test_hooks")]
        #[doc(hidden)]
        fn rustduck_test_throw_unknown() -> Result<()>;
    }
}