crabcamera 0.9.2

Advanced cross-platform camera integration for Tauri applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Tauri commands for video recording
//!
//! These commands provide an interface for recording video from cameras.

use std::collections::HashMap;
use std::sync::{Arc, LazyLock, Mutex as SyncMutex};
use tauri::command;
use tokio::sync::RwLock;

#[cfg(feature = "audio")]
use crate::constants::{AUDIO_BITRATE, AUDIO_CHANNELS, AUDIO_DEVICE_DEFAULT, AUDIO_SAMPLE_RATE};
use crate::constants::{
    DEFAULT_CAMERA_ID, RECORDING_QUALITY_PRESET_1080P, RECORDING_QUALITY_PRESET_4K,
    RECORDING_QUALITY_PRESET_720P, RECORDING_QUALITY_PRESET_HIGH, RECORDING_QUALITY_PRESET_LOW,
    RECORDING_QUALITY_PRESET_MEDIUM, RECORDING_SESSION_PREFIX,
};
use crate::platform::PlatformCamera;
use crate::recording::{Recorder, RecordingConfig, RecordingQuality, RecordingStats};
use crate::types::CameraFormat;

// Global recorder registry
type RecorderRegistry = LazyLock<Arc<RwLock<HashMap<String, Arc<SyncMutex<RecordingSession>>>>>>;

static RECORDER_REGISTRY: RecorderRegistry =
    LazyLock::new(|| Arc::new(RwLock::new(HashMap::new())));

/// Active recording session combining camera and recorder
struct RecordingSession {
    recorder: Option<Recorder>,
    camera: Arc<SyncMutex<PlatformCamera>>,
    is_running: bool,
}

/// Options for [`start_recording`].
///
/// Grouped into a single struct so the Tauri command takes one argument
/// (satisfying clippy's `too_many_arguments` limit); the JS `invoke` call
/// passes a single options object.
pub struct RecordingStartOptions {
    /// Camera device ID (or `None` for the default camera).
    pub device_id: Option<String>,
    /// Path to save the MP4 file.
    pub output_path: String,
    /// Video width in pixels.
    pub width: u32,
    /// Video height in pixels.
    pub height: u32,
    /// Target frame rate.
    pub fps: f64,
    /// Recording quality preset (optional).
    pub quality: Option<String>,
    /// Metadata title (optional).
    pub title: Option<String>,
    /// Audio device ID for recording (optional, enables audio when provided).
    #[cfg(feature = "audio")]
    pub audio_device_id: Option<String>,
}

