/** * @file CameraViewModel.kt * @brief UI/recording state machine and pose-data buffering for the bowling camera screen. */ package com.example.jnicpp.bowling import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.isActive import kotlinx.coroutines.launch /** * @brief Holds camera/recording UI state so it survives configuration * changes and so the state machine lives outside the Activity. * * This class knows nothing about CameraX or ML Kit APIs directly -- * [BowlingCameraActivity] and [CameraXController] report events into it, * and the UI observes it back out. That keeps this class trivially * unit-testable (no Android camera framework involved). */ class CameraViewModel : ViewModel() { /** @brief The camera screen's overall recording state. */ sealed interface RecordingState { /** @brief No recording in progress or starting. */ data object Idle : RecordingState /** @brief A recording has been requested but hasn't started writing yet. */ data object Starting : RecordingState /** @brief A recording is actively being written. @param elapsedSeconds Seconds elapsed since recording started. */ data class Recording(val elapsedSeconds: Long) : RecordingState } private val _recordingState = MutableStateFlow(RecordingState.Idle) /** @brief Current recording state, observed by the UI to drive button/timer/indicator visibility. */ val recordingState: StateFlow = _recordingState.asStateFlow() // Whether live pose detection/overlay is on. Only meant to change while // recordingState is Idle -- the UI disables the toggle otherwise (see // BowlingCameraActivity#renderRecordingState) since the recording // pipeline picks its pose mode once at start. private val _poseEnabled = MutableStateFlow(false) /** @brief Whether pose detection/overlay is currently enabled. */ val poseEnabled: StateFlow = _poseEnabled.asStateFlow() // Latest per-frame joint angles, for the overlay's angle-label text now // and for frame-by-frame swing analysis/logging later. Null whenever // there's no current pose result to derive them from (pose off, no // frame processed yet, or a frame with no landmarks that met the // confidence bar -- see PoseAngleCalculator). private val _poseAngles = MutableStateFlow(null) /** @brief Joint angles computed for the most recent analyzed frame, or null if none available. */ val poseAngles: StateFlow = _poseAngles.asStateFlow() // Time-ordered pose samples for the current/most recent recording // session, one appended per analyzed frame while actually recording // (see onPoseFrameUpdated) -- a live preview with pose overlay on but // not recording doesn't fill this. Cleared at the start of each new // recording (see onRecordingStarting). Exposed as a read-only snapshot; // StepDetector.detect() consumes it once a recording finishes (see // onRecordingStopped). private val poseFrameBuffer = mutableListOf() /** @brief Time-ordered pose samples buffered for the current/most recent recording session. */ val poseFrames: List get() = poseFrameBuffer // Extra SMA smoothing for ankle/hip landmarks specifically, on top of // PoseLandmarkSmoother's per-frame EMA -- see AnkleHipMovingAverageFilter. // Reset (not replaced) alongside the buffer so a new session's window // doesn't lerp in from the previous one's last few frames. private val ankleHipSmoother = AnkleHipMovingAverageFilter() // Live, incremental step counting for the current recording -- see // LiveStepDetector. Resets itself mid-recording when the bowler holds // a stationary "ready" stance again, so one recording can capture // several practice approaches back to back. private val liveStepDetector = LiveStepDetector() // Steps detected so far in the current attempt (since the last reset, // whether that reset was a new recording starting or the bowler // returning to a stationary stance mid-recording -- see // onPoseFrameUpdated and LiveStepDetector). The UI reads events.size // as the "Step N" counter. Stays populated after recording stops so // the last attempt's count remains visible. private val _stepEvents = MutableStateFlow>(emptyList()) /** @brief Steps detected so far in the current attempt, since the last reset. */ val stepEvents: StateFlow> = _stepEvents.asStateFlow() private val _permissionsGranted = MutableStateFlow(false) /** @brief Whether all required camera/microphone/storage permissions are currently granted. */ val permissionsGranted: StateFlow = _permissionsGranted.asStateFlow() // One-shot user-facing error messages (camera unavailable, detector // failure, storage failure, ...). SharedFlow, not StateFlow, so the same // error doesn't get replayed and re-shown after a config change. private val _errorEvents = MutableSharedFlow(extraBufferCapacity = 4) /** @brief One-shot user-facing error messages, e.g. for a Toast/Snackbar. */ val errorEvents: SharedFlow = _errorEvents.asSharedFlow() private var timerJob: Job? = null /** * @brief Records the result of a runtime permission request. * @param granted true if all required permissions were granted. */ fun onPermissionsResult(granted: Boolean) { _permissionsGranted.value = granted } /** * @brief Toggles live pose detection/overlay on or off. * @param enabled true to enable pose detection/overlay, false to disable. */ fun onPoseToggled(enabled: Boolean) { _poseEnabled.value = enabled if (!enabled) _poseAngles.value = null } /** * @brief Reports one analyzed frame's landmarks and joint angles. * * Always updates the live angle overlay. Buffering into [poseFrames] * and live step counting are scoped to an actual recording (see * [poseFrames]'s doc), so a preview with pose overlay on but not * recording doesn't silently accumulate frames outside any session. * * @param landmarks EMA-smoothed landmarks for this frame, keyed by ML Kit's `PoseLandmark` type constant. * @param angles Joint angles computed for this same frame. */ fun onPoseFrameUpdated(landmarks: Map, angles: PoseAngles) { _poseAngles.value = angles if (_recordingState.value is RecordingState.Recording) { val smoothedAnkleHip = ankleHipSmoother.smooth(landmarks) val frame = buildPoseFrame( timestampMs = System.currentTimeMillis(), landmarks = landmarks, smoothedAnkleHip = smoothedAnkleHip, angles = angles ) poseFrameBuffer.add(frame) val result = liveStepDetector.update(frame) if (result.wasReset) { _stepEvents.value = emptyList() } if (result.newSteps.isNotEmpty()) { _stepEvents.value = _stepEvents.value + result.newSteps } } } /** @brief Marks a recording as being requested and resets all per-session buffering/detection state. */ fun onRecordingStarting() { _recordingState.value = RecordingState.Starting poseFrameBuffer.clear() ankleHipSmoother.reset() liveStepDetector.reset() _stepEvents.value = emptyList() } /** @brief Marks a recording as actively writing and starts the elapsed-time timer. */ fun onRecordingStarted() { timerJob?.cancel() timerJob = viewModelScope.launch { var seconds = 0L while (isActive) { _recordingState.value = RecordingState.Recording(seconds) delay(1000) seconds++ } } } /** * @brief Marks the current recording as finished and stops the elapsed-time timer. * * [stepEvents] is left as whatever [LiveStepDetector] had already * counted live -- it already reflects the last in-progress attempt's * steps, and a fresh [StepDetector.detect] batch pass over the whole * buffer here would ignore any mid-recording resets and overcount * across separate attempts. */ fun onRecordingStopped() { timerJob?.cancel() timerJob = null _recordingState.value = RecordingState.Idle } /** * @brief Surfaces a one-shot error message to the UI, and clears a * stuck recording indicator if one was in progress. * * A failed start/stop shouldn't leave the UI stuck showing a recording * indicator that no longer reflects reality. * * @param message Human-readable error message to surface. */ fun postError(message: String) { _errorEvents.tryEmit(message) if (_recordingState.value != RecordingState.Idle) { onRecordingStopped() } } /** @brief Cancels the elapsed-time timer when this ViewModel is destroyed. */ override fun onCleared() { super.onCleared() timerJob?.cancel() } }