Skip to main content

libobs_simple\output/
simple.rs

1//! Simple output builder for OBS.
2//!
3//! This module provides a simplified interface for configuring OBS outputs
4//! based on the SimpleOutput implementation from OBS Studio.
5//!
6//! # Example
7//!
8//! ```no_run
9//! use libobs_simple::output::simple::{SimpleOutputBuilder, X264Preset};
10//! use libobs_wrapper::{data::video::ObsVideoInfoBuilder, utils::{ObsPath, StartupInfo}};
11//!
12//! fn main() -> Result<(), Box<dyn std::error::Error>> {
13//!     let context = StartupInfo::new()
14//!         .set_video_info(ObsVideoInfoBuilder::new().build())
15//!         .start()?;
16//!
17//!     let _output = SimpleOutputBuilder::new(context, "recording", ObsPath::new("./recording.mp4"))
18//!         .video_bitrate(6000)
19//!         .audio_bitrate(160)
20//!         .x264_encoder(X264Preset::VeryFast)
21//!         .build()?;
22//!
23//!     Ok(())
24//! }
25//! ```
26
27use libobs_wrapper::{
28    capabilities::{
29        EncoderTypeInfo, ObsCapabilities, OutputCapabilities, OutputCompatibilityRequest,
30    },
31    context::ObsContext,
32    data::{
33        audio::{AudioEncoderSlot, AudioMixIndex},
34        output::{ObsOutputRef, ObsOutputTrait},
35        ObsData, ObsDataSetters,
36    },
37    encoders::{ObsAudioEncoderType, ObsVideoEncoderType},
38    settings::PropertyValue,
39    utils::{ObsError, ObsPath, ObsString},
40};
41
42use super::configure::{set_reported, ConfigurationMode, OutputConfigurationReport};
43
44/// Preset for x264 software encoder
45#[derive(Debug, Clone, Copy)]
46pub enum X264Preset {
47    /// Ultrafast preset - lowest CPU usage, largest file size
48    UltraFast,
49    /// Superfast preset
50    SuperFast,
51    /// Veryfast preset (recommended default)
52    VeryFast,
53    /// Faster preset
54    Faster,
55    /// Fast preset - higher CPU usage, better quality
56    Fast,
57    /// Medium preset
58    Medium,
59    /// Slow preset
60    Slow,
61    /// Slower preset
62    Slower,
63}
64
65impl X264Preset {
66    pub fn as_str(&self) -> &'static str {
67        match self {
68            X264Preset::UltraFast => "ultrafast",
69            X264Preset::SuperFast => "superfast",
70            X264Preset::VeryFast => "veryfast",
71            X264Preset::Faster => "faster",
72            X264Preset::Fast => "fast",
73            X264Preset::Medium => "medium",
74            X264Preset::Slow => "slow",
75            X264Preset::Slower => "slower",
76        }
77    }
78}
79
80/// Preset for hardware encoders (NVENC, AMD, QSV)
81#[derive(Debug, Clone, Copy)]
82pub enum HardwarePreset {
83    /// Prioritize encoding speed over quality
84    Speed,
85    /// Balance between speed and quality
86    Balanced,
87    /// Prioritize quality over speed
88    Quality,
89}
90
91impl HardwarePreset {
92    pub fn as_str(&self) -> &'static str {
93        match self {
94            HardwarePreset::Speed => "speed",
95            HardwarePreset::Balanced => "balanced",
96            HardwarePreset::Quality => "quality",
97        }
98    }
99}
100
101/// Video encoder configuration
102#[derive(Debug, Clone)]
103pub enum VideoEncoder {
104    /// Automatically select an encoder for this codec, preferring hardware and falling back
105    /// to a software implementation when the current OBS installation has no hardware option.
106    Auto(HardwareCodec),
107    /// x264 software encoder
108    X264(X264Preset),
109    /// Require a hardware encoder (NVENC/AMF/QSV/etc.); no software fallback is allowed.
110    Hardware {
111        codec: HardwareCodec,
112        preset: HardwarePreset,
113    },
114    /// Custom encoder by type
115    Custom(ObsVideoEncoderType),
116}
117
118/// Target codec for generic hardware selection
119#[derive(Debug, Clone, Copy)]
120pub enum HardwareCodec {
121    H264,
122    HEVC,
123    AV1,
124}
125
126impl HardwareCodec {
127    fn codec_name(self) -> &'static str {
128        match self {
129            Self::H264 => "h264",
130            Self::HEVC => "hevc",
131            Self::AV1 => "av1",
132        }
133    }
134}
135
136fn video_encoder_descriptor(
137    capabilities: &ObsCapabilities,
138    encoder: &VideoEncoder,
139) -> Result<EncoderTypeInfo, ObsError> {
140    video_encoder_candidates(capabilities, encoder)
141        .into_iter()
142        .next()
143        .ok_or(ObsError::NoAvailableEncoders)
144}
145
146fn video_encoder_candidates(
147    capabilities: &ObsCapabilities,
148    encoder: &VideoEncoder,
149) -> Vec<EncoderTypeInfo> {
150    match encoder {
151        VideoEncoder::Auto(codec) => capabilities
152            .select_video_encoder()
153            .codec(codec.codec_name())
154            .prefer_hardware()
155            .matches()
156            .into_iter()
157            .cloned()
158            .collect(),
159        VideoEncoder::Hardware { codec, .. } => capabilities
160            .select_video_encoder()
161            .codec(codec.codec_name())
162            .require_hardware()
163            .matches()
164            .into_iter()
165            .cloned()
166            .collect(),
167        VideoEncoder::X264(_) => capabilities
168            .encoders()
169            .iter()
170            .filter(|candidate| candidate.id() == "obs_x264")
171            .cloned()
172            .collect(),
173        VideoEncoder::Custom(encoder_type) => {
174            let id = ObsString::from(encoder_type.clone()).to_string();
175            capabilities
176                .encoders()
177                .iter()
178                .filter(|candidate| candidate.id() == id)
179                .cloned()
180                .collect()
181        }
182    }
183}
184
185fn creation_failure_allows_fallback(error: &ObsError) -> bool {
186    matches!(
187        error,
188        ObsError::NullPointer(_) | ObsError::NoAvailableEncoders | ObsError::SourceNotAvailable(_)
189    )
190}
191
192fn start_failure_allows_encoder_fallback(error: &ObsError) -> bool {
193    let ObsError::OutputStartFailure(Some(message)) = error else {
194        return false;
195    };
196    let message = message.to_ascii_lowercase();
197    if [
198        "path",
199        "permission",
200        "disk",
201        "space",
202        "connect",
203        "server",
204        "auth",
205        "stream key",
206        "network",
207        "url",
208        "destination",
209    ]
210    .iter()
211    .any(|token| message.contains(token))
212    {
213        return false;
214    }
215    ["encoder", "nvenc", "amf", "qsv", "vaapi", "videotoolbox"]
216        .iter()
217        .any(|token| message.contains(token))
218}
219
220pub(crate) fn select_video_encoder_type(
221    context: &ObsContext,
222    encoder: &VideoEncoder,
223) -> Result<ObsVideoEncoderType, ObsError> {
224    let capabilities = context.capabilities()?;
225    let descriptor = video_encoder_descriptor(&capabilities, encoder)?;
226    Ok(ObsVideoEncoderType::from(descriptor.id()))
227}
228
229fn audio_encoder_descriptor(
230    capabilities: &ObsCapabilities,
231    encoder: &AudioEncoder,
232) -> Result<EncoderTypeInfo, ObsError> {
233    if let AudioEncoder::Custom(encoder_type) = encoder {
234        let id = ObsString::from(encoder_type.clone()).to_string();
235        return capabilities
236            .encoders()
237            .iter()
238            .find(|candidate| candidate.id() == id)
239            .cloned()
240            .ok_or(ObsError::NoAvailableEncoders);
241    }
242
243    let codec = match encoder {
244        AudioEncoder::AAC => "aac",
245        AudioEncoder::Opus => "opus",
246        AudioEncoder::Custom(_) => unreachable!(),
247    };
248    capabilities
249        .select_audio_encoder()
250        .codec(codec)
251        .best_available()
252        .cloned()
253        .ok_or(ObsError::NoAvailableEncoders)
254}
255
256/// Audio encoder configuration
257#[derive(Debug, Clone)]
258pub enum AudioEncoder {
259    /// AAC audio encoder (ffmpeg)
260    AAC,
261    /// Opus audio encoder
262    Opus,
263    /// Custom audio encoder by type
264    Custom(ObsAudioEncoderType),
265}
266
267/// Output format for file recording
268#[derive(Debug, Clone, Copy, Default)]
269pub enum OutputFormat {
270    /// .flv
271    FlashVideo,
272    /// .mkv
273    MatroskaVideo,
274    /// .mp4
275    Mpeg4,
276    /// .mov
277    QuickTime,
278    /// .mp4 (hybrid)
279    #[default]
280    HybridMP4,
281    /// .mov (hybrid)
282    HybridMov,
283    /// .mp4 (fragmented)
284    FragmentedMP4,
285    /// .mov (fragmented)
286    FragmentedMOV,
287    /// MPEG-TS .ts
288    MpegTs,
289}
290
291/// One audio track in a simple recording. The encoder reads `mix` and is attached to `slot`.
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293pub struct SimpleAudioTrack {
294    pub mix: AudioMixIndex,
295    pub slot: AudioEncoderSlot,
296}
297
298impl SimpleAudioTrack {
299    pub const fn new(mix: AudioMixIndex, slot: AudioEncoderSlot) -> Self {
300        Self { mix, slot }
301    }
302}
303
304/// Unified output settings
305#[derive(Debug, Clone)]
306pub struct OutputSettings {
307    name: ObsString,
308    video_bitrate: u32,
309    audio_bitrate: u32,
310    video_encoder: VideoEncoder,
311    audio_encoder: AudioEncoder,
312    audio_tracks: Vec<SimpleAudioTrack>,
313    custom_encoder_settings: Option<String>,
314    path: ObsPath,
315    format: OutputFormat,
316    custom_muxer_settings: Option<String>,
317    /// Quality for CRF-based x264 encoding, on a 0–100 scale.
318    crf: Option<u32>,
319    configuration_mode: ConfigurationMode,
320}
321
322impl OutputSettings {
323    /// Sets the video bitrate in Kbps.
324    pub fn with_video_bitrate(mut self, bitrate: u32) -> Self {
325        self.video_bitrate = bitrate;
326        self
327    }
328
329    /// Sets the audio bitrate in Kbps.
330    pub fn with_audio_bitrate(mut self, bitrate: u32) -> Self {
331        self.audio_bitrate = bitrate;
332        self
333    }
334
335    /// Sets the video encoder to use x264 software encoding.
336    pub fn with_x264_encoder(mut self, preset: X264Preset) -> Self {
337        self.video_encoder = VideoEncoder::X264(preset);
338        self
339    }
340
341    /// Sets the video encoder to use a generic hardware encoder for the given codec.
342    /// The builder will choose an available backend (NVENC/AMF/QSV) at runtime.
343    pub fn with_hardware_encoder(mut self, codec: HardwareCodec, preset: HardwarePreset) -> Self {
344        self.video_encoder = VideoEncoder::Hardware { codec, preset };
345        self
346    }
347
348    /// Sets a custom video encoder.
349    pub fn with_custom_video_encoder(mut self, encoder: ObsVideoEncoderType) -> Self {
350        self.video_encoder = VideoEncoder::Custom(encoder);
351        self
352    }
353
354    /// Sets custom x264 encoder settings.
355    pub fn with_custom_settings<S: Into<String>>(mut self, settings: S) -> Self {
356        self.custom_encoder_settings = Some(settings.into());
357        self
358    }
359
360    /// Sets a quality target for x264 encoding on a 0–100 scale.
361    ///
362    /// A value of 100 maps to x264 CRF 0 (highest quality), while 0 maps to
363    /// CRF 51 (lowest quality). Hardware encoders retain bitrate-based control.
364    pub fn with_crf(mut self, crf: u32) -> Self {
365        self.crf = Some(crf.min(100));
366        self
367    }
368
369    /// Sets the output path.
370    pub fn with_path<P: Into<ObsPath>>(mut self, path: P) -> Self {
371        self.path = path.into();
372        self
373    }
374
375    /// Sets the output format.
376    pub fn with_format(mut self, format: OutputFormat) -> Self {
377        self.format = format;
378        self
379    }
380
381    /// Sets custom muxer settings.
382    pub fn with_custom_muxer_settings<S: Into<String>>(mut self, settings: S) -> Self {
383        self.custom_muxer_settings = Some(settings.into());
384        self
385    }
386
387    /// Sets the audio encoder.
388    pub fn with_audio_encoder(mut self, encoder: AudioEncoder) -> Self {
389        self.audio_encoder = encoder;
390        self
391    }
392}
393
394#[derive(Debug, Clone)]
395pub struct SimpleOutputBuilder {
396    settings: OutputSettings,
397    context: ObsContext,
398}
399
400/// Simple recording output paired with the effective plugin/settings report used to build it.
401#[derive(Debug)]
402pub struct ConfiguredSimpleOutput {
403    output: ObsOutputRef,
404    report: OutputConfigurationReport,
405}
406
407impl ConfiguredSimpleOutput {
408    pub fn output(&self) -> &ObsOutputRef {
409        &self.output
410    }
411
412    pub fn report(&self) -> &OutputConfigurationReport {
413        &self.report
414    }
415
416    pub fn into_output(self) -> ObsOutputRef {
417        self.output
418    }
419}
420
421/// Managed simple recording that can conservatively retry eligible encoder initialization/start
422/// failures using the remaining compatible candidates. Destination/auth/path errors are never
423/// retried as encoder fallbacks.
424#[derive(Debug)]
425pub struct ManagedSimpleOutput {
426    template: SimpleOutputBuilder,
427    configured: ConfiguredSimpleOutput,
428    next_candidate: usize,
429}
430
431impl ManagedSimpleOutput {
432    pub fn output(&self) -> &ObsOutputRef {
433        self.configured.output()
434    }
435
436    pub fn report(&self) -> &OutputConfigurationReport {
437        self.configured.report()
438    }
439
440    pub fn start(&mut self) -> Result<(), ObsError> {
441        loop {
442            let plugin_id = self.configured.report.video_encoder_plugin_id.clone();
443            match self.configured.output.start() {
444                Ok(()) => {
445                    self.configured.report.attempts.push(super::EncoderAttempt {
446                        plugin_id,
447                        stage: super::EncoderAttemptStage::Start,
448                        outcome: super::EncoderAttemptOutcome::Succeeded,
449                    });
450                    return Ok(());
451                }
452                Err(error) => {
453                    let eligible = start_failure_allows_encoder_fallback(&error);
454                    self.configured.report.attempts.push(super::EncoderAttempt {
455                        plugin_id: plugin_id.clone(),
456                        stage: super::EncoderAttemptStage::Start,
457                        outcome: super::EncoderAttemptOutcome::Failed {
458                            error: error.to_string(),
459                            fallback_eligible: eligible,
460                        },
461                    });
462                    if !eligible
463                        || self.configured.output.is_active().unwrap_or(true)
464                        || self.configured.output.is_reconnecting().unwrap_or(true)
465                    {
466                        return Err(error);
467                    }
468
469                    let prior_attempts = self.configured.report.attempts.clone();
470                    let prior_reasons = self.configured.report.fallback_reasons.clone();
471                    let (mut replacement, next_candidate) = self
472                        .template
473                        .clone()
474                        .build_with_report_from_candidate(self.next_candidate)?;
475                    replacement.report.attempts.splice(0..0, prior_attempts);
476                    replacement
477                        .report
478                        .fallback_reasons
479                        .splice(0..0, prior_reasons);
480                    replacement.report.fallback_reasons.push(format!(
481                        "encoder '{}' failed to start; retrying eligible backend '{}'",
482                        plugin_id, replacement.report.video_encoder_plugin_id
483                    ));
484                    self.configured = replacement;
485                    self.next_candidate = next_candidate;
486                }
487            }
488        }
489    }
490
491    pub fn stop(&self) -> Result<(), ObsError> {
492        self.configured.output.stop()
493    }
494}
495
496pub trait ObsContextSimpleExt {
497    fn simple_output_builder<K: Into<ObsPath>, T: Into<ObsString>>(
498        &self,
499        name: T,
500        path: K,
501    ) -> SimpleOutputBuilder;
502}
503
504impl ObsContextSimpleExt for ObsContext {
505    fn simple_output_builder<K: Into<ObsPath>, T: Into<ObsString>>(
506        &self,
507        name: T,
508        path: K,
509    ) -> SimpleOutputBuilder {
510        SimpleOutputBuilder::new(self.clone(), name, path)
511    }
512}
513
514impl SimpleOutputBuilder {
515    /// Creates a new SimpleOutputBuilder with default settings.
516    pub fn new<K: Into<ObsPath>, T: Into<ObsString>>(
517        context: ObsContext,
518        name: T,
519        path: K,
520    ) -> Self {
521        SimpleOutputBuilder {
522            settings: OutputSettings {
523                video_bitrate: 6000,
524                audio_bitrate: 160,
525                video_encoder: VideoEncoder::Auto(HardwareCodec::H264),
526                audio_encoder: AudioEncoder::AAC,
527                audio_tracks: vec![SimpleAudioTrack::new(
528                    AudioMixIndex::new(0).expect("OBS always exposes mix 0"),
529                    AudioEncoderSlot::new(0).expect("OBS always exposes audio slot 0"),
530                )],
531                custom_encoder_settings: None,
532                path: path.into(),
533                format: OutputFormat::default(),
534                custom_muxer_settings: None,
535                crf: None,
536                configuration_mode: ConfigurationMode::Permissive,
537                name: name.into(),
538            },
539            context,
540        }
541    }
542
543    /// Sets the output settings.
544    pub fn settings(mut self, settings: OutputSettings) -> Self {
545        self.settings = settings;
546        self
547    }
548
549    /// Sets the video bitrate in Kbps.
550    pub fn video_bitrate(mut self, bitrate: u32) -> Self {
551        self.settings.video_bitrate = bitrate;
552        self
553    }
554
555    /// Sets the audio bitrate in Kbps.
556    pub fn audio_bitrate(mut self, bitrate: u32) -> Self {
557        self.settings.audio_bitrate = bitrate;
558        self
559    }
560
561    /// Sets the output path.
562    pub fn path<P: Into<ObsPath>>(mut self, path: P) -> Self {
563        self.settings.path = path.into();
564        self
565    }
566
567    /// Sets the output format.
568    pub fn format(mut self, format: OutputFormat) -> Self {
569        self.settings.format = format;
570        self
571    }
572
573    /// Uses automatic codec-based encoder selection. Hardware implementations are preferred,
574    /// while software encoders remain a transparent fallback.
575    pub fn auto_video_encoder(mut self, codec: HardwareCodec) -> Self {
576        self.settings.video_encoder = VideoEncoder::Auto(codec);
577        self
578    }
579
580    /// Prefer hardware for the requested codec while allowing software fallback.
581    pub fn prefer_hardware_encoder(self, codec: HardwareCodec) -> Self {
582        self.auto_video_encoder(codec)
583    }
584
585    /// Sets the video encoder to x264.
586    pub fn x264_encoder(mut self, preset: X264Preset) -> Self {
587        self.settings.video_encoder = VideoEncoder::X264(preset);
588        self
589    }
590
591    /// Requires a generic hardware encoder. If no hardware backend is available, build fails.
592    pub fn hardware_encoder(mut self, codec: HardwareCodec, preset: HardwarePreset) -> Self {
593        self.settings.video_encoder = VideoEncoder::Hardware { codec, preset };
594        self
595    }
596
597    /// Alias spelling out the no-software-fallback policy.
598    pub fn require_hardware_encoder(self, codec: HardwareCodec, preset: HardwarePreset) -> Self {
599        self.hardware_encoder(codec, preset)
600    }
601
602    /// Selects one explicit backend by OBS encoder type. No automatic backend substitution occurs.
603    pub fn explicit_video_encoder(mut self, encoder: ObsVideoEncoderType) -> Self {
604        self.settings.video_encoder = VideoEncoder::Custom(encoder);
605        self
606    }
607
608    /// Requires all requested generic encoder settings to be accepted exactly by the selected
609    /// backend. In permissive mode (the default), unsupported/rejected generic choices retain the
610    /// plugin default and are surfaced in [`OutputConfigurationReport`].
611    pub fn configuration_mode(mut self, mode: ConfigurationMode) -> Self {
612        self.settings.configuration_mode = mode;
613        self
614    }
615
616    pub fn strict_configuration(self) -> Self {
617        self.configuration_mode(ConfigurationMode::Strict)
618    }
619
620    /// Adds an encoded recording track. The source mix and output attachment slot are independent.
621    ///
622    /// The builder starts with mix 0 at slot 0 for compatibility. A common layout keeps that
623    /// combined track and adds dedicated desktop/microphone mixes at slots 1 and 2.
624    pub fn audio_track(mut self, mix: AudioMixIndex, slot: AudioEncoderSlot) -> Self {
625        self.settings
626            .audio_tracks
627            .retain(|track| track.slot != slot);
628        self.settings
629            .audio_tracks
630            .push(SimpleAudioTrack::new(mix, slot));
631        self
632    }
633
634    /// Removes the compatibility default combined track (mix 0 / slot 0).
635    pub fn without_default_audio_track(mut self) -> Self {
636        self.settings
637            .audio_tracks
638            .retain(|track| track.slot.index() != 0);
639        self
640    }
641
642    /// Sets a quality target for x264 encoding on a 0–100 scale.
643    ///
644    /// A value of 100 maps to x264 CRF 0 (highest quality), while 0 maps to
645    /// CRF 51 (lowest quality). Hardware encoders retain bitrate-based control.
646    pub fn crf(mut self, crf: u32) -> Self {
647        self.settings.crf = Some(crf.min(100));
648        self
649    }
650
651    /// Builds a validated recording graph using the concrete capabilities available at runtime.
652    /// This compatibility entry point discards the structured configuration report.
653    pub fn build(self) -> Result<ObsOutputRef, ObsError> {
654        Ok(self.build_with_report()?.into_output())
655    }
656
657    /// Builds the graph and returns the effective plugin/settings configuration report.
658    pub fn build_with_report(self) -> Result<ConfiguredSimpleOutput, ObsError> {
659        self.build_with_report_from_candidate(0)
660            .map(|(configured, _)| configured)
661    }
662
663    /// Builds the managed variant that can retry eligible initialization/start failures.
664    pub fn build_managed(self) -> Result<ManagedSimpleOutput, ObsError> {
665        let template = self.clone();
666        let (configured, next_candidate) = self.build_with_report_from_candidate(0)?;
667        Ok(ManagedSimpleOutput {
668            template,
669            configured,
670            next_candidate,
671        })
672    }
673
674    fn build_with_report_from_candidate(
675        self,
676        candidate_start: usize,
677    ) -> Result<(ConfiguredSimpleOutput, usize), ObsError> {
678        let output_id = match self.settings.format {
679            OutputFormat::HybridMP4 => "mp4_output",
680            OutputFormat::HybridMov => "mov_output",
681            _ => "ffmpeg_muxer",
682        };
683
684        let capabilities = self.context.capabilities()?;
685        let video_candidates =
686            video_encoder_candidates(&capabilities, &self.settings.video_encoder);
687        let preferred_video_type = video_candidates
688            .get(candidate_start)
689            .cloned()
690            .ok_or(ObsError::NoAvailableEncoders)?;
691        let audio_type = audio_encoder_descriptor(&capabilities, &self.settings.audio_encoder)?;
692
693        let mut compatibility = OutputCompatibilityRequest::new()
694            .output_id(output_id)
695            .require_output_capabilities(
696                OutputCapabilities::ENCODED | OutputCapabilities::VIDEO | OutputCapabilities::AUDIO,
697            );
698        if let Some(codec) = preferred_video_type.codec() {
699            compatibility = compatibility.video_codec(codec);
700        }
701        if let Some(codec) = audio_type.codec() {
702            compatibility = compatibility.audio_codec(codec);
703        }
704        let output_type = capabilities
705            .best_output_plan(&compatibility)
706            .map_err(|report| ObsError::NoCompatibleOutputGraph {
707                summary: report.summary(),
708            })?
709            .output()
710            .clone();
711
712        let mut report = OutputConfigurationReport {
713            output_plugin_id: output_type.id().to_owned(),
714            video_encoder_plugin_id: preferred_video_type.id().to_owned(),
715            audio_encoder_plugin_ids: self
716                .settings
717                .audio_tracks
718                .iter()
719                .map(|_| audio_type.id().to_owned())
720                .collect(),
721            ..Default::default()
722        };
723        if matches!(self.settings.video_encoder, VideoEncoder::Auto(_))
724            && !preferred_video_type.is_likely_hardware_accelerated()
725        {
726            report.fallback_reasons.push(format!(
727                "preferred hardware encoder was unavailable; selected software backend '{}'",
728                preferred_video_type.id()
729            ));
730        }
731
732        let mut output_settings = output_type.default_settings_mut()?;
733        output_settings.set_string("path", self.settings.path.clone().build())?;
734        if let Some(ref muxer_settings) = self.settings.custom_muxer_settings {
735            output_settings.set_string("muxer_settings", muxer_settings.as_str())?;
736        }
737
738        let mut selected_video = None;
739        let mut selected_index = candidate_start;
740        let mut last_creation_error = None;
741        for (index, video_type) in video_candidates.iter().enumerate().skip(candidate_start) {
742            let mut candidate_report = OutputConfigurationReport::default();
743            let mut video_settings = video_type.default_settings_mut()?;
744            self.configure_video_encoder(video_type, &mut video_settings, &mut candidate_report)?;
745            match self.context.create_video_encoder(
746                video_type,
747                format!("{}_video_encoder", self.settings.name),
748                Some(video_settings),
749            ) {
750                Ok(encoder) => {
751                    report.video_encoder_plugin_id = video_type.id().to_owned();
752                    report.settings.extend(candidate_report.settings);
753                    report.attempts.push(super::EncoderAttempt {
754                        plugin_id: video_type.id().to_owned(),
755                        stage: super::EncoderAttemptStage::Creation,
756                        outcome: super::EncoderAttemptOutcome::Succeeded,
757                    });
758                    if index > candidate_start {
759                        report.fallback_reasons.push(format!(
760                            "earlier encoder creation failed; selected '{}'",
761                            video_type.id()
762                        ));
763                    }
764                    selected_video = Some(encoder);
765                    selected_index = index;
766                    break;
767                }
768                Err(error) => {
769                    let eligible = creation_failure_allows_fallback(&error);
770                    report.attempts.push(super::EncoderAttempt {
771                        plugin_id: video_type.id().to_owned(),
772                        stage: super::EncoderAttemptStage::Creation,
773                        outcome: super::EncoderAttemptOutcome::Failed {
774                            error: error.to_string(),
775                            fallback_eligible: eligible,
776                        },
777                    });
778                    if !eligible {
779                        return Err(error);
780                    }
781                    last_creation_error = Some(error);
782                }
783            }
784        }
785        let video_encoder = selected_video
786            .ok_or_else(|| last_creation_error.unwrap_or(ObsError::NoAvailableEncoders))?;
787
788        if self.settings.audio_tracks.is_empty() {
789            return Err(ObsError::InvalidOperation(
790                "simple recording requires at least one audio track".into(),
791            ));
792        }
793
794        let mut audio_encoders = Vec::with_capacity(self.settings.audio_tracks.len());
795        for track in &self.settings.audio_tracks {
796            let mut audio_settings = audio_type.default_settings_mut()?;
797            let audio_schema = audio_type.settings_schema_for(&audio_settings)?;
798            set_reported(
799                &audio_schema,
800                &mut audio_settings,
801                "audio_encoder",
802                "rate_control",
803                PropertyValue::String("CBR".into()),
804                self.settings.configuration_mode,
805                &mut report,
806            )?;
807            set_reported(
808                &audio_schema,
809                &mut audio_settings,
810                "audio_encoder",
811                "bitrate",
812                PropertyValue::Integer(i64::from(self.settings.audio_bitrate)),
813                self.settings.configuration_mode,
814                &mut report,
815            )?;
816            let encoder = self.context.create_audio_encoder_for_mix(
817                &audio_type,
818                format!(
819                    "{}_audio_mix{}_slot{}",
820                    self.settings.name,
821                    track.mix.index(),
822                    track.slot.index()
823                ),
824                Some(audio_settings),
825                track.mix,
826            )?;
827            audio_encoders.push((*track, encoder));
828        }
829
830        let mut pipeline = self
831            .context
832            .output_pipeline(
833                &output_type,
834                self.settings.name.clone(),
835                Some(output_settings),
836            )
837            .video_encoder(video_encoder);
838        for (track, encoder) in audio_encoders {
839            pipeline = pipeline.audio_encoder_at_slot(track.slot, encoder);
840        }
841
842        Ok((
843            ConfiguredSimpleOutput {
844                output: pipeline.build()?.into_output(),
845                report,
846            },
847            selected_index + 1,
848        ))
849    }
850
851    fn get_encoder_preset(&self, encoder: &VideoEncoder) -> Option<&str> {
852        match encoder {
853            VideoEncoder::Auto(_) => None,
854            VideoEncoder::X264(preset) => Some(preset.as_str()),
855            VideoEncoder::Hardware { preset, .. } => Some(preset.as_str()),
856            VideoEncoder::Custom(_) => None,
857        }
858    }
859
860    fn x264_crf_from_quality(quality: u32) -> i64 {
861        (100u32.saturating_sub(quality.min(100)) * 51 / 100) as i64
862    }
863
864    fn uses_x264(encoder_type: &EncoderTypeInfo) -> bool {
865        encoder_type.id() == "obs_x264"
866    }
867
868    fn configure_video_encoder(
869        &self,
870        encoder_type: &EncoderTypeInfo,
871        settings: &mut ObsData,
872        report: &mut OutputConfigurationReport,
873    ) -> Result<(), ObsError> {
874        let schema = encoder_type.settings_schema_for(settings)?;
875        let use_crf = self.settings.crf.is_some() && Self::uses_x264(encoder_type);
876        if use_crf {
877            set_reported(
878                &schema,
879                settings,
880                "video_encoder",
881                "rate_control",
882                PropertyValue::String("CRF".into()),
883                self.settings.configuration_mode,
884                report,
885            )?;
886            if let Some(quality) = self.settings.crf {
887                set_reported(
888                    &schema,
889                    settings,
890                    "video_encoder",
891                    "crf",
892                    PropertyValue::Integer(Self::x264_crf_from_quality(quality)),
893                    self.settings.configuration_mode,
894                    report,
895                )?;
896            }
897        } else {
898            set_reported(
899                &schema,
900                settings,
901                "video_encoder",
902                "rate_control",
903                PropertyValue::String("CBR".into()),
904                self.settings.configuration_mode,
905                report,
906            )?;
907            set_reported(
908                &schema,
909                settings,
910                "video_encoder",
911                "bitrate",
912                PropertyValue::Integer(i64::from(self.settings.video_bitrate)),
913                self.settings.configuration_mode,
914                report,
915            )?;
916            if self.settings.crf.is_some() {
917                let reason = format!(
918                    "CRF is x264-specific; selected backend '{}' retained its bitrate/default rate control",
919                    encoder_type.id()
920                );
921                report.fallback_reasons.push(reason.clone());
922                log::warn!("{reason}");
923                if self.settings.configuration_mode == ConfigurationMode::Strict {
924                    return Err(ObsError::InvalidOperation(reason));
925                }
926            }
927        }
928        if let Some(preset) = self.get_encoder_preset(&self.settings.video_encoder) {
929            set_reported(
930                &schema,
931                settings,
932                "video_encoder",
933                "preset",
934                PropertyValue::String(preset.into()),
935                self.settings.configuration_mode,
936                report,
937            )?;
938        }
939        if let Some(ref custom) = self.settings.custom_encoder_settings {
940            set_reported(
941                &schema,
942                settings,
943                "video_encoder",
944                "x264opts",
945                PropertyValue::String(custom.clone()),
946                self.settings.configuration_mode,
947                report,
948            )?;
949        }
950        Ok(())
951    }
952}
953
954#[cfg(test)]
955mod policy_tests {
956    use super::*;
957
958    #[test]
959    fn start_fallback_is_conservative_about_destination_failures() {
960        for message in [
961            "invalid output path",
962            "permission denied opening file",
963            "failed to connect to server",
964            "authentication failed",
965            "invalid stream key",
966        ] {
967            assert!(!start_failure_allows_encoder_fallback(
968                &ObsError::OutputStartFailure(Some(message.into()))
969            ));
970        }
971    }
972
973    #[test]
974    fn start_fallback_accepts_backend_initialization_failures() {
975        for message in [
976            "NVENC encoder failed to initialize",
977            "QSV encoder unavailable",
978            "AMF encoder initialization failed",
979            "video encoder could not start",
980        ] {
981            assert!(start_failure_allows_encoder_fallback(
982                &ObsError::OutputStartFailure(Some(message.into()))
983            ));
984        }
985    }
986
987    #[test]
988    fn unrelated_errors_do_not_trigger_creation_fallback() {
989        assert!(creation_failure_allows_fallback(&ObsError::NullPointer(
990            None
991        )));
992        assert!(!creation_failure_allows_fallback(
993            &ObsError::InvalidOperation("bad destination".into())
994        ));
995    }
996}