impl CameraCapture {
    #[allow(dead_code)] // helper kept for future heuristics
    #[cfg(not(coverage))]
    fn pick_encoder() -> (&'static str, &'static str) {
        let encoders = &[
            ("nvh264enc", "video/x-raw(memory:NVMM),format=NV12"),
            ("nvautogpuh264enc", "video/x-raw,format=NV12"),
            ("vulkanh264enc", "video/x-raw(memory:VulkanImage),format=NV12"),
            ("vah264enc", "video/x-raw,format=NV12"),
            ("vaapih264enc", "video/x-raw,format=NV12"),
            ("v4l2h264enc", "video/x-raw"), // RPi, Jetson, etc.
        ];
        for (name, caps) in encoders {
            if gst::ElementFactory::find(name).is_some() {
                return (name, caps);
            }
        }
        if Self::software_video_fallback_allowed() {
            return ("x264enc", "video/x-raw");
        }
        ("missing-hardware-h264enc", "video/x-raw")
    }

    #[cfg(coverage)]
    fn pick_encoder() -> (&'static str, &'static str) {
        ("x264enc", "video/x-raw")
    }

    #[cfg(not(coverage))]
    fn choose_encoder() -> anyhow::Result<(&'static str, Option<&'static str>)> {
        if buildable_encoder("nvh264enc") {
            return Ok((
                "nvh264enc",
                supported_encoder_property(
                    "nvh264enc",
                    &["iframeinterval", "idrinterval", "gop-size"],
                ),
            ));
        }
        if buildable_encoder("nvautogpuh264enc") {
            return Ok((
                "nvautogpuh264enc",
                supported_encoder_property(
                    "nvautogpuh264enc",
                    &["iframeinterval", "idrinterval", "gop-size"],
                ),
            ));
        }
        if buildable_encoder("vulkanh264enc") {
            return Ok((
                "vulkanh264enc",
                supported_encoder_property("vulkanh264enc", &["idr-period"]),
            ));
        }
        if buildable_encoder("vah264enc") {
            return Ok((
                "vah264enc",
                supported_encoder_property("vah264enc", &["key-int-max", "keyframe-period"]),
            ));
        }
        if buildable_encoder("vaapih264enc") {
            return Ok((
                "vaapih264enc",
                supported_encoder_property("vaapih264enc", &["keyframe-period"]),
            ));
        }
        if buildable_encoder("v4l2h264enc") {
            return Ok((
                "v4l2h264enc",
                supported_encoder_property("v4l2h264enc", &["idrcount"]),
            ));
        }
        if Self::software_video_fallback_allowed() {
            return Ok(("x264enc", Some("key-int-max")));
        }
        anyhow::bail!(
            "hardware H.264 encoder required, but no buildable NVIDIA/Vulkan/VAAPI/V4L2 encoder was found"
        )
    }

    #[cfg(coverage)]
    fn choose_encoder() -> anyhow::Result<(&'static str, Option<&'static str>)> {
        Ok(match std::env::var("LESAVKA_CAM_TEST_ENCODER")
            .ok()
            .as_deref()
            .map(str::trim)
        {
            Some("nvh264enc") => ("nvh264enc", None),
            Some("nvautogpuh264enc") => ("nvautogpuh264enc", None),
            Some("vulkanh264enc") => ("vulkanh264enc", Some("idr-period")),
            Some("vah264enc") => ("vah264enc", Some("keyframe-period")),
            Some("vaapih264enc") => ("vaapih264enc", Some("keyframe-period")),
            Some("v4l2h264enc") => ("v4l2h264enc", Some("idrcount")),
            _ => ("x264enc", Some("key-int-max")),
        })
    }

    #[cfg(not(coverage))]
    /// Select the lowest-latency HEVC encoder available on this client.
    ///
    /// Inputs: installed GStreamer encoder factories and their supported
    /// keyframe properties. Output: the chosen encoder element plus the
    /// property used to keep keyframes frequent. Why: transport freshness
    /// improves only if HEVC is encoded in a live-call shape instead of a
    /// throughput-oriented offline encode shape.
    fn choose_hevc_encoder() -> anyhow::Result<(&'static str, Option<&'static str>)> {
        for (name, keyframe_props) in [
            ("nvh265enc", &["iframeinterval", "idrinterval", "gop-size"][..]),
            (
                "nvautogpuh265enc",
                &["iframeinterval", "idrinterval", "gop-size"][..],
            ),
            ("vah265enc", &["key-int-max", "keyframe-period"][..]),
            ("vaapih265enc", &["keyframe-period"][..]),
            ("v4l2h265enc", &["idrcount"][..]),
        ] {
            if buildable_encoder(name) {
                return Ok((name, supported_encoder_property(name, keyframe_props)));
            }
        }
        if Self::software_video_fallback_allowed() {
            return Ok(("x265enc", Some("key-int-max")));
        }
        anyhow::bail!(
            "hardware HEVC encoder required, but no GStreamer HEVC hardware encoder was found and FFmpeg hevc_nvenc was not selected"
        )
    }