/// Start recording from a camera to a file
///
/// # Arguments
/// * `options` - Recording configuration (see [`RecordingStartOptions`])
///
/// # Returns
/// * Session ID for tracking the recording
///
/// # Errors
/// Returns an `Err` if the camera cannot be initialized or its stream cannot
/// be started, if the camera mutex is poisoned, or if the [`Recorder`] cannot
/// be created.
#[command]
pub async fn start_recording(options: RecordingStartOptions) -> Result<String, String> {
    let RecordingStartOptions {
        device_id,
        output_path,
        width,
        height,
        fps,
        quality,
        title,
        #[cfg(feature = "audio")]
        audio_device_id,
    } = options;
    let camera_id = device_id.unwrap_or_else(|| DEFAULT_CAMERA_ID.to_string());

    #[cfg(feature = "audio")]
    {
        if let Some(ref audio_id) = audio_device_id {
            log::info!(
                "Starting recording from camera {camera_id} with audio {audio_id} to {output_path}"
            );
        } else {
            log::info!("Starting recording from camera {camera_id} (no audio) to {output_path}");
        }
    }
    #[cfg(not(feature = "audio"))]
    log::info!(
        "Starting recording from camera {} to {}",
        camera_id,
        output_path
    );

    // Parse quality preset
    let recording_quality = match quality.as_deref() {
        Some(q) if q == RECORDING_QUALITY_PRESET_LOW || q == RECORDING_QUALITY_PRESET_720P => {
            Some(RecordingQuality::Low)
        }
        Some(q) if q == RECORDING_QUALITY_PRESET_MEDIUM || q == RECORDING_QUALITY_PRESET_1080P => {
            Some(RecordingQuality::Medium)
        }
        Some(q) if q == RECORDING_QUALITY_PRESET_HIGH || q == RECORDING_QUALITY_PRESET_4K => {
            Some(RecordingQuality::High)
        }
        _ => None,
    };

    // Build recording config
    let mut config = if let Some(q) = recording_quality {
        RecordingConfig::from_quality_with_fps(q, fps)
    } else {
        RecordingConfig::new(width, height, fps)
    };

    if let Some(t) = title {
        config = config.with_title(t);
    }

    // Add audio configuration if audio device specified
    // Per #TauriAudioCommands: ! start_recording_accepts_audio_device_option
    #[cfg(feature = "audio")]
    if let Some(audio_id) = audio_device_id {
        config = config.with_audio(crate::recording::AudioConfig {
            device_id: if audio_id == AUDIO_DEVICE_DEFAULT {
                None
            } else {
                Some(audio_id)
            },
            sample_rate: AUDIO_SAMPLE_RATE,
            channels: AUDIO_CHANNELS,
            bitrate: AUDIO_BITRATE,
        });
    }

    // Initialize camera
    #[allow(clippy::cast_possible_truncation)]
    // f64→f32: fps values (typically ≤ 240) are exact in f32
    let fps_f32 = fps as f32;
    let camera = super::capture::get_or_create_camera(
        camera_id.clone(),
        CameraFormat::new(config.width, config.height, fps_f32),
    )
    .await
    .map_err(|e| format!("Failed to initialize camera: {e}"))?;

    // Start camera stream
    {
        let mut cam = camera
            .lock()
            .map_err(|_| "Camera mutex poisoned".to_string())?;
        cam.start_stream()
            .map_err(|e| format!("Failed to start camera stream: {e}"))?;
    }

    // Create recorder
    let recorder = Recorder::new(&output_path, config)
        .map_err(|e| format!("Failed to create recorder: {e}"))?;

    // Generate session ID
    let session_id = format!(
        "{}{}",
        RECORDING_SESSION_PREFIX,
        chrono::Utc::now().timestamp_millis()
    );

    // Store session
    let session = RecordingSession {
        recorder: Some(recorder),
        camera,
        is_running: true,
    };

    {
        let mut registry = RECORDER_REGISTRY.write().await;
        registry.insert(session_id.clone(), Arc::new(SyncMutex::new(session)));
    }

    log::info!("Recording started: session {session_id}");
    Ok(session_id)
}

/// Write frames from the camera to the recording
///
/// This should be called repeatedly to capture frames.
/// Returns the number of frames recorded so far.
///
/// # Errors
/// Returns an `Err` if the recording session is not found, if the session or
/// camera mutex is poisoned, if recording is not running, if the camera frame
/// capture fails, if no recorder is available, or if writing the frame fails.
#[command]
pub async fn record_frame(session_id: String) -> Result<u64, String> {
    let session_arc = {
        let registry = RECORDER_REGISTRY.read().await;
        registry
            .get(&session_id)
            .cloned()
            .ok_or_else(|| format!("Recording session not found: {session_id}"))?
    };

    let mut session = session_arc
        .lock()
        .map_err(|_| "Mutex poisoned".to_string())?;

    if !session.is_running {
        return Err("Recording is not running".to_string());
    }

    // Capture frame from camera
    let frame = {
        let mut camera = session
            .camera
            .lock()
            .map_err(|_| "Mutex poisoned".to_string())?;
        camera
            .capture_frame()
            .map_err(|e| format!("Failed to capture frame: {e}"))?
    };

    // Write to recorder
    let recorder = session
        .recorder
        .as_mut()
        .ok_or_else(|| "Recorder not available".to_string())?;
    recorder
        .write_frame(&frame)
        .map_err(|e| format!("Failed to write frame: {e}"))?;

    Ok(recorder.frame_count())
}

/// Stop recording and finalize the file
///
/// # Returns
/// * Recording statistics (frames, duration, file size, etc.)
///
/// # Errors
/// Returns an `Err` if the recording session is not found, if the session or
/// camera mutex is poisoned, if the recorder has already been taken, or if
/// finalizing the recording fails.
#[command]
pub async fn stop_recording(session_id: String) -> Result<RecordingStats, String> {
    // Remove session from registry
    let session_arc = {
        let mut registry = RECORDER_REGISTRY.write().await;
        registry
            .remove(&session_id)
            .ok_or_else(|| format!("Recording session not found: {session_id}"))?
    };

    // Get exclusive access and stop
    let mut session = session_arc
        .lock()
        .map_err(|_| "Mutex poisoned".to_string())?;

    // Stop camera stream
    {
        let mut camera = session
            .camera
            .lock()
            .map_err(|_| "Camera mutex poisoned".to_string())?;
        let _ = camera.stop_stream();
    }

    // Finish recording
    let stats = session
        .recorder
        .take()
        .ok_or_else(|| "Recorder already taken".to_string())?
        .finish()
        .map_err(|e| format!("Failed to finalize recording: {e}"))?;

    log::info!(
        "Recording stopped: {} frames, {:.2}s, {} bytes",
        stats.video_frames,
        stats.duration_secs,
        stats.bytes_written
    );

    Ok(stats)
}

