impl Handler {
    /// Accept client-bundled webcam and microphone packets on the v2 upstream path.
    async fn stream_webcam_media_rpc(
        &self,
        req: Request<tonic::Streaming<UpstreamMediaBundle>>,
    ) -> Result<Response<ReceiverStream<Result<Empty, Status>>>, Status> {
        let rpc_id = runtime_support::next_stream_id();
        let camera_cfg = camera::current_camera_config();
        let bundled_leases = self.upstream_media_rt.activate_bundled_session();
        let microphone_lease = bundled_leases.microphone;
        let camera_lease = bundled_leases.camera;
        info!(
            rpc_id,
            session_id = camera_lease.session_id,
            camera_generation = camera_lease.generation,
            microphone_generation = microphone_lease.generation,
            output = camera_cfg.output.as_str(),
            codec = camera_cfg.codec.as_str(),
            width = camera_cfg.width,
            height = camera_cfg.height,
            fps = camera_cfg.fps,
            "📦 stream_webcam_media v2 opened"
        );
        let (camera_session_id, relay, _relay_reused) =
            match self.camera_rt.activate(&camera_cfg).await {
                Ok(active) => active,
                Err(err) => {
                    self.upstream_media_rt.close_camera(camera_lease.generation);
                    self.upstream_media_rt.close_microphone(microphone_lease.generation);
                    return Err(err);
                }
            };
        let uac_dev = std::env::var("LESAVKA_UAC_DEV").unwrap_or_else(|_| "hw:UAC2Gadget,0".into());
        let microphone_sink =
            match tokio::time::timeout(
                media_v2_uac_start_timeout(),
                self.upstream_media_rt
                    .reserve_microphone_sink(microphone_lease.generation),
            )
            .await
            {
                Ok(Some(permit)) => match runtime_support::open_voice_with_retry(&uac_dev).await {
                    Ok(sink) => Some((permit, sink)),
                    Err(err) => {
                        warn!(
                            rpc_id,
                            session_id = camera_lease.session_id,
                            "📦⚠️  continuing bundled upstream video without UAC audio; microphone sink failed: {err:#}"
                        );
                        self.upstream_media_rt
                            .close_microphone(microphone_lease.generation);
                        None
                    }
                },
                Ok(None) => {
                    warn!(
                        rpc_id,
                        session_id = camera_lease.session_id,
                        "📦⚠️  continuing bundled upstream video without UAC audio; microphone generation was superseded before sink startup"
                    );
                    None
                }
                Err(_) => {
                    warn!(
                        rpc_id,
                        session_id = camera_lease.session_id,
                        timeout_ms = media_v2_uac_start_timeout().as_millis(),
                        "📦⚠️  continuing bundled upstream video without UAC audio; microphone sink startup timed out"
                    );
                    self.upstream_media_rt
                        .close_microphone(microphone_lease.generation);
                    None
                }
            };
        let audio_enabled = microphone_sink.is_some();
        let camera_rt = self.camera_rt.clone();
        let upstream_media_rt = self.upstream_media_rt.clone();
        let (tx, rx) = tokio::sync::mpsc::channel(1);

        tokio::spawn(async move {
            let mut inbound = req.into_inner();
            let mut last_bundle_session_id = None;
            let mut last_bundle_seq = None;
            let mut waiting_for_hevc_keyframe = false;
            let mut outcome = "aborted";
            let idle_timeout = media_v2_stream_idle_timeout();
            let audio_starvation_heal_after = media_v2_audio_starvation_heal_after();
            let mut audio_starved_since = None;
            let av_skew_heal_after = media_v2_av_skew_heal_after();
            let mut av_skewed_since = None;
            let (mut audio_handoff_tx, audio_worker) =
                if let Some((microphone_sink_permit, sink)) = microphone_sink {
                    let (audio_handoff_tx, audio_handoff_rx) =
                        tokio::sync::mpsc::channel::<MediaV2ScheduledAudio>(32);
                    let audio_rt = upstream_media_rt.clone();
                    let worker = tokio::spawn(async move {
                        let _microphone_sink_permit = microphone_sink_permit;
                        run_media_v2_audio_handoff(audio_handoff_rx, sink, audio_rt).await;
                    });
                    (Some(audio_handoff_tx), Some(worker))
                } else {
                    (None, None)
                };
            // UVC freshness is more important than draining intermediate video
            // frames after a slow sink call. Keep only the newest scheduled
            // frame while the handoff worker is busy.
            let (video_handoff_tx, video_handoff_rx) =
                tokio::sync::watch::channel::<Option<MediaV2ScheduledVideo>>(None);
            let video_worker = tokio::spawn(run_media_v2_video_handoff(
                video_handoff_rx,
                relay.clone(),
                upstream_media_rt.clone(),
                rpc_id,
                camera_lease.session_id,
                camera_session_id,
            ));

            loop {
                let Some(bundle_result) = (match tokio::time::timeout(idle_timeout, inbound.next()).await {
                    Ok(next) => next,
                    Err(_) => {
                        outcome = "idle-timeout";
                        warn!(
                            rpc_id,
                            session_id = camera_lease.session_id,
                            idle_timeout_ms = idle_timeout.as_millis(),
                            "📦 stream_webcam_media v2 idle timeout; closing stale upstream leases"
                        );
                        break;
                    }
                }) else {
                    break;
                };
                let mut bundle = match bundle_result {
                    Ok(bundle) => bundle,
                    Err(err) => {
                        warn!(
                            rpc_id,
                            session_id = camera_lease.session_id,
                            "📦 stream_webcam_media v2 inbound error before clean EOF: {err}"
                        );
                        break;
                    }
                };
                let bundle_arrived_at = tokio::time::Instant::now();
                if !camera_rt.is_active(camera_session_id)
                    || !upstream_media_rt.is_camera_active(camera_lease.generation)
                    || (audio_enabled
                        && !upstream_media_rt.is_microphone_active(microphone_lease.generation))
                {
                    outcome = "superseded";
                    break;
                }
                if !audio_enabled {
                    // UVC video must stay live even when UAC is wedged or being recovered.
                    bundle.audio.clear();
                }
                if last_bundle_session_id.is_some_and(|session_id| session_id != bundle.session_id) {
                    warn!(
                        rpc_id,
                        previous_session_id = last_bundle_session_id.unwrap_or_default(),
                        next_session_id = bundle.session_id,
                        "📦 v2 bundled client session changed; resetting local media clock"
                    );
                    last_bundle_seq = None;
                }
                last_bundle_session_id = Some(bundle.session_id);
                if last_bundle_seq.is_some_and(|seq| bundle.seq <= seq) {
                    warn!(
                        rpc_id,
                        session_id = camera_lease.session_id,
                        client_bundle_session_id = bundle.session_id,
                        bundle_seq = bundle.seq,
                        previous_bundle_seq = last_bundle_seq.unwrap_or_default(),
                        "📦 v2 dropping duplicate/stale bundled packet"
                    );
                    continue;
                }
                last_bundle_seq = Some(bundle.seq);

                let Some(facts) = summarize_media_v2_bundle(&bundle) else {
                    continue;
                };
                if media_v2_audio_starvation_elapsed(
                    audio_enabled,
                    facts,
                    bundle_arrived_at,
                    &mut audio_starved_since,
                    audio_starvation_heal_after,
                ) {
                    let audio_starved_ms = audio_starved_since
                        .map(|since| bundle_arrived_at.saturating_duration_since(since))
                        .unwrap_or_default()
                        .as_millis();
                    warn!(
                        rpc_id,
                        session_id = camera_lease.session_id,
                        client_bundle_session_id = bundle.session_id,
                        bundle_seq = bundle.seq,
                        audio_starved_ms,
                        "📦🩺 v2 bundled microphone starved while video stayed live; retiring upstream audio epoch"
                    );
                    upstream_media_rt.soft_recover_microphone();
                    outcome = "audio-starved";
                    break;
                }
                if media_v2_av_skew_elapsed(
                    facts,
                    bundle_arrived_at,
                    &mut av_skewed_since,
                    av_skew_heal_after,
                ) {
                    let av_skewed_ms = av_skewed_since
                        .map(|since| bundle_arrived_at.saturating_duration_since(since))
                        .unwrap_or_default()
                        .as_millis();
                    warn!(
                        rpc_id,
                        session_id = camera_lease.session_id,
                        client_bundle_session_id = bundle.session_id,
                        bundle_seq = bundle.seq,
                        capture_span_ms = facts.capture_span_us / 1000,
                        av_skewed_ms,
                        "📦🩺 v2 bundled A/V epoch skew stayed impossible; retiring upstream audio epoch"
                    );
                    upstream_media_rt.soft_recover_microphone();
                    outcome = "av-skewed";
                    break;
                }
                if facts.has_audio && facts.has_video && facts.capture_span_us > MEDIA_V2_MAX_MIXED_CAPTURE_SPAN_US {
                    if matches!(camera_cfg.codec, camera::CameraCodec::Hevc) && facts.has_video {
                        waiting_for_hevc_keyframe = true;
                    }
                    warn!(
                        rpc_id,
                        session_id = camera_lease.session_id,
                        client_bundle_session_id = bundle.session_id,
                        bundle_seq = bundle.seq,
                        span_ms = facts.capture_span_us / 1000,
                        "📦 v2 dropping mixed bundle with impossible A/V capture span"
                    );
                    continue;
                }
                for audio in &bundle.audio {
                    upstream_media_rt.record_client_timing(
                        UpstreamMediaKind::Microphone,
                        audio_client_timing(audio),
                    );
                }
                if let Some(video) = bundle.video.as_ref() {
                    upstream_media_rt.record_client_timing(
                        UpstreamMediaKind::Camera,
                        video_client_timing(video),
                    );
                }
                let (video_offset_us, audio_offset_us) = upstream_media_rt.playout_offsets();
                let Some(schedule) = media_v2_handoff_schedule(facts, audio_offset_us, video_offset_us) else {
                    if facts.has_video {
                        if matches!(camera_cfg.codec, camera::CameraCodec::Hevc) {
                            waiting_for_hevc_keyframe = true;
                        }
                        upstream_media_rt.record_video_freeze(
                            "v2 dropped stale bundled A/V before UVC/UAC handoff",
                        );
                    }
                    warn!(
                        rpc_id,
                        session_id = camera_lease.session_id,
                        client_bundle_session_id = bundle.session_id,
                        bundle_seq = bundle.seq,
                        max_queue_age_ms = facts.max_queue_age_ms,
                        "📦 v2 dropping whole bundle because it is already outside the freshness budget"
                    );
                    continue;
                };
                debug!(
                    rpc_id,
                    session_id = camera_lease.session_id,
                    client_bundle_session_id = bundle.session_id,
                    bundle_seq = bundle.seq,
                    max_queue_age_ms = facts.max_queue_age_ms,
                    common_delay_ms = schedule.common_delay.as_millis(),
                    relative_audio_delay_ms = schedule.relative_audio_delay.as_millis(),
                    relative_video_delay_ms = schedule.relative_video_delay.as_millis(),
                    audio_offset_us,
                    video_offset_us,
                    "📦 v2 scheduled bundled UAC/UVC handoff from one capture clock"
                );
                let bundle_epoch = bundle_arrived_at + schedule.common_delay;
                let bundle_base_remote_pts_us = facts.capture_start_us;
                let frame_step_us = media_v2_frame_step_us(camera_cfg.fps);

                if audio_handoff_tx.is_some()
                    && schedule.audio_due_at.is_some()
                    && let Some(scheduled_audio) = prepare_media_v2_audio(
                        &mut bundle.audio,
                        &upstream_media_rt,
                        bundle_base_remote_pts_us,
                        bundle_epoch,
                    )
                    && audio_handoff_tx
                            .as_ref()
                            .expect("checked audio handoff sender")
                            .send(scheduled_audio)
                            .await
                            .is_err()
                {
                    audio_handoff_tx = None;
                    warn!(
                        rpc_id,
                        session_id = camera_lease.session_id,
                        "📦 v2 audio handoff worker stopped while receiving bundled media"
                    );
                    break;
                }
                let hold_video_for_hevc_recovery =
                    media_v2_should_hold_hevc_video_for_recovery(
                        waiting_for_hevc_keyframe,
                        camera_cfg.codec,
                        bundle.video.as_ref(),
                    );
                if hold_video_for_hevc_recovery {
                    upstream_media_rt.record_video_freeze(
                        "v2 held HEVC delta frame until next recovery keyframe",
                    );
                    bundle.video.take();
                }
                let video_recovers_hevc_gap =
                    media_v2_has_hevc_recovery_keyframe(camera_cfg.codec, bundle.video.as_ref());
                let scheduled_video = if schedule.video_due_at.is_some() {
                    prepare_media_v2_video(
                        bundle.video.take(),
                        &upstream_media_rt,
                        bundle_base_remote_pts_us,
                        bundle_epoch,
                        bundle_arrived_at,
                        frame_step_us,
                    )
                } else {
                    None
                };
                if let Some(scheduled_video) = scheduled_video {
                    video_handoff_tx.send_replace(Some(scheduled_video));
                    if video_recovers_hevc_gap {
                        waiting_for_hevc_keyframe = false;
                    }
                } else if matches!(camera_cfg.codec, camera::CameraCodec::Hevc)
                    && facts.has_video
                    && !hold_video_for_hevc_recovery
                {
                    waiting_for_hevc_keyframe = true;
                }
            }

            outcome = if outcome == "aborted" { "closed" } else { outcome };
            drop(audio_handoff_tx);
            drop(video_handoff_tx);
            if let Some(audio_worker) = audio_worker
                && let Err(err) = audio_worker.await
            {
                warn!(
                    rpc_id,
                    session_id = camera_lease.session_id,
                    "📦 v2 audio handoff worker join failed: {err}"
                );
            }
            if let Err(err) = video_worker.await {
                warn!(
                    rpc_id,
                    session_id = camera_lease.session_id,
                    "📦 v2 video handoff worker join failed: {err}"
                );
            }
            upstream_media_rt.close_camera(camera_lease.generation);
            upstream_media_rt.close_microphone(microphone_lease.generation);
            camera_rt.release_if_active(camera_session_id).await;
            info!(
                rpc_id,
                session_id = camera_lease.session_id,
                camera_session_id,
                outcome,
                "📦 stream_webcam_media v2 lifecycle ended"
            );
            tx.send(Ok(Empty {})).await.ok();
            Ok::<(), Status>(())
        });

        Ok(Response::new(ReceiverStream::new(rx)))
    }
}
