wayclip-core 0.1.2

Core module for the Wayclip ecosystem: models, settings, and methods for App
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
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
use crate::models::error::WayclipError;
use serde::{Deserialize, Serialize};
use std::{
    fmt::{Display, Formatter},
    str::FromStr,
};

const DEFAULT_LENGTH_SECONDS: u64 = 120;
const DEFAULT_RESOLUTION: (u64, u64) = (1920, 1080);
const DEFAULT_VIDEO_CODEC: VideoCodec = VideoCodec::H264(CodecType::NVIDIA);
const DEFAULT_FPS: u64 = 30;
const DEFAULT_BITRATE_KBPS: u64 = 15000;
const DEFAULT_AUDIO_CODEC: AudioCodec = AudioCodec::Opus;
const DEFAULT_MICROPHONE_LEVEL: f64 = 0.75;
const DEFAULT_BACKGROUND_LEVEL: f64 = 0.50;
const DEFAULT_MICROPHONE_ENABLED: bool = true;
const DEFAULT_BACKGROUND_ENABLED: bool = true;
const DEFAULT_AUDIO_SAMPLE_RATE: u64 = 48000;
const MIN_RESOLUTION_WIDTH: u64 = 1;
const MAX_RESOLUTION_WIDTH: u64 = 7680;
const MIN_RESOLUTION_HEIGHT: u64 = 1;
const MAX_RESOLUTION_HEIGHT: u64 = 4320;
const MIN_BITRATE_KBPS: u64 = 300;
const MAX_BITRATE_KBPS: u64 = 10000000;
const MIN_AUDIO_LEVEL: f64 = 0.0;
const MAX_AUDIO_LEVEL: f64 = 1.0;
const MIN_FPS: u64 = 1;
const MAX_FPS: u64 = 1000;
const ALLOWED_AUDIO_SAMPLE_RATES_HZ: &[u64] = &[8000, 16000, 22050, 32000, 44100, 48000, 96000];

/// The recording settings for audio & video
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RecordingSettings {
    /// Video settings
    pub video: VideoSettings,
    /// Audio settings
    pub audio: AudioSettings,
}

/// Video settings that daemon will follow
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoSettings {
    /// Length of clip at which ring buffer will loop
    pub length_seconds: u64,
    /// Resolution at which to record
    pub resolution: Resolution,
    /// Fps at which to record
    pub fps: Fps,
    /// The video codec to use
    pub codec: VideoCodec,
    /// The bitrate at which its recorded
    pub bitrate_kbps: Bitrate,
}

impl Default for VideoSettings {
    fn default() -> Self {
        Self {
            length_seconds: DEFAULT_LENGTH_SECONDS,
            resolution: Resolution::default(),
            fps: Fps::default(),
            codec: DEFAULT_VIDEO_CODEC,
            bitrate_kbps: Bitrate::default(),
        }
    }
}

/// Wrapper for FPS
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Fps(pub u64);

impl Default for Fps {
    fn default() -> Self {
        Self(DEFAULT_FPS)
    }
}

impl FromStr for Fps {
    type Err = WayclipError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let fps: u64 = s.parse()?;
        if !(MIN_FPS..=MAX_FPS).contains(&fps) {
            return Err(WayclipError::Validation(
                format!(
                    "Fps must be within the range {} to {} FPS",
                    MIN_FPS, MAX_FPS
                )
                .into(),
            ));
        }

        Ok(Self(fps))
    }
}

impl Display for Fps {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}fps", self.0)
    }
}

/// Wrapper for resolution
#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Resolution {
    pub width: u64,
    pub height: u64,
}

impl Resolution {
    /// Method to form struct from any unsgined integer tuple
    pub fn from_tuple<U>(tuple: (U, U)) -> Self
    where
        U: Into<u64>,
    {
        Self {
            width: tuple.0.into(),
            height: tuple.1.into(),
        }
    }

    /// Format the struct to a tuple
    pub fn to_tuple(&self) -> (u64, u64) {
        (self.width, self.height)
    }
}

impl Default for Resolution {
    fn default() -> Self {
        Self {
            width: DEFAULT_RESOLUTION.0,
            height: DEFAULT_RESOLUTION.1,
        }
    }
}

impl FromStr for Resolution {
    type Err = WayclipError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split('x').collect();
        if parts.len() != 2 {
            return Err(WayclipError::Validation(
                "Resolution must be in 'WIDTHxHEIGHT' format (e.g. 1920x1080)".into(),
            ));
        }

        let width = parts[0]
            .parse()
            .map_err(|_| WayclipError::Validation("Invalid resolution width".into()))?;
        let height = parts[1]
            .parse()
            .map_err(|_| WayclipError::Validation("Invalid resolution height".into()))?;

        if width < MIN_RESOLUTION_WIDTH
            || height < MIN_RESOLUTION_HEIGHT
            || width > MAX_RESOLUTION_WIDTH
            || height > MAX_RESOLUTION_HEIGHT
        {
            return Err(WayclipError::Validation(
                format!(
                    "Resolution must be within the range {}x{} and {}x{} pixels",
                    MIN_RESOLUTION_WIDTH,
                    MIN_RESOLUTION_HEIGHT,
                    MAX_RESOLUTION_WIDTH,
                    MAX_RESOLUTION_HEIGHT
                )
                .into(),
            ));
        }

