Skip to main content

libobs_wrapper\data\output/
stats.rs

1//! Output health snapshots and restart-aware bitrate sampling.
2
3use std::{
4    ffi::CStr,
5    time::{Duration, Instant},
6};
7
8use crate::{run_with_obs, utils::ObsError};
9
10use super::ObsOutputTrait;
11
12/// A native metric whose support may be optional for an output plugin.
13#[derive(Clone, Debug, PartialEq)]
14pub enum OutputMetric<T> {
15    /// The metric is semantically unavailable for this output category.
16    Unavailable,
17    /// A non-sentinel value proves that the plugin is reporting the metric.
18    Available(T),
19    /// libobs returned the metric's zero/sentinel value but its public API does not expose whether
20    /// the optional plugin callback exists. This is intentionally not presented as a known zero.
21    Indeterminate(T),
22}
23
24impl<T> OutputMetric<T> {
25    pub fn value(&self) -> Option<&T> {
26        match self {
27            Self::Available(value) | Self::Indeterminate(value) => Some(value),
28            Self::Unavailable => None,
29        }
30    }
31}
32
33/// Point-in-time output health. Dropped frames are network-congestion drops, not rendering or
34/// encoding lag.
35#[derive(Clone, Debug, PartialEq)]
36pub struct OutputStatusSnapshot {
37    pub active: bool,
38    pub paused: bool,
39    pub reconnecting: bool,
40    pub total_bytes: OutputMetric<u64>,
41    pub dropped_network_frames: OutputMetric<u64>,
42    pub total_output_frames: u64,
43    pub last_error: Option<String>,
44}
45
46/// Additive statistics API for any managed OBS output.
47pub trait ObsOutputStatisticsExt: ObsOutputTrait {
48    fn status_snapshot(&self) -> Result<OutputStatusSnapshot, ObsError> {
49        let output = self.__native_handle();
50        let runtime = self.runtime().clone();
51        let flags = self.native_output_flags()?;
52        let service_output = flags & libobs::OBS_OUTPUT_SERVICE != 0;
53
54        run_with_obs!(runtime, (output), move || unsafe {
55            // Safety: output is retained by its managed handle for the actor call.
56            let active = libobs::obs_output_active(output.get_ptr());
57            let paused = libobs::obs_output_paused(output.get_ptr());
58            let reconnecting = libobs::obs_output_reconnecting(output.get_ptr());
59            let bytes = libobs::obs_output_get_total_bytes(output.get_ptr());
60            let dropped = libobs::obs_output_get_frames_dropped(output.get_ptr()).max(0) as u64;
61            let total_frames = libobs::obs_output_get_total_frames(output.get_ptr()).max(0) as u64;
62            let error_ptr = libobs::obs_output_get_last_error(output.get_ptr());
63            let last_error = if error_ptr.is_null() {
64                None
65            } else {
66                let value = CStr::from_ptr(error_ptr).to_string_lossy().into_owned();
67                (!value.is_empty()).then_some(value)
68            };
69
70            let total_bytes = if bytes == 0 {
71                OutputMetric::Indeterminate(0)
72            } else {
73                OutputMetric::Available(bytes)
74            };
75            let dropped_network_frames = if !service_output {
76                OutputMetric::Unavailable
77            } else if dropped == 0 {
78                OutputMetric::Indeterminate(0)
79            } else {
80                OutputMetric::Available(dropped)
81            };
82
83            OutputStatusSnapshot {
84                active,
85                paused,
86                reconnecting,
87                total_bytes,
88                dropped_network_frames,
89                total_output_frames: total_frames,
90                last_error,
91            }
92        })
93    }
94}
95
96impl<T: ObsOutputTrait + ?Sized> ObsOutputStatisticsExt for T {}
97
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub enum BitrateSampleState {
100    FirstSample,
101    Rate,
102    CounterReset,
103    Unavailable,
104    TooSoon,
105}
106
107#[derive(Clone, Debug, PartialEq)]
108pub struct BitrateSample {
109    pub state: BitrateSampleState,
110    pub bits_per_second: Option<f64>,
111    pub elapsed: Option<Duration>,
112}
113
114/// Stateful byte-counter sampler. Reuse one sampler for one output lifecycle.
115#[derive(Debug, Default)]
116pub struct OutputBitrateSampler {
117    previous: Option<(Instant, u64)>,
118}
119
120impl OutputBitrateSampler {
121    pub fn new() -> Self {
122        Self::default()
123    }
124
125    pub fn reset(&mut self) {
126        self.previous = None;
127    }
128
129    pub fn sample<T: ObsOutputStatisticsExt + ?Sized>(
130        &mut self,
131        output: &T,
132    ) -> Result<BitrateSample, ObsError> {
133        let snapshot = output.status_snapshot()?;
134        self.sample_counter(Instant::now(), snapshot.total_bytes)
135    }
136
137    fn sample_counter(
138        &mut self,
139        now: Instant,
140        bytes: OutputMetric<u64>,
141    ) -> Result<BitrateSample, ObsError> {
142        let bytes = match bytes {
143            OutputMetric::Unavailable => {
144                self.previous = None;
145                return Ok(BitrateSample {
146                    state: BitrateSampleState::Unavailable,
147                    bits_per_second: None,
148                    elapsed: None,
149                });
150            }
151            OutputMetric::Available(bytes) | OutputMetric::Indeterminate(bytes) => bytes,
152        };
153
154        let Some((previous_time, previous_bytes)) = self.previous.replace((now, bytes)) else {
155            return Ok(BitrateSample {
156                state: BitrateSampleState::FirstSample,
157                bits_per_second: None,
158                elapsed: None,
159            });
160        };
161
162        let elapsed = now.saturating_duration_since(previous_time);
163        if elapsed.is_zero() {
164            return Ok(BitrateSample {
165                state: BitrateSampleState::TooSoon,
166                bits_per_second: None,
167                elapsed: Some(elapsed),
168            });
169        }
170        if bytes < previous_bytes {
171            return Ok(BitrateSample {
172                state: BitrateSampleState::CounterReset,
173                bits_per_second: None,
174                elapsed: Some(elapsed),
175            });
176        }
177
178        let delta_bytes = bytes - previous_bytes;
179        Ok(BitrateSample {
180            state: BitrateSampleState::Rate,
181            bits_per_second: Some(delta_bytes as f64 * 8.0 / elapsed.as_secs_f64()),
182            elapsed: Some(elapsed),
183        })
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn bitrate_sampler_handles_first_rate_and_counter_reset() {
193        let mut sampler = OutputBitrateSampler::new();
194        let base = Instant::now();
195        assert_eq!(
196            sampler
197                .sample_counter(base, OutputMetric::Available(1_000))
198                .unwrap()
199                .state,
200            BitrateSampleState::FirstSample
201        );
202        let rate = sampler
203            .sample_counter(
204                base + Duration::from_secs(2),
205                OutputMetric::Available(3_000),
206            )
207            .unwrap();
208        assert_eq!(rate.state, BitrateSampleState::Rate);
209        assert_eq!(rate.bits_per_second, Some(8_000.0));
210
211        let reset = sampler
212            .sample_counter(
213                base + Duration::from_secs(3),
214                OutputMetric::Indeterminate(0),
215            )
216            .unwrap();
217        assert_eq!(reset.state, BitrateSampleState::CounterReset);
218        assert_eq!(reset.bits_per_second, None);
219    }
220
221    #[test]
222    fn unavailable_metric_clears_sampler_generation() {
223        let mut sampler = OutputBitrateSampler::new();
224        let base = Instant::now();
225        sampler
226            .sample_counter(base, OutputMetric::Available(10))
227            .unwrap();
228        assert_eq!(
229            sampler
230                .sample_counter(base + Duration::from_secs(1), OutputMetric::Unavailable)
231                .unwrap()
232                .state,
233            BitrateSampleState::Unavailable
234        );
235        assert_eq!(
236            sampler
237                .sample_counter(base + Duration::from_secs(2), OutputMetric::Available(20))
238                .unwrap()
239                .state,
240            BitrateSampleState::FirstSample
241        );
242    }
243}