Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add server-side media capture for camera and microphone

Adam Eivyace903c3e3ec
diff --git a/client/src/pages/Media.jsx b/client/src/pages/Media.jsx
index f3de7a75f6..986aa54e2b 100644
--- a/client/src/pages/Media.jsx
+++ b/client/src/pages/Media.jsx
@@ -1,22 +1,23 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { Camera, Mic, MicOff, Video, VideoOff, RefreshCw, Settings, Volume2 } from 'lucide-react';
+import api from '../services/api';
const MEDIA_CONSTRAINTS_KEY = 'portos-media-constraints';
export default function Media() {
const videoRef = useRef(null);
+ const audioRef = useRef(null);
const audioContextRef = useRef(null);
const analyserRef = useRef(null);
const animationFrameRef = useRef(null);
- const [stream, setStream] = useState(null);
+ const [streaming, setStreaming] = useState(false);
const [videoEnabled, setVideoEnabled] = useState(true);
const [audioEnabled, setAudioEnabled] = useState(true);
const [devices, setDevices] = useState({ video: [], audio: [] });
- const [selectedVideo, setSelectedVideo] = useState('');
- const [selectedAudio, setSelectedAudio] = useState('');
+ const [selectedVideo, setSelectedVideo] = useState('0');
+ const [selectedAudio, setSelectedAudio] = useState('0');
const [error, setError] = useState(null);
- const [permissionState, setPermissionState] = useState('prompt'); // 'prompt', 'granted', 'denied'
const [audioLevel, setAudioLevel] = useState(0);
const [showSettings, setShowSettings] = useState(false);
const [isLoading, setIsLoading] = useState(false);
@@ -41,25 +42,22 @@ export default function Media() {
}
}, [selectedVideo, selectedAudio]);
- // Enumerate available devices
- const enumerateDevices = useCallback(async () => {
- const deviceList = await navigator.mediaDevices.enumerateDevices();
- const videoInputs = deviceList.filter(d => d.kind === 'videoinput');
- const audioInputs = deviceList.filter(d => d.kind === 'audioinput');
-
- setDevices({ video: videoInputs, audio: audioInputs });
+ // Fetch available devices from server
+ const fetchDevices = useCallback(async () => {
+ const response = await api.get('/media/devices');
+ setDevices(response.data);
// Set default selections if not already set
- if (!selectedVideo && videoInputs.length > 0) {
- setSelectedVideo(videoInputs[0].deviceId);
+ if (!selectedVideo && response.data.video.length > 0) {
+ setSelectedVideo(response.data.video[0].id);
}
- if (!selectedAudio && audioInputs.length > 0) {
- setSelectedAudio(audioInputs[0].deviceId);
+ if (!selectedAudio && response.data.audio.length > 0) {
+ setSelectedAudio(response.data.audio[0].id);
}
}, [selectedVideo, selectedAudio]);
- // Set up audio level monitoring
- const setupAudioAnalyser = useCallback(async (audioStream) => {
+ // Set up audio level monitoring from audio element
+ const setupAudioAnalyser = useCallback(async (audioElement) => {
// Clean up existing audio context
if (audioContextRef.current) {
audioContextRef.current.close();
@@ -76,10 +74,11 @@ export default function Media() {
}
const analyser = audioContext.createAnalyser();
- const source = audioContext.createMediaStreamSource(audioStream);
+ const source = audioContext.createMediaElementSource(audioElement);
analyser.fftSize = 256;
source.connect(analyser);
+ source.connect(audioContext.destination); // Connect to speakers
audioContextRef.current = audioContext;
analyserRef.current = analyser;
@@ -103,57 +102,56 @@ export default function Media() {
updateLevel();
}, []);
- // Start media stream
+ // Start media stream from server
const startMedia = useCallback(async () => {
setIsLoading(true);
setError(null);
- // Stop any existing stream
- if (stream) {
- stream.getTracks().forEach(track => track.stop());
- }
+ // Start streaming on server
+ await api.post('/media/start', {
+ videoDeviceId: selectedVideo,
+ audioDeviceId: selectedAudio,
+ video: videoEnabled,
+ audio: audioEnabled
+ });
- const constraints = {
- video: videoEnabled ? {
- deviceId: selectedVideo ? { exact: selectedVideo } : undefined,
- width: { ideal: 1280 },
- height: { ideal: 720 }
- } : false,
- audio: audioEnabled ? {
- deviceId: selectedAudio ? { exact: selectedAudio } : undefined,
- echoCancellation: true,
- noiseSuppression: true
- } : false
- };
-
- // If neither video nor audio is enabled, don't request
- if (!constraints.video && !constraints.audio) {
- setIsLoading(false);
- return;
- }
+ setStreaming(true);
+ setIsLoading(false);
+ }, [videoEnabled, audioEnabled, selectedVideo, selectedAudio]);
- const mediaStream = await navigator.mediaDevices.getUserMedia(constraints);
+ // Set up media sources when streaming starts
+ useEffect(() => {
+ if (!streaming) return;
- setStream(mediaStream);
- setPermissionState('granted');
+ const timestamp = Date.now();
- if (audioEnabled) {
- setupAudioAnalyser(mediaStream);
+ // Set video source to server stream
+ if (videoRef.current && videoEnabled) {
+ videoRef.current.src = `http://${window.location.hostname}:5554/api/media/video?t=${timestamp}`;
}
- // Re-enumerate to get device labels (only available after permission granted)
- await enumerateDevices();
- setIsLoading(false);
- }, [videoEnabled, audioEnabled, selectedVideo, selectedAudio, stream, enumerateDevices, setupAudioAnalyser]);
+ // Set audio source to server stream and set up analyzer
+ if (audioRef.current && audioEnabled) {
+ audioRef.current.src = `http://${window.location.hostname}:5554/api/media/audio?t=${timestamp}`;
+ audioRef.current.play().then(() => {
+ setupAudioAnalyser(audioRef.current);
+ }).catch(err => {
+ console.error('Audio playback error:', err);
+ });
+ }
+ }, [streaming, videoEnabled, audioEnabled, setupAudioAnalyser]);
// Stop media stream
- const stopMedia = useCallback(() => {
- if (stream) {
- stream.getTracks().forEach(track => track.stop());
- setStream(null);
- }
+ const stopMedia = useCallback(async () => {
+ // Stop streaming on server
+ await api.post('/media/stop');
+
if (videoRef.current) {
- videoRef.current.srcObject = null;
+ videoRef.current.src = '';
+ }
+ if (audioRef.current) {
+ audioRef.current.pause();
+ audioRef.current.src = '';
}
if (audioContextRef.current) {
audioContextRef.current.close();
@@ -162,73 +160,47 @@ export default function Media() {
if (animationFrameRef.current) {
cancelAnimationFrame(animationFrameRef.current);
}
+ setStreaming(false);
setAudioLevel(0);
- }, [stream]);
+ }, []);
- // Toggle video track
+ // Toggle video
const toggleVideo = useCallback(() => {
- if (stream) {
- const videoTrack = stream.getVideoTracks()[0];
- if (videoTrack) {
- videoTrack.enabled = !videoTrack.enabled;
- setVideoEnabled(videoTrack.enabled);
- }
- } else {
- setVideoEnabled(v => !v);
+ const newValue = !videoEnabled;
+ setVideoEnabled(newValue);
+
+ if (streaming) {
+ // Restart stream with new video setting
+ startMedia();
}
- }, [stream]);
+ }, [videoEnabled, streaming, startMedia]);
- // Toggle audio track
+ // Toggle audio
const toggleAudio = useCallback(() => {
- if (stream) {
- const audioTrack = stream.getAudioTracks()[0];
- if (audioTrack) {
- audioTrack.enabled = !audioTrack.enabled;
- setAudioEnabled(audioTrack.enabled);
- if (!audioTrack.enabled) {
- setAudioLevel(0);
- }
- }
- } else {
- setAudioEnabled(a => !a);
+ const newValue = !audioEnabled;
+ setAudioEnabled(newValue);
+
+ if (streaming) {
+ // Restart stream with new audio setting
+ startMedia();
}
- }, [stream]);
+ }, [audioEnabled, streaming, startMedia]);
- // Check permission status on mount
+ // Fetch devices on mount
useEffect(() => {
- const checkPermissions = async () => {
- if (navigator.permissions) {
- const cameraStatus = await navigator.permissions.query({ name: 'camera' });
- const micStatus = await navigator.permissions.query({ name: 'microphone' });
-
- if (cameraStatus.state === 'granted' && micStatus.state === 'granted') {
- setPermissionState('granted');
- } else if (cameraStatus.state === 'denied' || micStatus.state === 'denied') {
- setPermissionState('denied');
- setError('Camera or microphone access was denied. Please enable permissions in your browser settings.');
- }
- }
-
- // Enumerate devices (labels may be empty until permission granted)
- await enumerateDevices();
- };
-
- checkPermissions();
- }, [enumerateDevices]);
+ fetchDevices().catch(err => {
+ setError(`Failed to fetch devices: ${err.message}`);
+ });
+ }, [fetchDevices]);
// Cleanup on unmount
useEffect(() => {
return () => {
- stopMedia();
+ if (streaming) {
+ stopMedia();
+ }
};
- }, [stopMedia]);
-
- // Set video srcObject when stream changes (handles async state update)
- useEffect(() => {
- if (videoRef.current && stream && videoEnabled) {
- videoRef.current.srcObject = stream;
- }
- }, [stream, videoEnabled]);
+ }, [streaming, stopMedia]);
// Handle device change
const handleDeviceChange = useCallback(async (type, deviceId) => {
@@ -239,19 +211,19 @@ export default function Media() {
}
// Restart stream with new device if currently streaming
- if (stream) {
+ if (streaming) {
// Small delay to let state update
setTimeout(() => startMedia(), 100);
}
- }, [stream, startMedia]);
+ }, [streaming, startMedia]);
return (
<div>
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
<div>
- <h2 className="text-2xl font-bold text-white">Media Devices</h2>
- <p className="text-gray-500">Access your camera and microphone</p>
+ <h2 className="text-2xl font-bold text-white">Server Media Devices</h2>
+ <p className="text-gray-500">Access camera and microphone from the PortOS server</p>
</div>
<div className="flex items-center gap-2">
<button
@@ -294,9 +266,9 @@ export default function Media() {
{devices.video.length === 0 ? (
<option value="">No cameras found</option>
) : (
- devices.video.map((device, i) => (
- <option key={device.deviceId} value={device.deviceId}>
- {device.label || `Camera ${i + 1}`}
+ devices.video.map((device) => (
+ <option key={device.id} value={device.id}>
+ {device.name}
</option>
))
)}
@@ -317,9 +289,9 @@ export default function Media() {
{devices.audio.length === 0 ? (
<option value="">No microphones found</option>
) : (
- devices.audio.map((device, i) => (
- <option key={device.deviceId} value={device.deviceId}>
- {device.label || `Microphone ${i + 1}`}
+ devices.audio.map((device) => (
+ <option key={device.id} value={device.id}>
+ {device.name}
</option>
))
)}
@@ -335,22 +307,22 @@ export default function Media() {
<div className="lg:col-span-2">
<div className="bg-port-card border border-port-border rounded-xl overflow-hidden">
<div className="aspect-video bg-black relative">
- {stream && videoEnabled ? (
- <video
+ {streaming && videoEnabled ? (
+ <img
ref={videoRef}
- autoPlay
- playsInline
- muted
+ alt="Server camera stream"
className="w-full h-full object-cover"
/>
) : (
<div className="absolute inset-0 flex flex-col items-center justify-center text-gray-500">
<VideoOff size={48} className="mb-4" />
<p className="text-sm">
- {!stream ? 'Camera not started' : 'Camera disabled'}
+ {!streaming ? 'Camera not started' : 'Camera disabled'}
</p>
</div>
)}
+ {/* Hidden audio element for playback */}
+ <audio ref={audioRef} crossOrigin="anonymous" style={{ display: 'none' }} />
{/* Loading overlay */}
{isLoading && (
@@ -364,7 +336,7 @@ export default function Media() {
<div className="p-4 flex items-center justify-center gap-4">
<button
onClick={toggleVideo}
- disabled={!stream && permissionState !== 'granted'}
+ disabled={!streaming}
className={`p-3 rounded-full transition-colors ${
videoEnabled
? 'bg-port-card border border-port-border text-white hover:bg-port-border'
@@ -377,7 +349,7 @@ export default function Media() {
<button
onClick={toggleAudio}
- disabled={!stream && permissionState !== 'granted'}
+ disabled={!streaming}
className={`p-3 rounded-full transition-colors ${
audioEnabled
? 'bg-port-card border border-port-border text-white hover:bg-port-border'
@@ -388,10 +360,10 @@ export default function Media() {
{audioEnabled ? <Mic size={20} /> : <MicOff size={20} />}
</button>
- {!stream ? (
+ {!streaming ? (
<button
onClick={startMedia}
- disabled={isLoading || permissionState === 'denied'}
+ disabled={isLoading}
className="px-6 py-3 bg-port-accent text-white rounded-full font-medium hover:bg-port-accent/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? 'Starting...' : 'Start Media'}
@@ -406,8 +378,8 @@ export default function Media() {
)}
<button
- onClick={startMedia}
- disabled={!stream || isLoading}
+ onClick={fetchDevices}
+ disabled={isLoading}
className="p-3 rounded-full bg-port-card border border-port-border text-gray-400 hover:text-white hover:bg-port-border transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
title="Refresh devices"
>
@@ -461,10 +433,10 @@ export default function Media() {
</div>
<p className="text-sm text-gray-500 text-center">
- {!stream
+ {!streaming
? 'Start media to see audio levels'
: !audioEnabled
- ? 'Microphone muted'
+ ? 'Microphone disabled'
: audioLevel > 0.1
? 'Receiving audio'
: 'No audio detected'}
@@ -476,41 +448,28 @@ export default function Media() {
<div className="bg-port-card border border-port-border rounded-xl p-4">
<h3 className="font-semibold text-white mb-4">Status</h3>
<div className="space-y-3">
- <div className="flex items-center justify-between">
- <span className="text-gray-400">Permission</span>
- <span className={`text-sm font-medium ${
- permissionState === 'granted'
- ? 'text-port-success'
- : permissionState === 'denied'
- ? 'text-port-error'
- : 'text-port-warning'
- }`}>
- {permissionState === 'granted' ? 'Granted' : permissionState === 'denied' ? 'Denied' : 'Not requested'}
- </span>
- </div>
-
<div className="flex items-center justify-between">
<span className="text-gray-400">Stream</span>
- <span className={`text-sm font-medium ${stream ? 'text-port-success' : 'text-gray-500'}`}>
- {stream ? 'Active' : 'Inactive'}
+ <span className={`text-sm font-medium ${streaming ? 'text-port-success' : 'text-gray-500'}`}>
+ {streaming ? 'Active' : 'Inactive'}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-400">Camera</span>
<span className={`text-sm font-medium ${
- stream && videoEnabled ? 'text-port-success' : 'text-gray-500'
+ streaming && videoEnabled ? 'text-port-success' : 'text-gray-500'
}`}>
- {stream ? (videoEnabled ? 'On' : 'Off') : '-'}
+ {streaming ? (videoEnabled ? 'On' : 'Off') : '-'}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-400">Microphone</span>
<span className={`text-sm font-medium ${
- stream && audioEnabled ? 'text-port-success' : 'text-gray-500'
+ streaming && audioEnabled ? 'text-port-success' : 'text-gray-500'
}`}>
- {stream ? (audioEnabled ? 'On' : 'Off') : '-'}
+ {streaming ? (audioEnabled ? 'On' : 'Off') : '-'}
</span>
</div>
</div>
@@ -520,8 +479,8 @@ export default function Media() {
<div className="bg-port-card border border-port-border rounded-xl p-4">
<h3 className="font-semibold text-white mb-3">Instructions</h3>
<ul className="space-y-2 text-sm text-gray-400">
- <li>1. Click &quot;Start Media&quot; to access devices</li>
- <li>2. Grant permission when prompted</li>
+ <li>1. Click &quot;Start Media&quot; to stream from server</li>
+ <li>2. Video and audio stream from the PortOS server</li>
<li>3. Use controls to toggle camera/mic</li>
<li>4. Select different devices in Settings</li>
</ul>
diff --git a/client/src/services/api.js b/client/src/services/api.js
index be9d0e62b6..40e31f6045 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -527,3 +527,28 @@ export const runBrainReview = (providerOverride, modelOverride) => request('/bra
method: 'POST',
body: JSON.stringify({ providerOverride, modelOverride })
});
+
+// Media - Server media devices
+export const getMediaDevices = () => request('/media/devices');
+export const getMediaStatus = () => request('/media/status');
+export const startMediaStream = (videoDeviceId, audioDeviceId, video = true, audio = true) => request('/media/start', {
+ method: 'POST',
+ body: JSON.stringify({ videoDeviceId, audioDeviceId, video, audio })
+});
+export const stopMediaStream = () => request('/media/stop', { method: 'POST' });
+
+// Default export for simplified imports
+export default {
+ get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),
+ post: (endpoint, body, options) => request(endpoint, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ ...options
+ }),
+ put: (endpoint, body, options) => request(endpoint, {
+ method: 'PUT',
+ body: JSON.stringify(body),
+ ...options
+ }),
+ delete: (endpoint, options) => request(endpoint, { method: 'DELETE', ...options })
+};
diff --git a/server/index.js b/server/index.js
index da2d99e6c8..4031f60fef 100644
--- a/server/index.js
+++ b/server/index.js
@@ -27,6 +27,7 @@ import memoryRoutes from './routes/memory.js';
import notificationsRoutes from './routes/notifications.js';
import standardizeRoutes from './routes/standardize.js';
import brainRoutes from './routes/brain.js';
+import mediaRoutes from './routes/media.js';
import { initSocket } from './services/socket.js';
import { initScriptRunner } from './services/scriptRunner.js';
import { errorMiddleware, setupProcessErrorHandlers } from './lib/errorHandler.js';
@@ -94,6 +95,7 @@ app.use('/api/memory', memoryRoutes);
app.use('/api/notifications', notificationsRoutes);
app.use('/api/standardize', standardizeRoutes);
app.use('/api/brain', brainRoutes);
+app.use('/api/media', mediaRoutes);
// Initialize script runner
initScriptRunner().catch(err => console.error(`❌ Script runner init failed: ${err.message}`));
diff --git a/server/routes/media.js b/server/routes/media.js
new file mode 100644
index 0000000000..8e542efc5f
--- /dev/null
+++ b/server/routes/media.js
@@ -0,0 +1,119 @@
+import express from 'express';
+import { z } from 'zod';
+import mediaService from '../services/mediaService.js';
+
+const router = express.Router();
+
+// Validation schemas
+const startMediaSchema = z.object({
+ videoDeviceId: z.string().optional(),
+ audioDeviceId: z.string().optional(),
+ video: z.boolean().default(true),
+ audio: z.boolean().default(true)
+});
+
+// List available media devices
+router.get('/devices', async (req, res) => {
+ const devices = await mediaService.listDevices();
+ res.json(devices);
+});
+
+// Get current streaming status
+router.get('/status', (req, res) => {
+ res.json({
+ video: mediaService.isVideoStreaming(),
+ audio: mediaService.isAudioStreaming()
+ });
+});
+
+// Start media streaming
+router.post('/start', async (req, res) => {
+ const { videoDeviceId = '0', audioDeviceId = '0', video = true, audio = true } = startMediaSchema.parse(req.body);
+
+ if (video) {
+ mediaService.startVideoStream(videoDeviceId);
+ }
+
+ if (audio) {
+ mediaService.startAudioStream(audioDeviceId);
+ }
+
+ res.json({
+ success: true,
+ video: mediaService.isVideoStreaming(),
+ audio: mediaService.isAudioStreaming()
+ });
+});
+
+// Stop media streaming
+router.post('/stop', (req, res) => {
+ mediaService.stopAll();
+ res.json({ success: true });
+});
+
+// Stream video
+router.get('/video', (req, res) => {
+ const videoStream = mediaService.getVideoStream();
+
+ if (!videoStream) {
+ return res.status(404).json({ error: 'Video stream not active' });
+ }
+
+ res.setHeader('Content-Type', 'multipart/x-mixed-replace; boundary=frame');
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
+ res.setHeader('Pragma', 'no-cache');
+ res.setHeader('Expires', '0');
+ res.setHeader('Access-Control-Allow-Origin', '*');
+
+ let frameBuffer = Buffer.alloc(0);
+
+ videoStream.on('data', (chunk) => {
+ frameBuffer = Buffer.concat([frameBuffer, chunk]);
+
+ // Look for JPEG markers
+ let start = frameBuffer.indexOf(Buffer.from([0xFF, 0xD8])); // JPEG start
+ let end = frameBuffer.indexOf(Buffer.from([0xFF, 0xD9]), start + 2); // JPEG end
+
+ while (start !== -1 && end !== -1) {
+ const frame = frameBuffer.slice(start, end + 2);
+ res.write(`--frame\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`);
+ res.write(frame);
+ res.write('\r\n');
+
+ frameBuffer = frameBuffer.slice(end + 2);
+ start = frameBuffer.indexOf(Buffer.from([0xFF, 0xD8]));
+ end = frameBuffer.indexOf(Buffer.from([0xFF, 0xD9]), start + 2);
+ }
+ });
+
+ videoStream.on('end', () => {
+ res.end();
+ });
+
+ req.on('close', () => {
+ console.log('📹 Video client disconnected');
+ });
+});
+
+// Stream audio
+router.get('/audio', (req, res) => {
+ const audioStream = mediaService.getAudioStream();
+
+ if (!audioStream) {
+ return res.status(404).json({ error: 'Audio stream not active' });
+ }
+
+ res.setHeader('Content-Type', 'audio/webm');
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
+ res.setHeader('Pragma', 'no-cache');
+ res.setHeader('Expires', '0');
+ res.setHeader('Access-Control-Allow-Origin', '*');
+
+ audioStream.pipe(res);
+
+ req.on('close', () => {
+ console.log('🎤 Audio client disconnected');
+ });
+});
+
+export default router;
diff --git a/server/services/mediaService.js b/server/services/mediaService.js
new file mode 100644
index 0000000000..340e46dc15
--- /dev/null
+++ b/server/services/mediaService.js
@@ -0,0 +1,186 @@
+import { spawn } from 'child_process';
+import { PassThrough } from 'stream';
+
+class MediaService {
+ constructor() {
+ this.videoProcess = null;
+ this.audioProcess = null;
+ this.videoStream = null;
+ this.audioStream = null;
+ this.devices = {
+ video: [],
+ audio: []
+ };
+ }
+
+ async listDevices() {
+ return new Promise((resolve, reject) => {
+ const ffmpeg = spawn('ffmpeg', [
+ '-f', 'avfoundation',
+ '-list_devices', 'true',
+ '-i', ''
+ ]);
+
+ let output = '';
+
+ ffmpeg.stderr.on('data', (data) => {
+ output += data.toString();
+ });
+
+ ffmpeg.on('close', () => {
+ const videoDevices = [];
+ const audioDevices = [];
+
+ const lines = output.split('\n');
+ let inVideoSection = false;
+ let inAudioSection = false;
+
+ for (const line of lines) {
+ if (line.includes('AVFoundation video devices:')) {
+ inVideoSection = true;
+ inAudioSection = false;
+ continue;
+ }
+ if (line.includes('AVFoundation audio devices:')) {
+ inVideoSection = false;
+ inAudioSection = true;
+ continue;
+ }
+
+ const match = line.match(/\[(\d+)\] (.+)/);
+ if (match) {
+ const [, id, name] = match;
+ if (inVideoSection && !name.includes('Capture screen')) {
+ videoDevices.push({ id, name: name.trim() });
+ } else if (inAudioSection) {
+ audioDevices.push({ id, name: name.trim() });
+ }
+ }
+ }
+
+ this.devices = { video: videoDevices, audio: audioDevices };
+ resolve(this.devices);
+ });
+
+ ffmpeg.on('error', reject);
+ });
+ }
+
+ startVideoStream(deviceId = '0') {
+ if (this.videoProcess) {
+ this.stopVideoStream();
+ }
+
+ this.videoStream = new PassThrough();
+
+ // Use MJPEG format for compatibility and low latency
+ this.videoProcess = spawn('ffmpeg', [
+ '-f', 'avfoundation',
+ '-video_size', '1280x720',
+ '-framerate', '30',
+ '-i', `${deviceId}:none`,
+ '-f', 'mjpeg',
+ '-q:v', '5',
+ '-'
+ ]);
+
+ this.videoProcess.stdout.pipe(this.videoStream);
+
+ this.videoProcess.stderr.on('data', (data) => {
+ const msg = data.toString();
+ if (!msg.includes('frame=') && !msg.includes('fps=')) {
+ console.log(`📹 FFmpeg video: ${msg.trim()}`);
+ }
+ });
+
+ this.videoProcess.on('error', (err) => {
+ console.error(`❌ Video stream error: ${err.message}`);
+ });
+
+ this.videoProcess.on('close', () => {
+ console.log('📹 Video stream stopped');
+ this.videoStream = null;
+ });
+
+ return this.videoStream;
+ }
+
+ startAudioStream(deviceId = '0') {
+ if (this.audioProcess) {
+ this.stopAudioStream();
+ }
+
+ this.audioStream = new PassThrough();
+
+ // Use WebM format with Opus codec for web compatibility
+ this.audioProcess = spawn('ffmpeg', [
+ '-f', 'avfoundation',
+ '-i', `:${deviceId}`,
+ '-f', 'webm',
+ '-acodec', 'libopus',
+ '-ac', '1',
+ '-ar', '48000',
+ '-b:a', '128k',
+ '-'
+ ]);
+
+ this.audioProcess.stdout.pipe(this.audioStream);
+
+ this.audioProcess.stderr.on('data', (data) => {
+ const msg = data.toString();
+ if (!msg.includes('frame=') && !msg.includes('size=')) {
+ console.log(`🎤 FFmpeg audio: ${msg.trim()}`);
+ }
+ });
+
+ this.audioProcess.on('error', (err) => {
+ console.error(`❌ Audio stream error: ${err.message}`);
+ });
+
+ this.audioProcess.on('close', () => {
+ console.log('🎤 Audio stream stopped');
+ this.audioStream = null;
+ });
+
+ return this.audioStream;
+ }
+
+ stopVideoStream() {
+ if (this.videoProcess) {
+ this.videoProcess.kill('SIGTERM');
+ this.videoProcess = null;
+ this.videoStream = null;
+ }
+ }
+
+ stopAudioStream() {
+ if (this.audioProcess) {
+ this.audioProcess.kill('SIGTERM');
+ this.audioProcess = null;
+ this.audioStream = null;
+ }
+ }
+
+ stopAll() {
+ this.stopVideoStream();
+ this.stopAudioStream();
+ }
+
+ isVideoStreaming() {
+ return this.videoProcess !== null && this.videoStream !== null;
+ }
+
+ isAudioStreaming() {
+ return this.audioProcess !== null && this.audioStream !== null;
+ }
+
+ getVideoStream() {
+ return this.videoStream;
+ }
+
+ getAudioStream() {
+ return this.audioStream;
+ }
+}
+
+export default new MediaService();