gstreamer 0.24.4

Rust bindings for GStreamer
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{fmt, io::Write, ptr};

use glib::{prelude::*, translate::*};

use crate::log::DebugLogger;
use crate::{ffi, ClockTime, DebugCategory, DebugLevel, LogContextFlags, LogContextHashFlags};

#[derive(Debug)]
#[doc(alias = "GstLogContext")]
#[repr(transparent)]
pub struct LogContext(ptr::NonNull<ffi::GstLogContext>);

impl LogContext {
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_log_context_get_category")]
    #[doc(alias = "get_category")]
    #[inline]
    pub fn category(&self) -> DebugCategory {
        unsafe { from_glib_none(ffi::gst_log_context_get_category(self.0.as_ptr())) }
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_log_context_reset")]
    #[inline]
    pub fn reset(&self) {
        unsafe {
            ffi::gst_log_context_reset(self.0.as_ptr());
        }
    }

    #[inline]
    pub fn as_ptr(&self) -> *mut ffi::GstLogContext {
        self.0.as_ptr()
    }

    // rustdoc-stripper-ignore-next
    /// Logs without checking the log level.
    #[inline(never)]
    fn log_unfiltered_internal(
        &self,
        obj: Option<&glib::Object>,
        level: DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        args: fmt::Arguments,
    ) {
        let mut w = smallvec::SmallVec::<[u8; 256]>::new();

        // Can't really happen but better safe than sorry
        if Write::write_fmt(&mut w, args).is_err() {
            return;
        }
        w.push(0);

        self.log_literal_unfiltered_internal(obj, level, file, function, line, unsafe {
            glib::GStr::from_utf8_with_nul_unchecked(&w)
        });
    }

    #[inline(never)]
    fn log_literal_unfiltered_internal(
        &self,
        obj: Option<&glib::Object>,
        level: DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        msg: &glib::GStr,
    ) {
        let obj_ptr = match obj {
            Some(obj) => obj.as_ptr(),
            None => ptr::null_mut(),
        };

        function.run_with_gstr(|function| unsafe {
            ffi::gst_debug_log_literal_with_context(
                self.0.as_ptr(),
                level.into_glib(),
                file.as_ptr(),
                function.as_ptr(),
                line as i32,
                obj_ptr,
                msg.as_ptr(),
            );
        });
    }

    #[inline(never)]
    fn log_id_unfiltered_internal(
        &self,
        id: &glib::GStr,
        level: DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        args: fmt::Arguments,
    ) {
        let mut w = smallvec::SmallVec::<[u8; 256]>::new();

        // Can't really happen but better safe than sorry
        if Write::write_fmt(&mut w, args).is_err() {
            return;
        }
        w.push(0);

        self.log_id_literal_unfiltered_internal(id, level, file, function, line, unsafe {
            glib::GStr::from_utf8_with_nul_unchecked(&w)
        });
    }

    #[inline(never)]
    fn log_id_literal_unfiltered_internal(
        &self,
        id: &glib::GStr,
        level: DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        msg: &glib::GStr,
    ) {
        function.run_with_gstr(|function| unsafe {
            ffi::gst_debug_log_id_literal_with_context(
                self.0.as_ptr(),
                level.into_glib(),
                file.as_ptr(),
                function.as_ptr(),
                line as i32,
                id.as_ptr(),
                msg.as_ptr(),
            );
        });
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_debug_log_with_context")]
    pub fn log(
        &self,
        obj: Option<&impl IsA<glib::Object>>,
        level: DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        args: fmt::Arguments,
    ) {
        if !self.above_threshold(level) {
            return;
        }

        self.log_unfiltered_internal(
            obj.map(|obj| obj.as_ref()),
            level,
            file,
            function,
            line,
            args,
        )
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_debug_log_literal_with_context")]
    pub fn log_literal(
        &self,
        obj: Option<&impl IsA<glib::Object>>,
        level: DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        msg: &glib::GStr,
    ) {
        if !self.above_threshold(level) {
            return;
        }

        self.log_literal_unfiltered_internal(
            obj.map(|obj| obj.as_ref()),
            level,
            file,
            function,
            line,
            msg,
        )
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_debug_log_id_with_context")]
    pub fn log_id(
        &self,
        id: impl AsRef<glib::GStr>,
        level: DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        args: fmt::Arguments,
    ) {
        if !self.above_threshold(level) {
            return;
        }

        self.log_id_unfiltered_internal(id.as_ref(), level, file, function, line, args);
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_debug_log_id_literal_with_context")]
    pub fn log_id_literal(
        &self,
        id: impl AsRef<glib::GStr>,
        level: DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        msg: &glib::GStr,
    ) {
        if !self.above_threshold(level) {
            return;
        }

        self.log_id_literal_unfiltered_internal(id.as_ref(), level, file, function, line, msg);
    }
}

impl Drop for LogContext {
    fn drop(&mut self) {
        unsafe {
            ffi::gst_log_context_free(self.0.as_ptr());
        }
    }
}

unsafe impl Send for LogContext {}
unsafe impl Sync for LogContext {}

impl crate::log::DebugLogger for LogContext {
    #[inline]
    fn above_threshold(&self, level: crate::DebugLevel) -> bool {
        self.category().above_threshold(level)
    }

    #[inline]
    fn log_unfiltered(
        &self,
        obj: Option<&impl IsA<glib::Object>>,
        level: crate::DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        args: std::fmt::Arguments,
    ) {
        self.log_unfiltered_internal(
            obj.map(|obj| obj.as_ref()),
            level,
            file,
            function,
            line,
            args,
        )
    }

    #[inline]
    fn log_literal_unfiltered(
        &self,
        obj: Option<&impl IsA<glib::Object>>,
        level: crate::DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        msg: &glib::GStr,
    ) {
        self.log_literal_unfiltered_internal(
            obj.map(|obj| obj.as_ref()),
            level,
            file,
            function,
            line,
            msg,
        )
    }

    #[inline]
    fn log_id_unfiltered(
        &self,
        id: impl AsRef<glib::GStr>,
        level: crate::DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        args: std::fmt::Arguments,
    ) {
        self.log_id_unfiltered_internal(id.as_ref(), level, file, function, line, args)
    }

    // rustdoc-stripper-ignore-next
    /// Logs without checking the log level.
    #[inline]
    fn log_id_literal_unfiltered(
        &self,
        id: impl AsRef<glib::GStr>,
        level: crate::DebugLevel,
        file: &glib::GStr,
        function: &str,
        line: u32,
        msg: &glib::GStr,
    ) {
        self.log_id_literal_unfiltered_internal(id.as_ref(), level, file, function, line, msg)
    }
}

#[derive(Debug)]
#[doc(alias = "GstLogContextBuilder")]
#[repr(transparent)]
pub struct LogContextBuilder(ptr::NonNull<ffi::GstLogContextBuilder>);

impl LogContextBuilder {
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_log_context_builder_new")]
    pub fn new(category: DebugCategory, flags: LogContextFlags) -> Self {
        skip_assert_initialized!();
        unsafe {
            let ptr = ffi::gst_log_context_builder_new(category.as_ptr(), flags.into_glib());
            LogContextBuilder(ptr::NonNull::new_unchecked(ptr))
        }
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_log_context_builder_set_hash_flags")]
    pub fn hash_flags(self, flags: LogContextHashFlags) -> Self {
        unsafe {
            ffi::gst_log_context_builder_set_hash_flags(self.0.as_ptr(), flags.into_glib());
        }
        self
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_log_context_builder_set_category")]
    pub fn category(self, category: DebugCategory) -> Self {
        unsafe {
            ffi::gst_log_context_builder_set_category(self.0.as_ptr(), category.as_ptr());
        }
        self
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_log_context_builder_set_interval")]
    pub fn interval(self, interval: impl Into<Option<ClockTime>>) -> Self {
        unsafe {
            ffi::gst_log_context_builder_set_interval(self.0.as_ptr(), interval.into().into_glib());
        }
        self
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "v1_28")))]
    #[doc(alias = "gst_log_context_builder_build")]
    pub fn build(self) -> LogContext {
        unsafe {
            let ptr = ffi::gst_log_context_builder_build(self.0.as_ptr());
            LogContext(ptr::NonNull::new_unchecked(ptr))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{log::DebugLogger, DebugLevel, LogContextFlags, LogContextHashFlags};

    #[test]
    fn log_context_builder_basic() {
        crate::init().unwrap();

        let cat = crate::DebugCategory::new(
            "test-log-context",
            crate::DebugColorFlags::empty(),
            Some("Test log context category"),
        );

        // Test basic builder pattern
        let context = LogContextBuilder::new(cat, LogContextFlags::empty()).build();

        assert_eq!(context.category(), cat);
    }

    #[test]
    fn log_context_builder_with_flags() {
        crate::init().unwrap();

        let cat = crate::DebugCategory::new(
            "test-log-context-flags",
            crate::DebugColorFlags::empty(),
            Some("Test log context with flags"),
        );

        // Test builder with various configuration options
        let context = LogContextBuilder::new(cat, LogContextFlags::THROTTLE)
            .hash_flags(LogContextHashFlags::USE_LINE_NUMBER)
            .interval(Some(crate::ClockTime::from_seconds(1)))
            .build();

        assert_eq!(context.category(), cat);
    }

    #[test]
    fn log_context_trait_implementation() {
        crate::init().unwrap();

        let cat = crate::DebugCategory::new(
            "test-trait-impl",
            crate::DebugColorFlags::empty(),
            Some("Test trait implementation"),
        );

        let context = LogContextBuilder::new(cat, LogContextFlags::empty()).build();

        // Test that LogContext implements DebugLogger trait
        assert_eq!(
            context.above_threshold(DebugLevel::Error),
            cat.above_threshold(DebugLevel::Error)
        );
        assert_eq!(
            context.above_threshold(DebugLevel::Debug),
            cat.above_threshold(DebugLevel::Debug)
        );
    }

    #[test]
    fn log_context_with_macros() {
        crate::init().unwrap();

        let cat = crate::DebugCategory::new(
            "test-macro-usage",
            crate::DebugColorFlags::empty(),
            Some("Test macro usage"),
        );
        cat.set_threshold(DebugLevel::Trace);

        let context = LogContextBuilder::new(cat, LogContextFlags::empty()).build();

        // Test that LogContext works with all the logging macros
        crate::error!(context, "error message");
        crate::error!(&context, "error message");
        crate::warning!(context, "warning message");
        crate::warning!(&context, "warning message");
        crate::info!(context, "info message");
        crate::info!(&context, "info message");
        crate::debug!(context, "debug message");
        crate::debug!(&context, "debug message");
        crate::trace!(context, "trace message");
        crate::trace!(&context, "trace message");

        // Test with object
        let obj = crate::Bin::with_name("test-bin");
        crate::error!(context, obj = &obj, "error with object");
        crate::warning!(context, obj = &obj, "warning with object");

        // Test with formatting
        let value = 42;
        crate::info!(context, "formatted message: {}", value);
        crate::debug!(context, obj = &obj, "formatted with obj: {}", value);
    }

    #[test]
    fn log_context_interchangeable_with_category() {
        crate::init().unwrap();

        let cat = crate::DebugCategory::new(
            "test-interchangeable",
            crate::DebugColorFlags::empty(),
            Some("Test interchangeable usage"),
        );
        cat.set_threshold(DebugLevel::Info);

        let context = LogContextBuilder::new(cat, LogContextFlags::empty()).build();

        // Test that we can use both category and context in the same way
        let test_message = "test message";

        // These should both work identically
        crate::info!(cat, "{}", test_message);
        crate::info!(&cat, "{}", test_message);
        crate::info!(context, "{}", test_message);
        crate::info!(&context, "{}", test_message);

        // With objects too
        let obj = crate::Bin::with_name("test-bin-2");
        crate::info!(cat, obj = &obj, "{}", test_message);
        crate::info!(context, obj = &obj, "{}", test_message);
    }

    #[test]
    fn static_log_context() {
        crate::init().unwrap();

        // Create a static category first
        static TEST_CATEGORY: std::sync::LazyLock<crate::DebugCategory> =
            std::sync::LazyLock::new(|| {
                crate::DebugCategory::new(
                    "test-static-context",
                    crate::DebugColorFlags::empty(),
                    Some("Test static context"),
                )
            });

        // Create static context directly with LazyLock
        static TEST_CONTEXT: std::sync::LazyLock<LogContext> = std::sync::LazyLock::new(|| {
            LogContextBuilder::new(*TEST_CATEGORY, LogContextFlags::empty()).build()
        });

        // Use the static context
        crate::info!(TEST_CONTEXT, "message from static context");

        assert_eq!(TEST_CONTEXT.category(), *TEST_CATEGORY);
    }

    #[test]
    fn static_log_context_with_advanced_options() {
        crate::init().unwrap();

        // Create a static category first
        static ADVANCED_CATEGORY: std::sync::LazyLock<crate::DebugCategory> =
            std::sync::LazyLock::new(|| {
                crate::DebugCategory::new(
                    "test-static-advanced",
                    crate::DebugColorFlags::empty(),
                    Some("Test static context advanced"),
                )
            });

        // Create static context with advanced options using LazyLock
        static ADVANCED_CONTEXT: std::sync::LazyLock<LogContext> = std::sync::LazyLock::new(|| {
            LogContextBuilder::new(*ADVANCED_CATEGORY, LogContextFlags::THROTTLE)
                .hash_flags(LogContextHashFlags::USE_LINE_NUMBER)
                .interval(Some(crate::ClockTime::from_seconds(2)))
                .build()
        });

        crate::debug!(ADVANCED_CONTEXT, "advanced static context message");
        assert_eq!(ADVANCED_CONTEXT.category(), *ADVANCED_CATEGORY);
    }

    #[test]
    fn log_context_with_id_logging() {
        crate::init().unwrap();

        let cat = crate::DebugCategory::new(
            "test-id-logging",
            crate::DebugColorFlags::empty(),
            Some("Test ID logging"),
        );
        cat.set_threshold(DebugLevel::Trace);

        let context = LogContextBuilder::new(cat, LogContextFlags::empty()).build();

        // Test ID-based logging with LogContext
        crate::trace!(context, id = "test-id-123", "message with ID");
        crate::debug!(
            context,
            id = "test-id-456",
            "another message with ID: {}",
            42
        );
    }

    #[test]
    fn log_context_memory_safety() {
        crate::init().unwrap();

        let cat = crate::DebugCategory::new(
            "test-memory-safety",
            crate::DebugColorFlags::empty(),
            Some("Test memory safety"),
        );

        // Test that LogContext can be safely dropped
        {
            let context = LogContextBuilder::new(cat, LogContextFlags::empty()).build();
            crate::info!(context, "message before drop");
        } // context is dropped here

        // Create another context to ensure no memory issues
        let context2 = LogContextBuilder::new(cat, LogContextFlags::THROTTLE).build();
        crate::info!(context2, "message from second context");
    }

    #[test]
    fn log_context_category_consistency() {
        crate::init().unwrap();

        let cat1 = crate::DebugCategory::new(
            "test-consistency-1",
            crate::DebugColorFlags::empty(),
            Some("Test consistency 1"),
        );

        let cat2 = crate::DebugCategory::new(
            "test-consistency-2",
            crate::DebugColorFlags::empty(),
            Some("Test consistency 2"),
        );

        let context1 = LogContextBuilder::new(cat1, LogContextFlags::empty()).build();
        let context2 = LogContextBuilder::new(cat2, LogContextFlags::empty()).build();

        // Verify that contexts maintain their respective categories
        assert_eq!(context1.category(), cat1);
        assert_eq!(context2.category(), cat2);
        assert_ne!(context1.category(), cat2);
        assert_ne!(context2.category(), cat1);
    }

    #[test]
    fn log_context_threshold_behavior() {
        crate::init().unwrap();

        let cat = crate::DebugCategory::new(
            "test-threshold",
            crate::DebugColorFlags::empty(),
            Some("Test threshold behavior"),
        );

        let context = LogContextBuilder::new(cat, LogContextFlags::empty()).build();

        // Test threshold behavior matches between category and context
        cat.set_threshold(DebugLevel::Warning);

        assert!(context.above_threshold(DebugLevel::Error));
        assert!(context.above_threshold(DebugLevel::Warning));
        assert!(!context.above_threshold(DebugLevel::Info));
        assert!(!context.above_threshold(DebugLevel::Debug));

        // Same as category
        assert_eq!(
            context.above_threshold(DebugLevel::Error),
            cat.above_threshold(DebugLevel::Error)
        );
        assert_eq!(
            context.above_threshold(DebugLevel::Warning),
            cat.above_threshold(DebugLevel::Warning)
        );
        assert_eq!(
            context.above_threshold(DebugLevel::Info),
            cat.above_threshold(DebugLevel::Info)
        );
        assert_eq!(
            context.above_threshold(DebugLevel::Debug),
            cat.above_threshold(DebugLevel::Debug)
        );
    }
}