rskit-media 0.2.0-alpha.3

Media types, codec/format registry, pipeline builder, and processing traits
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
//! Output configuration and encoding settings.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::{
    audio::{ChannelLayout, SampleRate},
    codec::{Codec, CodecLevel, CodecProfile},
    format::Format,
    registry::Registry,
    spatial::{FrameRate, Resolution},
};
use rskit_errors::{AppError, AppResult, ErrorCode};

/// Encoding quality preset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Quality {
    /// Lossless encoding.
    Lossless,
    /// Ultra-high quality.
    UltraHigh,
    /// High quality.
    High,
    /// Medium quality (default).
    Medium,
    /// Low quality.
    Low,
    /// Very low quality.
    VeryLow,
    /// Custom CRF/quality value (0–51 for x264).
    Custom(u8),
}

/// Bitrate specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Bitrate {
    /// Constant bitrate (bits/sec).
    Constant(u64),
    /// Variable bitrate target (bits/sec).
    Variable(u64),
    /// Constrained variable bitrate.
    Constrained {
        /// Target bitrate.
        target: u64,
        /// Maximum bitrate.
        max: u64,
    },
}

/// Encoding speed/effort tradeoff.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EncodingSpeed {
    /// Fastest encoding, lowest quality.
    UltraFast,
    /// Very fast encoding.
    SuperFast,
    /// Fast encoding.
    VeryFast,
    /// Faster than medium.
    Fast,
    /// Balanced speed/quality.
    Medium,
    /// Slower encoding, better quality.
    Slow,
    /// Slowest encoding, best quality.
    VerySlow,
}

/// Video-specific encoding settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoSettings {
    /// Video codec.
    pub codec: Codec,
    /// Output resolution.
    pub resolution: Option<Resolution>,
    /// Output frame rate.
    pub frame_rate: Option<FrameRate>,
    /// Quality preset.
    pub quality: Option<Quality>,
    /// Bitrate setting.
    pub bitrate: Option<Bitrate>,
    /// Encoding speed.
    pub speed: Option<EncodingSpeed>,
    /// Codec profile (e.g., H264High, HevcMain10).
    pub profile: Option<CodecProfile>,
    /// Codec level (e.g., "4.1").
    pub level: Option<CodecLevel>,
}

impl VideoSettings {
    /// Create new video settings with the given codec.
    pub fn new(codec: Codec) -> Self {
        Self {
            codec,
            resolution: None,
            frame_rate: None,
            quality: None,
            bitrate: None,
            speed: None,
            profile: None,
            level: None,
        }
    }

    /// Set the output resolution.
    #[must_use]
    pub fn with_resolution(mut self, res: Resolution) -> Self {
        self.resolution = Some(res);
        self
    }

    /// Set the output frame rate.
    #[must_use]
    pub fn with_frame_rate(mut self, fps: FrameRate) -> Self {
        self.frame_rate = Some(fps);
        self
    }

    /// Set the quality preset.
    #[must_use]
    pub fn with_quality(mut self, q: Quality) -> Self {
        self.quality = Some(q);
        self
    }

    /// Set the bitrate.
    #[must_use]
    pub fn with_bitrate(mut self, br: Bitrate) -> Self {
        self.bitrate = Some(br);
        self
    }

    /// Set the encoding speed.
    #[must_use]
    pub fn with_speed(mut self, speed: EncodingSpeed) -> Self {
        self.speed = Some(speed);
        self
    }

    /// Set the codec profile.
    #[must_use]
    pub fn with_profile(mut self, profile: CodecProfile) -> Self {
        self.profile = Some(profile);
        self
    }

    /// Set the codec level.
    #[must_use]
    pub fn with_level(mut self, level: CodecLevel) -> Self {
        self.level = Some(level);
        self
    }
}

/// Audio-specific encoding settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioSettings {
    /// Audio codec.
    pub codec: Codec,
    /// Sample rate.
    pub sample_rate: Option<SampleRate>,
    /// Channel layout.
    pub channels: Option<ChannelLayout>,
    /// Bitrate.
    pub bitrate: Option<Bitrate>,
}

impl AudioSettings {
    /// Create new audio settings with the given codec.
    pub fn new(codec: Codec) -> Self {
        Self {
            codec,
            sample_rate: None,
            channels: None,
            bitrate: None,
        }
    }

    /// Set the sample rate.
    #[must_use]
    pub fn with_sample_rate(mut self, sr: SampleRate) -> Self {
        self.sample_rate = Some(sr);
        self
    }

    /// Set the channel layout.
    #[must_use]
    pub fn with_channels(mut self, ch: ChannelLayout) -> Self {
        self.channels = Some(ch);
        self
    }

    /// Set the bitrate.
    #[must_use]
    pub fn with_bitrate(mut self, br: Bitrate) -> Self {
        self.bitrate = Some(br);
        self
    }
}

/// Complete output configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputConfig {
    /// Output container format.
    pub format: Format,
    /// Video encoding settings (None for audio-only).
    pub video: Option<VideoSettings>,
    /// Audio encoding settings (None for video-only).
    pub audio: Option<AudioSettings>,
    /// Streaming output settings (HLS, DASH, RTMP).
    pub streaming: Option<StreamingConfig>,
    /// Whether to strip metadata from output.
    pub strip_metadata: bool,
    /// Extra backend-specific parameters.
    pub extra: HashMap<String, String>,
}