        Ok(Self { width, height })
    }
}

impl Display for Resolution {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}x{}", self.width, self.height)
    }
}

/// Wrapper around bitrate
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Bitrate(pub u64);

impl Default for Bitrate {
    fn default() -> Self {
        Self(DEFAULT_BITRATE_KBPS)
    }
}

impl FromStr for Bitrate {
    type Err = WayclipError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let kbps: u64 = s.parse()?;

        if !(MIN_BITRATE_KBPS..=MAX_BITRATE_KBPS).contains(&kbps) {
            return Err(WayclipError::Validation(
                format!(
                    "Bitrate value must be within the range {} to {} kbps",
                    MIN_BITRATE_KBPS, MAX_BITRATE_KBPS
                )
                .into(),
            ));
        }

        Ok(Self(kbps))
    }
}

impl Display for Bitrate {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}kbps", self.0)
    }
}

/// The video codec type that is used
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum CodecType {
    /// Requires proprietary drivers and some gstreamer package
    /// <https://gstreamer.freedesktop.org/documentation/nvcodec/index.html>
    NVIDIA,
    /// Requires libva and supported driver
    VAAPI,
    /// One of the gstreamer-packages has it
    Software,
}

impl std::fmt::Display for CodecType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CodecType::NVIDIA => write!(f, "nvidia"),
            CodecType::Software => write!(f, "software"),
            CodecType::VAAPI => write!(f, "vaapi"),
        }
    }
}

impl FromStr for CodecType {
    type Err = WayclipError;
    fn from_str(s: &str) -> Result<Self, WayclipError> {
        match s.to_lowercase().as_str() {
            "nvidia" | "nv" => Ok(CodecType::NVIDIA),
            "vaapi" => Ok(CodecType::VAAPI),
            "software" | "sw" => Ok(CodecType::Software),
            _ => Err(WayclipError::Validation("Invalid codec type".into())),
        }
    }
}

/// The video codec to be used
/// Each codec also contains a codec type (NV/VAAPI/Software)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum VideoCodec {
    /// h264 (best)
    H264(CodecType),
    /// h265
    H265(CodecType),
    /// av1
    AV1(CodecType),
}

impl FromStr for VideoCodec {
    type Err = WayclipError;
    fn from_str(s: &str) -> Result<Self, WayclipError> {
        let (codec_name, codec_ty) = s
            .split_once(':')
            .ok_or_else(|| WayclipError::Validation("Expected format is <codec>:<type>".into()))?;
        let codec_type = codec_ty.parse()?;
        match codec_name.to_lowercase().as_str() {
            "h264" => Ok(VideoCodec::H264(codec_type)),
            "h265" => Ok(VideoCodec::H265(codec_type)),
            "av1" => Ok(VideoCodec::AV1(codec_type)),
            _ => Err(WayclipError::Validation("Invalid codec name".into())),
        }
    }
}

impl std::fmt::Display for VideoCodec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VideoCodec::AV1(codec_type) => {
                write!(f, "av1:{codec_type}")
            }
            VideoCodec::H265(codec_type) => {
                write!(f, "h265:{codec_type}")
            }
            VideoCodec::H264(codec_type) => {
                write!(f, "h264:{codec_type}")
            }
        }
    }
}

impl VideoCodec {
    /// Get the gstreamer parser element
    pub fn get_parser(&self) -> &str {
        match self {
            VideoCodec::H264(_) => "h264parse",
            VideoCodec::H265(_) => "h265parse",
            VideoCodec::AV1(_) => "av1parse",
        }
    }

    /// Get the inner codec (backend) type
    pub fn get_backend(&self) -> &CodecType {
        match self {
            VideoCodec::H264(t) | VideoCodec::H265(t) | VideoCodec::AV1(t) => t,
        }
    }

    /// Get the gstreamer encoder element
    pub fn get_encoder(&self) -> &str {
        match self {
            // https://gstreamer.freedesktop.org/documentation/nvcodec/nvh264enc.html?gi-language=rust
            VideoCodec::H264(CodecType::NVIDIA) => "nvh264enc",
            // https://gstreamer.freedesktop.org/documentation/nvcodec/nvh265enc.html?gi-language=rust
            VideoCodec::H265(CodecType::NVIDIA) => "nvh265enc",
            // https://gstreamer.freedesktop.org/documentation/nvcodec/nvav1enc.html?gi-language=rust
            VideoCodec::AV1(CodecType::NVIDIA) => "nvav1enc",

            // https://gstreamer.freedesktop.org/documentation/va/vah264enc.html?gi-language=rust
            VideoCodec::H264(CodecType::VAAPI) => "vah264enc",
            // https://gstreamer.freedesktop.org/documentation/va/vah265enc.html?gi-language=rust
            VideoCodec::H265(CodecType::VAAPI) => "vah265enc",
            // https://gstreamer.freedesktop.org/documentation/va/vaav1enc.html?gi-language=rust
            VideoCodec::AV1(CodecType::VAAPI) => "vaav1enc",

            // https://gstreamer.freedesktop.org/documentation/x264/index.html?gi-language=rust
            VideoCodec::H264(CodecType::Software) => "x264enc",
            // https://gstreamer.freedesktop.org/documentation/x265/index.html?gi-language=rust
            VideoCodec::H265(CodecType::Software) => "x265enc",
            // https://gstreamer.freedesktop.org/documentation/aom/av1enc.html?gi-language=rust
            VideoCodec::AV1(CodecType::Software) => "av1enc",
        }
    }
}

