impl Handler {
    /// Accept synthetic upstream webcam packets without UVC/HDMI hardware.
    async fn stream_camera_rpc(
        &self,
        req: Request<tonic::Streaming<VideoPacket>>,
    ) -> Result<Response<ReceiverStream<Result<Empty, Status>>>, Status> {
        let rpc_id = runtime_support::next_stream_id();
        let cfg = camera::current_camera_config();
        info!(
            rpc_id,
            output = cfg.output.as_str(),
            codec = cfg.codec.as_str(),
            width = cfg.width,
            height = cfg.height,
            fps = cfg.fps,
            hdmi = cfg.hdmi.as_ref().map(|h| h.name.as_str()).unwrap_or("none"),
            "🎥 stream_camera output selected"
        );

        let upstream_lease = self.upstream_media_rt.activate_camera();
        let (camera_session_id, relay, _relay_reused) = self.camera_rt.activate(&cfg).await?;
        let camera_rt = self.camera_rt.clone();
        let upstream_media_rt = self.upstream_media_rt.clone();
        info!(
            rpc_id,
            session_id = upstream_lease.session_id,
            camera_session_id,
            "🎥 stream_camera opened"
        );
        let frame_step_us = (1_000_000u64 / u64::from(cfg.fps.max(1))).max(1);

        let (tx, rx) = tokio::sync::mpsc::channel(1);

        tokio::spawn(async move {
            let mut cleanup = UpstreamStreamCleanup::camera(
                upstream_media_rt.clone(),
                upstream_lease.generation,
                rpc_id,
                upstream_lease.session_id,
                camera_session_id,
            );
            let mut s = req.into_inner();
            let mut pending = std::collections::VecDeque::new();
            let mut inbound_closed = false;
            let stale_drop_budget = upstream_stale_drop_budget();
            let mut startup_video_settled = false;
            'camera_loop: loop {
                if !camera_rt.is_active(camera_session_id)
                    || !upstream_media_rt.is_camera_active(upstream_lease.generation)
                {
                    info!(
                        rpc_id,
                        session_id = upstream_lease.session_id,
                        camera_session_id,
                        "🎥 stream_camera session superseded"
                    );
                    cleanup.mark_superseded();
                    break;
                }
                if !inbound_closed {
                    let next_packet = tokio::select! {
                        packet = s.next() => Some(packet),
                        _ = tokio::time::sleep(Duration::from_millis(50)) => None,
                    };
                    if let Some(next_packet) = next_packet {
                        match next_packet.transpose() {
                            Ok(Some(pkt)) => {
                                enqueue_pending_upstream_video_packet(
                                    &upstream_media_rt,
                                    &mut pending,
                                    pkt,
                                    rpc_id,
                                    upstream_lease.session_id,
                                    camera_session_id,
                                    "poll",
                                );
                            }
                            Ok(None) => inbound_closed = true,
                            Err(err) => {
                                cleanup.mark_aborted();
                                warn!(
                                    rpc_id,
                                    session_id = upstream_lease.session_id,
                                    camera_session_id,
                                    "🎥 stream_camera inbound error before clean EOF: {err}"
                                );
                                break 'camera_loop;
                            }
                        }
                    }
                }
                let Some(mut pkt) = pending.pop_front() else {
                    if inbound_closed {
                        cleanup.mark_closed();
                        break;
                    }
                    continue;
                };
                let plan = match upstream_media_rt.plan_video_pts(pkt.pts, frame_step_us) {
                    lesavka_server::upstream_media_runtime::UpstreamPlanDecision::AwaitingPair => {
                        if inbound_closed {
                            tracing::debug!(
                                rpc_id,
                                session_id = upstream_lease.session_id,
                                camera_session_id,
                                pts = pkt.pts,
                                "🎥 dropping trailing upstream video frame because no paired audio arrived before stream close"
                            );
                            continue;
                        }
                        pending.push_front(pkt);
                        continue;
                    }
                    lesavka_server::upstream_media_runtime::UpstreamPlanDecision::DropBeforeOverlap => {
                        continue;
                    }
                    lesavka_server::upstream_media_runtime::UpstreamPlanDecision::DropStale(reason) => {
                        tracing::warn!(
                            rpc_id,
                            session_id = upstream_lease.session_id,
                            camera_session_id,
                            pts = pkt.pts,
                            reason,
                            "🎥 upstream video frame dropped by authoritative freshness planner"
                        );
                        continue;
                    }
                    lesavka_server::upstream_media_runtime::UpstreamPlanDecision::StartupFailed(reason) => {
                        tracing::error!(
                            rpc_id,
                            session_id = upstream_lease.session_id,
                            camera_session_id,
                            reason,
                            "🎥 upstream video startup failed"
                        );
                        cleanup.mark_aborted();
                        break;
                    }
                    lesavka_server::upstream_media_runtime::UpstreamPlanDecision::Play(plan) => plan,
                };
                let mut audio_master_wait = std::pin::pin!(
                    upstream_media_rt.wait_for_audio_master(plan.local_pts_us, plan.due_at)
                );
                let audio_master_ready = loop {
                    tokio::select! {
                        ready = &mut audio_master_wait => break ready,
                        next_packet = s.next(), if !inbound_closed => {
                            match next_packet.transpose() {
                                Ok(Some(next_pkt)) => {
                                    enqueue_pending_upstream_video_packet(
                                        &upstream_media_rt,
                                        &mut pending,
                                        next_pkt,
                                        rpc_id,
                                        upstream_lease.session_id,
                                        camera_session_id,
                                        "audio-master-wait",
                                    );
                                }
                                Ok(None) => inbound_closed = true,
                                Err(err) => {
                                    cleanup.mark_aborted();
                                    warn!(
                                        rpc_id,
                                        session_id = upstream_lease.session_id,
                                        camera_session_id,
                                        "🎥 stream_camera inbound error while waiting for audio master: {err}"
                                    );
                                    break 'camera_loop;
                                }
                            }
                        }
                    }
                };
                if !audio_master_ready {
                    upstream_media_rt.record_video_freeze(
                        "video froze because audio master did not reach the frame timestamp",
                    );
                    tracing::warn!(
                        rpc_id,
                        session_id = upstream_lease.session_id,
                        camera_session_id,
                        pts = plan.local_pts_us,
                        "🎥 upstream video frame dropped because the audio master never caught up inside the pairing window"
                    );
                    continue;
                }
                if plan.late_by > stale_drop_budget {
                    let coalesced = retain_freshest_video_packet(&mut pending);
                    if startup_video_settled {
                        tracing::warn!(
                            rpc_id,
                            session_id = upstream_lease.session_id,
                            camera_session_id,
                            late_by_ms = plan.late_by.as_millis(),
                            pts = plan.local_pts_us,
                            dropped_pending = coalesced,
                            "🎥 upstream video frame dropped after missing its freshness budget"
                        );
                    } else {
                        tracing::debug!(
                            rpc_id,
                            session_id = upstream_lease.session_id,
                            camera_session_id,
                            late_by_ms = plan.late_by.as_millis(),
                            pts = plan.local_pts_us,
                            dropped_pending = coalesced,
                            "🎥 dropping startup-stale upstream video until the playout window settles"
                        );
                    }
                    continue;
                }
                let sleep_until_due = tokio::time::sleep_until(plan.due_at);
                tokio::pin!(sleep_until_due);
                loop {
                    tokio::select! {
                        _ = &mut sleep_until_due => break,
                        next_packet = s.next(), if !inbound_closed => {
                            match next_packet.transpose() {
                                Ok(Some(next_pkt)) => {
                                    enqueue_pending_upstream_video_packet(
                                        &upstream_media_rt,
                                        &mut pending,
                                        next_pkt,
                                        rpc_id,
                                        upstream_lease.session_id,
                                        camera_session_id,
                                        "due-wait",
                                    );
                                }
                                Ok(None) => inbound_closed = true,
                                Err(err) => {
                                    cleanup.mark_aborted();
                                    warn!(
                                        rpc_id,
                                        session_id = upstream_lease.session_id,
                                        camera_session_id,
                                        "🎥 stream_camera inbound error while waiting for frame due time: {err}"
                                    );
                                    break 'camera_loop;
                                }
                            }
                        }
                    }
                }
                let actual_late_by = tokio::time::Instant::now()
                    .checked_duration_since(plan.due_at)
                    .unwrap_or_default();
                if actual_late_by > stale_drop_budget {
                    tracing::debug!(
                        rpc_id,
                        session_id = upstream_lease.session_id,
                        camera_session_id,
                        late_by_ms = actual_late_by.as_millis(),
                        pts = plan.local_pts_us,
                        "🎥 emitting video after waiting for the audio master to preserve sync"
                    );
                }
                pkt.pts = plan.local_pts_us;
                startup_video_settled = true;
                let presented_pts = pkt.pts;
                relay.feed(pkt); // ← all logging inside video.rs
                upstream_media_rt.mark_video_presented(presented_pts, plan.due_at);
            }
            camera_rt.release_if_active(camera_session_id).await;
            tx.send(Ok(Empty {})).await.ok();
            Ok::<(), Status>(())
        });

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