    #[cfg(coverage)]
    /// Return a stable HEVC encoder choice for coverage builds.
    ///
    /// Inputs: none. Output: the software encoder contract used by tests. Why:
    /// coverage builds should exercise deterministic string construction
    /// without depending on workstation-specific hardware encoders.
    fn choose_hevc_encoder() -> anyhow::Result<(&'static str, Option<&'static str>)> {
        Ok(("x265enc", Some("key-int-max")))
    }

    #[cfg(not(coverage))]
    fn software_video_fallback_allowed() -> bool {
        std::env::var("LESAVKA_ALLOW_SOFTWARE_VIDEO")
            .ok()
            .is_some_and(|value| {
                let trimmed = value.trim();
                !(trimmed.is_empty()
                    || trimmed.eq_ignore_ascii_case("0")
                    || trimmed.eq_ignore_ascii_case("false")
                    || trimmed.eq_ignore_ascii_case("no")
                    || trimmed.eq_ignore_ascii_case("off"))
            })
    }

    #[cfg(coverage)]
    fn software_video_fallback_allowed() -> bool {
        true
    }

    #[cfg(not(coverage))]
    fn ffmpeg_hevc_nvenc_available() -> bool {
        if !Path::new("/dev/nvidiactl").exists() {
            return false;
        }
        Command::new("ffmpeg")
            .args([
                "-hide_banner",
                "-loglevel",
                "error",
                "-f",
                "lavfi",
                "-i",
                "color=c=black:s=128x128:r=1",
                "-frames:v",
                "1",
                "-an",
                "-pix_fmt",
                "nv12",
                "-c:v",
                "hevc_nvenc",
                "-f",
                "null",
                "-",
            ])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|status| status.success())
    }

    #[cfg(not(coverage))]
    fn should_use_ffmpeg_hevc_nvenc() -> bool {
        let requested = std::env::var("LESAVKA_CAM_HEVC_ENCODER")
            .or_else(|_| std::env::var("LESAVKA_LOCAL_HEVC_ENCODER"))
            .ok()
            .map(|value| value.trim().to_ascii_lowercase());
        match requested.as_deref() {
            Some("ffmpeg_hevc_nvenc" | "hevc_nvenc" | "nvenc") => {
                Self::ffmpeg_hevc_nvenc_available()
            }
            Some("gstreamer" | "gst") => false,
            _ => Self::ffmpeg_hevc_nvenc_available(),
        }
    }

    fn encoder_options(
        enc: &'static str,
        kf_prop: Option<&'static str>,
        keyframe_interval: u32,
    ) -> String {
        if enc == "x264enc" {
            let bitrate_kbit = env_u32("LESAVKA_CAM_H264_KBIT", 4500);
            let keyframe_opt = kf_prop
                .map(|property| format!(" {property}={keyframe_interval}"))
                .unwrap_or_default();
            format!(
                "{enc} tune=zerolatency speed-preset=faster bitrate={bitrate_kbit}{keyframe_opt}"
            )
        } else if enc == "vulkanh264enc" {
            let bitrate_kbit = env_u32("LESAVKA_CAM_H264_KBIT", 4500);
            let keyframe_opt = kf_prop
                .map(|property| format!(" {property}={keyframe_interval}"))
                .unwrap_or_default();
            format!("{enc} bitrate={bitrate_kbit} rate-control=cbr{keyframe_opt}")
        } else if enc == "x265enc" {
            let bitrate_kbit = env_u32("LESAVKA_CAM_HEVC_KBIT", 3000);
            let keyframe_opt = kf_prop
                .map(|property| format!(" {property}={keyframe_interval}"))
                .unwrap_or_default();
            format!(
                "{enc} tune=zerolatency speed-preset=ultrafast bitrate={bitrate_kbit}{keyframe_opt}"
            )
        } else if let Some(property) = kf_prop {
            format!("{enc} {property}={keyframe_interval}")
        } else {
            enc.to_string()
        }
    }

}