/// Audio settings daemonw ill use
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioSettings {
    /// The sample rate, in Hz
    pub sample_rate_hz: SampleRate,
    /// The audio codec to use
    pub codec: AudioCodec,
    /// The pipewire microphone information
    pub microphone: AudioNode,
    /// The pipewire background information
    pub background: AudioNode,
}

impl Default for AudioSettings {
    fn default() -> Self {
        // On startup -> empty strings
        // When pipewire comes to life -> replace
        Self {
            sample_rate_hz: SampleRate::default(),
            codec: DEFAULT_AUDIO_CODEC,
            microphone: AudioNode::new(
                String::new(),
                AudioLevel(DEFAULT_MICROPHONE_LEVEL),
                DEFAULT_MICROPHONE_ENABLED,
            ),
            background: AudioNode::new(
                String::new(),
                AudioLevel(DEFAULT_BACKGROUND_LEVEL),
                DEFAULT_BACKGROUND_ENABLED,
            ),
        }
    }
}

/// Wrapper around audio sample rate
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SampleRate(pub u64);

impl Default for SampleRate {
    fn default() -> Self {
        Self(DEFAULT_AUDIO_SAMPLE_RATE)
    }
}

impl FromStr for SampleRate {
    type Err = WayclipError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let hz: u64 = s.parse()?;

        if !ALLOWED_AUDIO_SAMPLE_RATES_HZ.contains(&hz) {
            return Err(WayclipError::Validation(
                format!(
                    "The audio sample rate may only be one of the following: {:?}",
                    ALLOWED_AUDIO_SAMPLE_RATES_HZ
                )
                .into(),
            ));
        }

        Ok(Self(hz))
    }
}

impl Display for SampleRate {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}hz", self.0)
    }
}

/// Inforatiom about a single node
/// Data about node_name collected from pipewire
/// P.S. Just realising this should not be the case, since this is shared module, and pipewire not
/// available on windows...
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioNode {
    /// The level in range of 0.0-1.0
    pub level: AudioLevel,
    /// The pipewire node name
    pub node_name: String,
    /// If the node is enabled
    pub enabled: bool,
}

impl AudioNode {
    /// Create new node
    pub fn new(node_name: String, level: AudioLevel, enabled: bool) -> Self {
        Self {
            level,
            node_name,
            enabled,
        }
    }
}

/// AudioLevel wrapper
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioLevel(pub f64);

impl FromStr for AudioLevel {
    type Err = WayclipError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let level: f64 = s.parse()?;

        if !(MIN_AUDIO_LEVEL..=MAX_AUDIO_LEVEL).contains(&level) {
            return Err(WayclipError::Validation(
                format!(
                    "The audio level must be within the range {} to {}",
                    MIN_AUDIO_LEVEL, MAX_AUDIO_LEVEL
                )
                .into(),
            ));
        }

        Ok(Self(level))
    }
}

impl Display for AudioLevel {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// The audio codec to be used
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AudioCodec {
    /// Opus
    Opus,
    /// AAC
    AAC,
    /// MP3
    MP3,
}

impl FromStr for AudioCodec {
    type Err = WayclipError;
    fn from_str(s: &str) -> Result<Self, WayclipError> {
        match s.to_lowercase().as_str() {
            "opus" => Ok(AudioCodec::Opus),
            "aac" => Ok(AudioCodec::AAC),
            "mp3" => Ok(AudioCodec::MP3),
            _ => Err(WayclipError::Validation("Invalid codec type".into())),
        }
    }
}

impl std::fmt::Display for AudioCodec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            AudioCodec::Opus => "opus",
            AudioCodec::MP3 => "mp3",
            AudioCodec::AAC => "aac",
        };

        write!(f, "{s}")
    }
}

impl AudioCodec {
    /// Get the gstreamer encoder element
    pub fn get_encoder(&self) -> &str {
        match self {
            AudioCodec::Opus => "opusenc",
            AudioCodec::AAC => "avenc_aac",
            AudioCodec::MP3 => "lamemp3enc",
        }
    }

    /// Get the gstreamer parser element
    pub fn get_parser(&self) -> &str {
        match self {
            AudioCodec::Opus => "opusparse",
            AudioCodec::AAC => "aacparse",
            AudioCodec::MP3 => "mpegaudioparse",
        }
    }
}