/// Streaming output configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StreamingConfig {
    /// HTTP Live Streaming (HLS) output.
    Hls(HlsConfig),
    /// MPEG-DASH output.
    Dash(DashConfig),
    /// RTMP push output.
    Rtmp(RtmpConfig),
}

/// HLS output configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HlsConfig {
    /// Segment duration in seconds (default: 6).
    pub segment_duration: u32,
    /// Number of segments in playlist (0 = all).
    pub playlist_size: u32,
    /// Playlist type.
    pub playlist_type: HlsPlaylistType,
    /// Segment filename pattern (default: "segment_%03d.ts").
    pub segment_filename: Option<String>,
}

impl Default for HlsConfig {
    fn default() -> Self {
        Self {
            segment_duration: 6,
            playlist_size: 0,
            playlist_type: HlsPlaylistType::Vod,
            segment_filename: None,
        }
    }
}

/// HLS playlist type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum HlsPlaylistType {
    /// Video on demand — all segments in playlist.
    Vod,
    /// Live/event — sliding window.
    Event,
}

/// DASH output configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashConfig {
    /// Segment duration in seconds (default: 4).
    pub segment_duration: u32,
    /// Use segment template mode.
    pub use_template: bool,
    /// Use segment timeline.
    pub use_timeline: bool,
}

impl Default for DashConfig {
    fn default() -> Self {
        Self {
            segment_duration: 4,
            use_template: true,
            use_timeline: true,
        }
    }
}

/// RTMP push configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RtmpConfig {
    /// RTMP server URL (e.g., "rtmp://live.example.com/app/stream_key").
    pub url: String,
}

impl OutputConfig {
    /// Create a new output config with the given format.
    pub fn new(format: Format) -> Self {
        Self {
            format,
            video: None,
            audio: None,
            streaming: None,
            strip_metadata: false,
            extra: HashMap::new(),
        }
    }

    /// Set video encoding settings.
    #[must_use]
    pub fn with_video(mut self, video: VideoSettings) -> Self {
        self.video = Some(video);
        self
    }

    /// Set audio encoding settings.
    #[must_use]
    pub fn with_audio(mut self, audio: AudioSettings) -> Self {
        self.audio = Some(audio);
        self
    }

    /// Set streaming output configuration.
    #[must_use]
    pub fn with_streaming(mut self, streaming: StreamingConfig) -> Self {
        self.streaming = Some(streaming);
        self
    }

    /// Strip metadata from output.
    #[must_use]
    pub fn with_strip_metadata(mut self) -> Self {
        self.strip_metadata = true;
        self
    }

    /// Add an extra backend-specific parameter.
    #[must_use]
    pub fn with_param(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {
        self.extra.insert(key.into(), val.into());
        self
    }

    /// Validate codec/format compatibility against a registry.
    pub fn validate(&self, registry: &Registry) -> AppResult<()> {
        if let Some(video) = &self.video
            && !registry.is_compatible(&video.codec, &self.format)
        {
            return Err(AppError::new(
                ErrorCode::InvalidInput,
                format!(
                    "video codec {} is not compatible with format {}",
                    video.codec, self.format,
                ),
            ));
        }
        if let Some(audio) = &self.audio
            && !registry.is_compatible(&audio.codec, &self.format)
        {
            return Err(AppError::new(
                ErrorCode::InvalidInput,
                format!(
                    "audio codec {} is not compatible with format {}",
                    audio.codec, self.format,
                ),
            ));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        audio::{ChannelLayout, SampleRate},
        codec::{self, Codec, CodecLevel, CodecProfile},
        format,
        spatial::{FrameRate, Resolution},
    };

    use super::*;

    #[test]
    fn video_audio_streaming_and_output_builders_set_all_fields() {
        let video = VideoSettings::new(Codec::new(codec::video::H264))
            .with_resolution(Resolution::p720())
            .with_frame_rate(FrameRate::fps(30))
            .with_quality(Quality::High)
            .with_bitrate(Bitrate::Constrained {
                target: 1_000,
                max: 2_000,
            })
            .with_speed(EncodingSpeed::Fast)
            .with_profile(CodecProfile::H264High)
            .with_level(CodecLevel::new("4.1"));
        let audio = AudioSettings::new(Codec::new(codec::audio::AAC))
            .with_sample_rate(SampleRate::dvd())
            .with_channels(ChannelLayout::Stereo)
            .with_bitrate(Bitrate::Variable(128_000));
        let output = OutputConfig::new(Format::new(format::MP4))
            .with_video(video)
            .with_audio(audio)
            .with_streaming(StreamingConfig::Hls(HlsConfig::default()))
            .with_strip_metadata()
            .with_param("movflags", "faststart");

        assert!(output.video.as_ref().unwrap().profile.is_some());
        assert!(output.video.as_ref().unwrap().level.is_some());
        assert!(output.audio.as_ref().unwrap().sample_rate.is_some());
        assert!(matches!(output.streaming, Some(StreamingConfig::Hls(_))));
        assert!(output.strip_metadata);
        assert_eq!(
            output.extra.get("movflags").map(String::as_str),
            Some("faststart")
        );
    }

    #[test]
    fn streaming_defaults_are_stable() {
        let hls = HlsConfig::default();
        assert_eq!(hls.segment_duration, 6);
        assert_eq!(hls.playlist_size, 0);
        assert_eq!(hls.playlist_type, HlsPlaylistType::Vod);
        assert!(hls.segment_filename.is_none());

        let dash = DashConfig::default();
        assert_eq!(dash.segment_duration, 4);
        assert!(dash.use_template);
        assert!(dash.use_timeline);
    }
}