/// Get the status of an active recording
///
/// # Errors
/// Returns an `Err` if the recording session is not found, or if the session
/// or camera mutex is poisoned, or if no recorder is available.
#[command]
pub async fn get_recording_status(session_id: String) -> Result<RecordingStatus, String> {
    let session_arc = {
        let registry = RECORDER_REGISTRY.read().await;
        registry
            .get(&session_id)
            .cloned()
            .ok_or_else(|| format!("Recording session not found: {session_id}"))?
    };

    let session = session_arc
        .lock()
        .map_err(|_| "Mutex poisoned".to_string())?;

    let recorder = session
        .recorder
        .as_ref()
        .ok_or_else(|| "Recorder not available".to_string())?;

    // Build audio status if audio feature enabled
    #[cfg(feature = "audio")]
    let audio_status = if recorder.audio_enabled() {
        Some(AudioStatus {
            enabled: true,
            failed: recorder.audio_failed(),
        })
    } else {
        None
    };

    Ok(RecordingStatus {
        session_id,
        is_running: session.is_running,
        frame_count: recorder.frame_count(),
        dropped_frames: recorder.dropped_frames(),
        duration_secs: recorder.duration(),
        #[cfg(feature = "audio")]
        audio_status,
    })
}

/// List all active recording sessions
///
/// # Errors
/// This function always succeeds and never returns an `Err`.
#[command]
pub async fn list_recording_sessions() -> Result<Vec<String>, String> {
    let registry = RECORDER_REGISTRY.read().await;
    Ok(registry.keys().cloned().collect())
}

/// Recording status information
/// Per #`AudioErrorRecovery`: ! `session_status_reflects_audio_state`
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecordingStatus {
    /// Unique identifier for the recording session.
    pub session_id: String,
    /// Whether the recording is actively capturing.
    pub is_running: bool,
    /// Total video frames successfully encoded.
    pub frame_count: u64,
    /// Frames dropped due to performance issues.
    pub dropped_frames: u64,
    /// Duration of the recording in seconds.
    pub duration_secs: f64,
    /// Audio recording status (None if audio not enabled)
    #[cfg(feature = "audio")]
    pub audio_status: Option<AudioStatus>,
}

/// Audio status within a recording session
/// Per #`AudioErrorRecovery`: ! `session_status_reflects_audio_state`
#[cfg(feature = "audio")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AudioStatus {
    /// Whether audio recording is enabled
    pub enabled: bool,
    /// Whether audio capture has failed
    pub failed: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_recording_status_serialization() {
        let status = RecordingStatus {
            session_id: "test_123".to_string(),
            is_running: true,
            frame_count: 100,
            dropped_frames: 2,
            duration_secs: 3.33,
            #[cfg(feature = "audio")]
            audio_status: Some(AudioStatus {
                enabled: true,
                failed: false,
            }),
        };

        let json = serde_json::to_string(&status).expect("serialize recording status");
        assert!(json.contains("test_123"));
        assert!(json.contains("100"));
        // JSON serialization uses camelCase for frontend compatibility
        #[cfg(feature = "audio")]
        {
            assert!(json.contains("audioStatus"));
        }
    }

    #[tokio::test]
    async fn test_write_frame_to_missing_session_returns_error() {
        let result = record_frame("nonexistent_session_xyz".to_string()).await;
        assert!(result.is_err());
        let msg = result.expect_err("missing session error expected");
        assert!(
            msg.contains("nonexistent_session_xyz"),
            "error should identify the missing session, got: {msg}"
        );
    }

    #[tokio::test]
    async fn test_get_recording_status_missing_session_returns_error() {
        let result = get_recording_status("no_such_session_abc".to_string()).await;
        assert!(result.is_err());
        let msg = result.expect_err("missing session error expected");
        assert!(
            msg.contains("no_such_session_abc"),
            "error should identify the missing session, got: {msg}"
        );
    }

    #[tokio::test]
    async fn test_stop_recording_missing_session_returns_error() {
        let result = stop_recording("ghost_session_999".to_string()).await;
        assert!(result.is_err());
        let msg = result.expect_err("missing session error expected");
        assert!(
            msg.contains("ghost_session_999"),
            "error should identify the missing session, got: {msg}"
        );
    }
}