impl Handler {
    /// Accept synthetic upstream microphone packets without ALSA hardware.
    async fn stream_microphone_rpc(
        &self,
        req: Request<tonic::Streaming<AudioPacket>>,
    ) -> Result<Response<ReceiverStream<Result<Empty, Status>>>, Status> {
        let rpc_id = runtime_support::next_stream_id();
        let lease = self.upstream_media_rt.activate_microphone();
        info!(rpc_id, session_id = lease.session_id, "🎤 stream_microphone opened");
        let Some(microphone_sink_permit) = self
            .upstream_media_rt
            .reserve_microphone_sink(lease.generation)
            .await
        else {
            info!(
                rpc_id,
                session_id = lease.session_id,
                "🎤 stream_microphone stood down before the sink became available"
            );
            self.upstream_media_rt.close_microphone(lease.generation);
            return Err(Status::aborted(
                "microphone stream superseded before sink became available",
            ));
        };
        let uac_dev = std::env::var("LESAVKA_UAC_DEV").unwrap_or_else(|_| "hw:UAC2Gadget,0".into());
        info!(%uac_dev, "🎤 stream_microphone using UAC sink");
        let mut sink = runtime_support::open_voice_with_retry(&uac_dev)
            .await
            .map_err(|e| {
                self.upstream_media_rt.close_microphone(lease.generation);
                Status::internal(format!("{e:#}"))
            })?;

        let (tx, rx) = tokio::sync::mpsc::channel(1);
        let upstream_media_rt = self.upstream_media_rt.clone();

        tokio::spawn(async move {
            let _microphone_sink_permit = microphone_sink_permit;
            let mut cleanup = UpstreamStreamCleanup::microphone(
                upstream_media_rt.clone(),
                lease.generation,
                rpc_id,
                lease.session_id,
            );
            let mut inbound = req.into_inner();
            let mut pending = std::collections::VecDeque::new();
            let mut inbound_closed = false;
            let stale_drop_budget = upstream_stale_drop_budget();
            static CNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

            'microphone_loop: loop {
                if !upstream_media_rt.is_microphone_active(lease.generation) {
                    info!(rpc_id, session_id = lease.session_id, "🎤 stream_microphone session superseded");
                    cleanup.mark_superseded();
                    break;
                }
                if !inbound_closed {
                    let next_packet = tokio::select! {
                        packet = inbound.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)) => {
                                upstream_media_rt.record_client_timing(
                                    UpstreamMediaKind::Microphone,
                                    audio_client_timing(&pkt),
                                );
                                pending.push_back(pkt);
                                let coalesced = retain_freshest_audio_packet(&mut pending);
                                if coalesced > 0 {
                                    tracing::debug!(
                                        rpc_id,
                                        session_id = lease.session_id,
                                        dropped = coalesced,
                                        "🎤 coalesced stale upstream audio backlog down to the freshest chunk"
                                    );
                                }
                            }
                            Ok(None) => inbound_closed = true,
                            Err(err) => {
                                cleanup.mark_aborted();
                                warn!(
                                    rpc_id,
                                    session_id = lease.session_id,
                                    "🎤 stream_microphone inbound error before clean EOF: {err}"
                                );
                                break;
                            }
                        }
                    }
                }
                let Some(mut pkt) = pending.pop_front() else {
                    if inbound_closed {
                        cleanup.mark_closed();
                        break;
                    }
                    continue;
                };
                let plan = match upstream_media_rt.plan_audio_pts(pkt.pts) {
                    lesavka_server::upstream_media_runtime::UpstreamPlanDecision::AwaitingPair => {
                        if inbound_closed {
                            tracing::debug!(
                                rpc_id,
                                session_id = lease.session_id,
                                pts = pkt.pts,
                                "🎤 dropping trailing upstream audio because no paired video 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 = lease.session_id,
                            pts = pkt.pts,
                            reason,
                            "🎤 upstream audio packet dropped by authoritative freshness planner"
                        );
                        continue;
                    }
                    lesavka_server::upstream_media_runtime::UpstreamPlanDecision::StartupFailed(reason) => {
                        tracing::error!(
                            rpc_id,
                            session_id = lease.session_id,
                            reason,
                            "🎤 upstream audio startup failed"
                        );
                        cleanup.mark_aborted();
                        break;
                    }
                    lesavka_server::upstream_media_runtime::UpstreamPlanDecision::Play(plan) => plan,
                };
                if plan.late_by > stale_drop_budget {
                    tracing::warn!(
                        rpc_id,
                        session_id = lease.session_id,
                        late_by_ms = plan.late_by.as_millis(),
                        pts = plan.local_pts_us,
                        "🎤 upstream audio packet dropped after missing its freshness budget"
                    );
                    continue;
                }
                while tokio::time::Instant::now() < plan.due_at {
                    let sleep_until_due = tokio::time::sleep_until(plan.due_at);
                    tokio::pin!(sleep_until_due);
                    tokio::select! {
                        _ = &mut sleep_until_due => break,
                        next_packet = inbound.next(), if !inbound_closed => {
                            match next_packet.transpose() {
                                Ok(Some(next_pkt)) => {
                                    upstream_media_rt.record_client_timing(
                                        UpstreamMediaKind::Microphone,
                                        audio_client_timing(&next_pkt),
                                    );
                                    pending.push_back(next_pkt);
                                    let coalesced = retain_freshest_audio_packet(&mut pending);
                                    if coalesced > 0 {
                                        tracing::debug!(
                                            rpc_id,
                                            session_id = lease.session_id,
                                            dropped = coalesced,
                                            "🎤 coalesced stale upstream audio while waiting for scheduled playout"
                                        );
                                    }
                                }
                                Ok(None) => inbound_closed = true,
                                Err(err) => {
                                    cleanup.mark_aborted();
                                    warn!(
                                        rpc_id,
                                        session_id = lease.session_id,
                                        "🎤 stream_microphone inbound error before clean EOF: {err}"
                                    );
                                    break 'microphone_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::warn!(
                        rpc_id,
                        session_id = lease.session_id,
                        late_by_ms = actual_late_by.as_millis(),
                        pts = plan.local_pts_us,
                        "🎤 upstream audio packet dropped after waking too late for fresh playout"
                    );
                    continue;
                }
                pkt.pts = plan.local_pts_us;
                let n = CNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                if n < 5 || n.is_multiple_of(3_000) {
                    tracing::info!(rpc_id, "🎤⬇ srv  pkt#{n}  {} bytes", pkt.data.len());
                }
                sink.push(&pkt);
                upstream_media_rt.mark_audio_presented(pkt.pts, plan.due_at);
            }
            sink.finish(); // flush on EOS
            let _ = tx.send(Ok(Empty {})).await;
            Ok::<(), Status>(())
        });

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