fix: update go2rtc stream url, fix video player layout, correct recording max minutes, attach go2rtc to tunnel network and fix pulse cookie volume
CD — Kai-Sa-Cam Deployment / deploy (push) Successful in 10s
CD — Kai-Sa-Cam Deployment / deploy (push) Successful in 10s
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { VideoPlayer } from "./components/VideoPlayer";
|
||||
import { Controls } from "./components/Controls";
|
||||
import { MediaGallery } from "./components/MediaGallery";
|
||||
@@ -63,21 +63,10 @@ export function App() {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-900 text-white flex flex-col">
|
||||
<header className="bg-gray-800 border-b border-gray-700 px-4 py-3 flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold">Kai-Sa-Cam</h1>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-gray-400">Gain</span>
|
||||
<input
|
||||
type="range"
|
||||
min="0.2"
|
||||
max="5"
|
||||
step="0.1"
|
||||
value={gain}
|
||||
onChange={(e) => setGain(Number(e.target.value))}
|
||||
className="w-32"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<h1 className="text-xl font-semibold flex items-center gap-3">
|
||||
<img src="/logo.png" alt="Logo" className="w-8 h-8 object-contain" />
|
||||
Kai-Sa-Cam
|
||||
</h1>
|
||||
</header>
|
||||
|
||||
<main className="flex-1 flex flex-col">
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
interface VideoPlayerProps {
|
||||
streamUrl: string
|
||||
streamUrl: string;
|
||||
}
|
||||
|
||||
export function VideoPlayer({ streamUrl }: VideoPlayerProps) {
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (iframeRef.current) {
|
||||
iframeRef.current.src = streamUrl
|
||||
iframeRef.current.src = streamUrl;
|
||||
}
|
||||
}, [streamUrl])
|
||||
}, [streamUrl]);
|
||||
|
||||
return (
|
||||
<div className="flex-1 relative bg-black rounded-lg overflow-hidden">
|
||||
<div className="flex-1 min-h-[300px] relative bg-black rounded-lg overflow-hidden flex items-center justify-center">
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={streamUrl}
|
||||
className="w-full h-full border-none"
|
||||
className="w-full h-full border-none absolute inset-0"
|
||||
allow="autoplay; encrypted-media"
|
||||
title="Flux caméra"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,193 +1,221 @@
|
||||
import { Router, Request, Response } from 'express'
|
||||
import { spawn, ChildProcess } from 'child_process'
|
||||
import { existsSync, mkdirSync, renameSync, statSync, unlinkSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
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()
|
||||
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)
|
||||
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
|
||||
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 })
|
||||
mkdirSync(MEDIA_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function checkDiskSpace(): boolean {
|
||||
try {
|
||||
const stats = statSync(MEDIA_DIR)
|
||||
const stats = statSync(MEDIA_DIR);
|
||||
// Simple check - in production you'd use df
|
||||
return true
|
||||
return true;
|
||||
} catch {
|
||||
return false
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function generateFilename(ext: string): string {
|
||||
const now = new Date()
|
||||
const timestamp = now.toISOString().replace(/[:.]/g, '-').split('T').join('_')
|
||||
return `recording_${timestamp}.${ext}`
|
||||
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 (!partPath) return;
|
||||
if (!existsSync(partPath)) {
|
||||
console.log('No part file to finalize')
|
||||
return
|
||||
console.log("No part file to finalize");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const stats = statSync(partPath)
|
||||
const stats = statSync(partPath);
|
||||
if (stats.size < 1024) {
|
||||
console.error(`Recording file too small (${stats.size} bytes), removing: ${partPath}`)
|
||||
console.error(
|
||||
`Recording file too small (${stats.size} bytes), removing: ${partPath}`,
|
||||
);
|
||||
try {
|
||||
unlinkSync(partPath)
|
||||
unlinkSync(partPath);
|
||||
} catch {}
|
||||
return
|
||||
return;
|
||||
}
|
||||
const finalPath = partPath.replace(/\.part$/, '.mp4')
|
||||
renameSync(partPath, finalPath)
|
||||
console.log(`Recording saved: ${finalPath} (${stats.size} bytes)`)
|
||||
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)
|
||||
console.error("Failed to finalize recording:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/recordings/start
|
||||
router.post('/start', async (req: Request, res: Response) => {
|
||||
router.post("/start", async (req: Request, res: Response) => {
|
||||
if (recordingProcess) {
|
||||
return res.status(409).json({ error: 'Enregistrement déjà en cours' })
|
||||
return res.status(409).json({ error: "Enregistrement déjà en cours" });
|
||||
}
|
||||
|
||||
if (!checkDiskSpace()) {
|
||||
return res.status(507).json({ error: 'Espace disque insuffisant' })
|
||||
return res.status(507).json({ error: "Espace disque insuffisant" });
|
||||
}
|
||||
|
||||
const filename = generateFilename('part')
|
||||
const filepath = join(MEDIA_DIR, filename)
|
||||
currentRecordingFile = filepath
|
||||
recordingStartTime = Date.now()
|
||||
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}`,
|
||||
"-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')
|
||||
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'],
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
cwd: process.cwd(),
|
||||
})
|
||||
});
|
||||
|
||||
recordingProcess.stdout?.on('data', (data) => {
|
||||
console.log(`ffmpeg stdout: ${data}`)
|
||||
})
|
||||
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}`)
|
||||
})
|
||||
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.stdout?.resume();
|
||||
recordingProcess.stderr?.resume();
|
||||
|
||||
recordingProcess.on('close', (code) => {
|
||||
console.log(`Recording ffmpeg exited with code ${code}`)
|
||||
const fileToFinalize = currentRecordingFile
|
||||
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
|
||||
})
|
||||
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
|
||||
})
|
||||
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') })
|
||||
})
|
||||
res.json({
|
||||
status: "started",
|
||||
filename: currentRecordingFile.replace(/\.part$/, ".mp4"),
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/recordings/stop
|
||||
router.post('/stop', async (req: Request, res: Response) => {
|
||||
router.post("/stop", async (req: Request, res: Response) => {
|
||||
if (!recordingProcess) {
|
||||
return res.status(409).json({ error: 'Aucun enregistrement en cours' })
|
||||
return res.status(409).json({ error: "Aucun enregistrement en cours" });
|
||||
}
|
||||
|
||||
const proc = recordingProcess
|
||||
const fileToFinalize = currentRecordingFile
|
||||
const proc = recordingProcess;
|
||||
const fileToFinalize = currentRecordingFile;
|
||||
|
||||
try {
|
||||
// Try graceful shutdown first
|
||||
proc.kill('SIGINT')
|
||||
proc.kill("SIGINT");
|
||||
} catch (e) {
|
||||
console.error('Error sending SIGINT:', e)
|
||||
console.error("Error sending SIGINT:", e);
|
||||
}
|
||||
|
||||
// Wait for process to exit (max 15 seconds)
|
||||
let waited = 0
|
||||
let waited = 0;
|
||||
while (recordingProcess && waited < 15000) {
|
||||
await new Promise(r => setTimeout(r, 100))
|
||||
waited += 100
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
waited += 100;
|
||||
}
|
||||
|
||||
if (recordingProcess) {
|
||||
try {
|
||||
recordingProcess.kill('SIGKILL')
|
||||
recordingProcess.kill("SIGKILL");
|
||||
} catch (e) {
|
||||
console.error('Error sending SIGKILL:', 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' })
|
||||
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' })
|
||||
})
|
||||
res.json({ status: "stopped" });
|
||||
});
|
||||
|
||||
// GET /api/recordings/status
|
||||
router.get('/status', async (req: Request, res: Response) => {
|
||||
router.get("/status", async (req: Request, res: Response) => {
|
||||
res.json({
|
||||
isRecording: !!recordingProcess,
|
||||
startTime: recordingStartTime,
|
||||
currentFile: currentRecordingFile?.replace(/\.part$/, '.mp4'),
|
||||
})
|
||||
})
|
||||
currentFile: currentRecordingFile?.replace(/\.part$/, ".mp4"),
|
||||
});
|
||||
});
|
||||
|
||||
export { router as recorderRouter }
|
||||
export { router as recorderRouter };
|
||||
|
||||
Reference in New Issue
Block a user