impl UpstreamMediaRuntime {
    fn plan_pts(
        &self,
        kind: UpstreamMediaKind,
        remote_pts_us: u64,
        min_step_us: u64,
    ) -> UpstreamPlanDecision {
        let mut state = self
            .state
            .lock()
            .expect("upstream media state mutex poisoned");
        let session_id = state.session_id;
        let packet_count = match kind {
            UpstreamMediaKind::Camera => {
                state.camera_packet_count = state.camera_packet_count.saturating_add(1);
                state.camera_packet_count
            }
            UpstreamMediaKind::Microphone => {
                state.microphone_packet_count = state.microphone_packet_count.saturating_add(1);
                state.microphone_packet_count
            }
        };
        update_latest_remote_pts(&mut state, kind, remote_pts_us);
        let mut first_remote_for_kind = match kind {
            UpstreamMediaKind::Camera => {
                let first_slot = &mut state.first_camera_remote_pts_us;
                *first_slot.get_or_insert(remote_pts_us)
            }
            UpstreamMediaKind::Microphone => {
                let first_slot = &mut state.first_microphone_remote_pts_us;
                *first_slot.get_or_insert(remote_pts_us)
            }
        };
        if kind == UpstreamMediaKind::Camera {
            let startup_grace_us = upstream_camera_startup_grace_us();
            if !state.camera_startup_ready
                && (startup_grace_us == 0
                    || remote_pts_us.saturating_sub(first_remote_for_kind) >= startup_grace_us)
            {
                state.camera_startup_ready = true;
                state.first_camera_remote_pts_us = Some(remote_pts_us);
                first_remote_for_kind = remote_pts_us;
            }
        }
        let now = Instant::now();
        let pairing_deadline = *state
            .pairing_anchor_deadline
            .get_or_insert_with(|| now + upstream_playout_delay());
        let playout_delay = upstream_playout_delay();
        let max_live_lag = upstream_max_live_lag();

        if state.session_base_remote_pts_us.is_none() {
            if state.session_started_at.is_some_and(|started_at| {
                now.saturating_duration_since(started_at) > upstream_startup_timeout()
            }) {
                state.phase = UpstreamSyncPhase::Failed;
                state.startup_timeouts = state.startup_timeouts.saturating_add(1);
                state.last_reason =
                    "paired upstream startup did not converge before timeout".to_string();
                return UpstreamPlanDecision::StartupFailed(
                    "paired upstream startup did not converge before timeout",
                );
            }
            if state.first_camera_remote_pts_us.is_some()
                && state.first_microphone_remote_pts_us.is_some()
                && state.camera_startup_ready
            {
                let first_camera_remote_pts_us =
                    state.first_camera_remote_pts_us.unwrap_or_default();
                let first_microphone_remote_pts_us =
                    state.first_microphone_remote_pts_us.unwrap_or_default();
                state.session_base_remote_pts_us =
                    Some(first_camera_remote_pts_us.max(first_microphone_remote_pts_us));
                let overlap_epoch = now + playout_delay;
                state.playout_epoch = Some(overlap_epoch);
                state.pairing_anchor_deadline = Some(overlap_epoch);
                state.phase = UpstreamSyncPhase::Syncing;
                state.last_reason = "fresh audio/video overlap anchor established".to_string();
                if !state.startup_anchor_logged {
                    let startup_delta_us =
                        first_camera_remote_pts_us as i128 - first_microphone_remote_pts_us as i128;
                    info!(
                        session_id,
                        first_camera_remote_pts_us,
                        first_microphone_remote_pts_us,
                        overlap_base_remote_pts_us =
                            state.session_base_remote_pts_us.unwrap_or_default(),
                        startup_delta_us,
                        "upstream media overlap anchors established"
                    );
                    state.startup_anchor_logged = true;
                }
                self.pairing_state_notify.notify_waiters();
            } else if now < pairing_deadline {
                state.phase = UpstreamSyncPhase::Acquiring;
                state.last_reason = "awaiting both upstream media streams".to_string();
                if upstream_timing_trace_enabled()
                    && (packet_count <= 10 || packet_count.is_multiple_of(300))
                {
                    info!(
                        session_id,
                        ?kind,
                        packet_count,
                        remote_pts_us,
                        wait_ms = pairing_deadline.saturating_duration_since(now).as_millis(),
                        "upstream media packet buffered while awaiting the counterpart stream"
                    );
                }
                return UpstreamPlanDecision::AwaitingPair;
            } else if state.first_camera_remote_pts_us.is_some() && !state.camera_startup_ready {
                state.phase = UpstreamSyncPhase::Syncing;
                state.last_reason = "camera startup warm-up is still in progress".to_string();
                if upstream_timing_trace_enabled()
                    && (packet_count <= 10 || packet_count.is_multiple_of(300))
                {
                    info!(
                        session_id,
                        ?kind,
                        packet_count,
                        remote_pts_us,
                        "upstream media packet buffered while camera startup warm-up is still in progress"
                    );
                }
                return UpstreamPlanDecision::AwaitingPair;
            } else if upstream_require_paired_startup() {
                let refreshed = refresh_unpaired_pairing_anchor(
                    &mut state,
                    kind,
                    remote_pts_us,
                    now + playout_delay,
                );
                if refreshed || upstream_timing_trace_enabled() {
                    info!(
                        session_id,
                        ?kind,
                        packet_count,
                        remote_pts_us,
                        refreshed_anchor = refreshed,
                        healing_window_ms = playout_delay.as_millis(),
                        "upstream media pairing window expired; holding one-sided stream for synced startup"
                    );
                }
                state.phase = UpstreamSyncPhase::Syncing;
                state.last_reason = "holding one-sided stream for synced startup".to_string();
                return UpstreamPlanDecision::AwaitingPair;
            } else {
                let single_stream_base_remote_pts_us = match kind {
                    UpstreamMediaKind::Camera => {
                        state.first_camera_remote_pts_us.unwrap_or(remote_pts_us)
                    }
                    UpstreamMediaKind::Microphone => state
                        .first_microphone_remote_pts_us
                        .unwrap_or(remote_pts_us),
                };
                state.session_base_remote_pts_us = Some(single_stream_base_remote_pts_us);
                let one_sided_epoch = now + playout_delay;
                state.playout_epoch = Some(one_sided_epoch);
                state.pairing_anchor_deadline = Some(one_sided_epoch);
                info!(
                    session_id,
                    ?kind,
                    single_stream_base_remote_pts_us,
                    "upstream media pairing window expired; continuing with one-sided playout"
                );
                self.pairing_state_notify.notify_waiters();
            }
        }

        let session_base_remote_pts_us = state.session_base_remote_pts_us.unwrap_or(remote_pts_us);
        if remote_pts_us < session_base_remote_pts_us {
            if upstream_timing_trace_enabled()
                && (packet_count <= 10 || packet_count.is_multiple_of(300))
            {
                info!(
                    session_id,
                    ?kind,
                    packet_count,
                    remote_pts_us,
                    session_base_remote_pts_us,
                    "upstream media packet dropped before the shared overlap base"
                );
            }
            return UpstreamPlanDecision::DropBeforeOverlap;
        }

        let source_lag = source_lag_for_kind(&state, kind, remote_pts_us);
        if source_lag > max_live_lag {
            match kind {
                UpstreamMediaKind::Camera => {
                    state.stale_video_drops = state.stale_video_drops.saturating_add(1);
                    state.video_freezes = state.video_freezes.saturating_add(1);
                    state.last_reason = "dropped stale video beyond max live lag".to_string();
                }
                UpstreamMediaKind::Microphone => {
                    state.stale_audio_drops = state.stale_audio_drops.saturating_add(1);
                    state.last_reason = "dropped stale audio beyond max live lag".to_string();
                }
            }
            state.phase = UpstreamSyncPhase::Healing;
            return UpstreamPlanDecision::DropStale("packet exceeded max live lag");
        }

        let mut local_pts_us = remote_pts_us.saturating_sub(session_base_remote_pts_us);
        let last_slot = match kind {
            UpstreamMediaKind::Camera => &mut state.last_video_local_pts_us,
            UpstreamMediaKind::Microphone => &mut state.last_audio_local_pts_us,
        };
        if let Some(last_pts_us) = *last_slot
            && local_pts_us <= last_pts_us
        {
            local_pts_us = last_pts_us.saturating_add(min_step_us.max(1));
        }
        *last_slot = Some(local_pts_us);
        let audio_ahead_video_allowance_us = self.audio_ahead_video_allowance_us();
        if kind == UpstreamMediaKind::Camera
            && state
                .last_audio_presented_pts_us
                .is_some_and(|audio_pts_us| {
                    video_is_too_far_behind_audio(
                        local_pts_us,
                        audio_pts_us,
                        audio_ahead_video_allowance_us,
                    )
                })
        {
            state.skew_video_drops = state.skew_video_drops.saturating_add(1);
            state.video_freezes = state.video_freezes.saturating_add(1);
            state.phase = UpstreamSyncPhase::Healing;
            state.last_reason =
                "dropped video frame that was too far behind the audio master".to_string();
            return UpstreamPlanDecision::DropStale("video frame was too far behind audio master");
        }
        let epoch = *state.playout_epoch.get_or_insert(pairing_deadline);
        let sink_offset_us = self.playout_offset_us(kind);
        let playout_delay = upstream_playout_delay().min(max_live_lag);
        let mut due_at =
            apply_playout_offset(epoch + Duration::from_micros(local_pts_us), sink_offset_us);
        let mut late_by = now.checked_duration_since(due_at).unwrap_or_default();
        let reanchor_threshold = upstream_reanchor_late_threshold(playout_delay);
        let intentional_future_wait_allowance =
            Duration::from_micros(self.intentional_future_wait_allowance_us(kind));
        let max_future_wait = max_live_lag
            .saturating_sub(source_lag)
            .saturating_add(intentional_future_wait_allowance);
        let due_future_wait = due_at.saturating_duration_since(now);
        if late_by > reanchor_threshold || due_future_wait > max_future_wait {
            let old_late_by = late_by;
            let old_future_wait = due_future_wait;
            let desired_delay = playout_delay.min(max_future_wait);
            let desired_due_at = now + desired_delay;
            let unoffset_due_at = apply_playout_offset(desired_due_at, -sink_offset_us);
            let recovered_epoch = unoffset_due_at
                .checked_sub(Duration::from_micros(local_pts_us))
                .unwrap_or(unoffset_due_at);
            state.playout_epoch = Some(recovered_epoch);
            state.pairing_anchor_deadline = Some(desired_due_at);
            state.freshness_reanchors = state.freshness_reanchors.saturating_add(1);
            state.phase = UpstreamSyncPhase::Healing;
            state.last_reason = "reanchored upstream playhead to preserve freshness".to_string();
            due_at = apply_playout_offset(
                recovered_epoch + Duration::from_micros(local_pts_us),
                sink_offset_us,
            );
            late_by = now.checked_duration_since(due_at).unwrap_or_default();
            info!(
                session_id,
                ?kind,
                packet_count,
                local_pts_us,
                remote_pts_us,
                old_late_by_ms = old_late_by.as_millis(),
                old_future_wait_ms = old_future_wait.as_millis(),
                recovery_buffer_ms = playout_delay.as_millis(),
                reanchor_threshold_ms = reanchor_threshold.as_millis(),
                max_live_lag_ms = max_live_lag.as_millis(),
                source_lag_ms = source_lag.as_millis(),
                "upstream media playhead reanchored to preserve freshness"
            );
        }
        let predicted_lag_at_playout =
            source_lag.saturating_add(due_at.saturating_duration_since(now));
        if predicted_lag_at_playout > max_live_lag.saturating_add(intentional_future_wait_allowance)
        {
            match kind {
                UpstreamMediaKind::Camera => {
                    state.stale_video_drops = state.stale_video_drops.saturating_add(1);
                    state.video_freezes = state.video_freezes.saturating_add(1);
                    state.last_reason =
                        "dropped video that would exceed max live lag at playout".to_string();
                }
                UpstreamMediaKind::Microphone => {
                    state.stale_audio_drops = state.stale_audio_drops.saturating_add(1);
                    state.last_reason =
                        "dropped audio that would exceed max live lag at playout".to_string();
                }
            }
            state.phase = UpstreamSyncPhase::Healing;
            return UpstreamPlanDecision::DropStale("packet would exceed max live lag at playout");
        }
        if upstream_timing_trace_enabled()
            && (packet_count <= 10 || packet_count.is_multiple_of(300))
        {
            let playout_delay_us = due_at.saturating_duration_since(now).as_micros();
            let late_by_us = late_by.as_micros();
            info!(
                session_id,
                ?kind,
                packet_count,
                remote_pts_us,
                session_base_remote_pts_us,
                first_remote_for_kind,
                remote_elapsed_us = remote_pts_us.saturating_sub(session_base_remote_pts_us),
                local_pts_us,
                playout_delay_us,
                sink_offset_us,
                late_by_us,
                source_lag_us = source_lag.as_micros(),
                "upstream media rebase sample"
            );
        }
        if kind == UpstreamMediaKind::Microphone {
            self.audio_progress_notify.notify_waiters();
        }
        UpstreamPlanDecision::Play(PlannedUpstreamPacket {
            local_pts_us,
            due_at,
            late_by,
            source_lag,
        })
    }
}
