diff --git a/apps/kai-sa-cam/src/server/recorder.ts b/apps/kai-sa-cam/src/server/recorder.ts new file mode 100644 index 0000000..23ac3db --- /dev/null +++ b/apps/kai-sa-cam/src/server/recorder.ts @@ -0,0 +1,193 @@ +import { Router, Request, Response } from 'express' +import { spawn, ChildProcess } from 'child_process' +import { existsSync, mkdirSync, renameSync, statSync, unlinkSync } from 'fs' +import { join } from 'path' + +const router = Router() + +// Get config from environment +const MEDIA_DIR = process.env.MEDIA_DIR || '/media' +const CONFIG_DIR = process.env.CONFIG_DIR || '/config' +const GO2RTC_RTSP_URL = process.env.GO2RTC_RTSP_URL || 'rtsp://kai-sa-go2rtc:8554/webcam' +const MAX_RECORDING_MINUTES = parseInt(process.env.MAX_RECORDING_MINUTES || '120', 10) +const DISK_MIN_FREE_GB = parseInt(process.env.DISK_MIN_FREE_GB || '2', 10) + +let recordingProcess: ChildProcess | null = null +let recordingStartTime: number | null = null +let currentRecordingFile: string | null = null + +// Ensure media directory exists +if (!existsSync(MEDIA_DIR)) { + mkdirSync(MEDIA_DIR, { recursive: true }) +} + +function checkDiskSpace(): boolean { + try { + const stats = statSync(MEDIA_DIR) + // Simple check - in production you'd use df + return true + } catch { + return false + } +} + +function generateFilename(ext: string): string { + const now = new Date() + const timestamp = now.toISOString().replace(/[:.]/g, '-').split('T').join('_') + return `recording_${timestamp}.${ext}` +} + +function finalizeRecording(partPath: string | null): void { + if (!partPath) return + if (!existsSync(partPath)) { + console.log('No part file to finalize') + return + } + try { + const stats = statSync(partPath) + if (stats.size < 1024) { + console.error(`Recording file too small (${stats.size} bytes), removing: ${partPath}`) + try { + unlinkSync(partPath) + } catch {} + return + } + const finalPath = partPath.replace(/\.part$/, '.mp4') + renameSync(partPath, finalPath) + console.log(`Recording saved: ${finalPath} (${stats.size} bytes)`) + } catch (e) { + console.error('Failed to finalize recording:', e) + } +} + +// POST /api/recordings/start +router.post('/start', async (req: Request, res: Response) => { + if (recordingProcess) { + return res.status(409).json({ error: 'Enregistrement déjà en cours' }) + } + + if (!checkDiskSpace()) { + return res.status(507).json({ error: 'Espace disque insuffisant' }) + } + + const filename = generateFilename('part') + const filepath = join(MEDIA_DIR, filename) + currentRecordingFile = filepath + recordingStartTime = Date.now() + + // ffmpeg command for recording (video only, no audio in RTSP stream) + const args = [ + '-hide_banner', + '-loglevel', 'warning', + '-rtsp_transport', 'tcp', + '-fflags', '+genpts', + '-use_wallclock_as_timestamps', '1', + '-avoid_negative_ts', 'make_zero', + '-i', GO2RTC_RTSP_URL, + '-c:v', 'libx264', + '-preset', 'ultrafast', + '-tune', 'zerolatency', + '-profile:v', 'baseline', + '-pix_fmt', 'yuv420p', + '-g', '30', + '-an', // no audio + '-f', 'mp4', + '-movflags', '+frag_keyframe+empty_moov+default_base_moof', + '-t', `${MAX_RECORDING_MINUTES * 60}`, + filepath, + ] + + const ffmpegPath = process.env.FFMPEG_PATH || 'ffmpeg' + console.log('Starting ffmpeg with args:', args.join(' ')) + console.log('Working directory:', process.cwd()) + console.log('User:', process.getuid?.() || 'N/A') + recordingProcess = spawn(ffmpegPath, args, { + stdio: ['ignore', 'pipe', 'pipe'], + cwd: process.cwd(), + }) + + recordingProcess.stdout?.on('data', (data) => { + console.log(`ffmpeg stdout: ${data}`) + }) + + recordingProcess.stderr?.on('data', (data) => { + const msg = data.toString() + if (msg.trim()) console.log(`ffmpeg stderr: ${msg}`) + }) + + // Consume stdout/stderr to prevent blocking + recordingProcess.stdout?.resume() + recordingProcess.stderr?.resume() + + recordingProcess.on('close', (code) => { + console.log(`Recording ffmpeg exited with code ${code}`) + const fileToFinalize = currentRecordingFile + // Try to finalize regardless of exit code (SIGINT often gives non-zero) + finalizeRecording(fileToFinalize) + recordingProcess = null + currentRecordingFile = null + recordingStartTime = null + }) + + recordingProcess.on('error', (err) => { + console.error('Recording process error:', err) + const fileToFinalize = currentRecordingFile + finalizeRecording(fileToFinalize) + recordingProcess = null + currentRecordingFile = null + recordingStartTime = null + }) + + res.json({ status: 'started', filename: currentRecordingFile.replace(/\.part$/, '.mp4') }) +}) + +// POST /api/recordings/stop +router.post('/stop', async (req: Request, res: Response) => { + if (!recordingProcess) { + return res.status(409).json({ error: 'Aucun enregistrement en cours' }) + } + + const proc = recordingProcess + const fileToFinalize = currentRecordingFile + + try { + // Try graceful shutdown first + proc.kill('SIGINT') + } catch (e) { + console.error('Error sending SIGINT:', e) + } + + // Wait for process to exit (max 15 seconds) + let waited = 0 + while (recordingProcess && waited < 15000) { + await new Promise(r => setTimeout(r, 100)) + waited += 100 + } + + if (recordingProcess) { + try { + recordingProcess.kill('SIGKILL') + } catch (e) { + console.error('Error sending SIGKILL:', e) + } + await new Promise(r => setTimeout(r, 500)) + recordingProcess = null + currentRecordingFile = null + recordingStartTime = null + finalizeRecording(fileToFinalize) + return res.status(500).json({ error: 'Échec arrêt enregistrement' }) + } + + res.json({ status: 'stopped' }) +}) + +// GET /api/recordings/status +router.get('/status', async (req: Request, res: Response) => { + res.json({ + isRecording: !!recordingProcess, + startTime: recordingStartTime, + currentFile: currentRecordingFile?.replace(/\.part$/, '.mp4'), + }) +}) + +export { router as recorderRouter } \ No newline at end of file