Stylique commited on
Commit
ad4e5f8
·
verified ·
1 Parent(s): 682db54

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +115 -116
server.js CHANGED
@@ -26,7 +26,8 @@ const BUNDLE_CACHE_TTL = 5 * 60 * 1000;
26
  app.get('/', (req, res) => {
27
  res.json({
28
  status: 'ok',
29
- service: 'FacelessFlowAI Video Renderer (L4 GPU Optimized)'
 
30
  });
31
  });
32
 
@@ -78,15 +79,46 @@ async function checkNvenc() {
78
  try {
79
  const { execSync } = await import('child_process');
80
  const result = execSync('ffmpeg -encoders 2>/dev/null | grep -i nvenc', { encoding: 'utf8' });
81
- console.log('[GPU] NVENC detected:', result.trim());
82
  return true;
83
  } catch (error) {
84
- console.log('[GPU] NVENC not available, using software encoding');
85
  return false;
86
  }
87
  }
88
 
89
- // Render endpoint - L4 GPU OPTIMIZED
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  app.post('/render', async (req, res) => {
91
  const { projectId, scenes, settings } = req.body;
92
 
@@ -110,7 +142,7 @@ app.post('/render', async (req, res) => {
110
  res.json({
111
  success: true,
112
  message: 'Rendering started in background',
113
- hardware: 'L4 GPU Optimized'
114
  });
115
 
116
  // 2. Start Background Process
@@ -118,14 +150,15 @@ app.post('/render', async (req, res) => {
118
  const startTime = Date.now();
119
 
120
  try {
121
- console.log(`[Render] Starting L4 GPU render for project ${projectId}`);
122
 
 
 
 
 
123
  const bundleLocation = await getCachedBundle();
124
  console.log('[Bundle] Bundle ready');
125
 
126
- // Check NVENC before rendering
127
- const nvencAvailable = await checkNvenc();
128
-
129
  const composition = await selectComposition({
130
  serveUrl: bundleLocation,
131
  id: 'Main',
@@ -135,18 +168,17 @@ app.post('/render', async (req, res) => {
135
  args: [
136
  '--no-sandbox',
137
  '--disable-dev-shm-usage',
138
- // L4 GPU OPTIMIZATIONS
139
  '--use-gl=angle',
140
  '--use-angle=gl-egl',
141
  '--enable-gpu-rasterization',
142
  '--enable-oop-rasterization',
143
- '--enable-zero-copy',
144
- '--disable-software-rasterizer',
145
- '--disable-gpu-driver-bug-workarounds',
146
- '--max-active-webgl-contexts=32',
147
- '--disable-frame-rate-limit',
148
- '--disable-background-timer-throttling',
149
- ]
150
  },
151
  });
152
 
@@ -157,11 +189,10 @@ app.post('/render', async (req, res) => {
157
  await mkdir(tempDir, { recursive: true });
158
  const outputPath = join(tempDir, 'output.mp4');
159
 
160
- // L4 OPTIMAL SETTINGS: 8 vCPUs, 30GB RAM, 24GB VRAM
161
- const optimalConcurrency = 12; // Higher than CPU count because GPU handles rendering
162
- console.log(`[L4 Config] Using concurrency: ${optimalConcurrency}`);
163
 
164
- console.log('[Render] Starting video rendering with L4 GPU...');
165
 
166
  await renderMedia({
167
  composition,
@@ -170,7 +201,7 @@ app.post('/render', async (req, res) => {
170
  pixelFormat: 'yuv420p',
171
  outputLocation: outputPath,
172
  imageFormat: 'jpeg',
173
- jpegQuality: 85, // Higher quality for L4
174
  inputProps: { scenes, settings },
175
  chromiumOptions: {
176
  executablePath: '/usr/bin/google-chrome-stable',
@@ -179,45 +210,38 @@ app.post('/render', async (req, res) => {
179
  '--disable-dev-shm-usage',
180
  '--use-gl=angle',
181
  '--use-angle=gl-egl',
182
- '--enable-gpu-rasterization',
183
- '--enable-oop-rasterization',
184
  ]
185
  },
186
- concurrency: optimalConcurrency,
187
- disallowParallelEncoding: false, // Allow parallel for L4
188
  onProgress: ({ progress, renderedFrames }) => {
189
  const percent = Math.round(progress * 100);
190
  const elapsed = (Date.now() - startTime) / 1000;
191
  const fps = elapsed > 0 ? Math.round(renderedFrames / elapsed) : 0;
192
- console.log(`[L4 Progress] ${percent}% | FPS: ${fps} | Frames: ${renderedFrames}`);
193
  },
194
  ffmpegOverride: ({ args }) => {
195
  if (nvencAvailable) {
196
  console.log('[L4 GPU] Using NVENC hardware encoding');
197
- // L4 NVENC OPTIMIZED SETTINGS
198
  return [
199
  ...args,
200
  '-c:v', 'h264_nvenc',
201
- '-preset', 'p1', // Fastest quality
202
- '-tune', 'll', // Low latency
203
- '-rc', 'vbr', // Variable bitrate
204
- '-cq', '18', // Constant quality (18 = high quality)
205
- '-b:v', '0', // Let CQ control bitrate
206
  '-movflags', '+faststart',
207
  '-profile:v', 'high',
208
  '-level', '5.1',
209
- '-bf', '3', // B-frames for compression
210
- '-gpu', '0', // Use GPU 0
211
- '-surfaces', '32', // More surfaces for L4
212
- '-spatial-aq', '1',
213
- '-temporal-aq', '1',
214
- '-rc-lookahead', '32',
215
  '-c:a', 'aac',
216
  '-b:a', '192k',
217
  '-ac', '2',
218
  ];
219
  } else {
220
- console.log('[CPU] Using software encoding (fallback)');
221
  return [
222
  ...args,
223
  '-c:v', 'libx264',
@@ -230,12 +254,12 @@ app.post('/render', async (req, res) => {
230
  }
231
  },
232
  audioBitrate: '192k',
233
- videoBitrate: '12M', // Higher bitrate for L4 quality
234
  muted: false,
235
  });
236
 
237
  const renderTime = Date.now() - startTime;
238
- console.log(`[L4 Render] Completed in ${Math.round(renderTime / 1000)}s`);
239
 
240
  const fps = Math.round(composition.durationInFrames / (renderTime / 1000));
241
  console.log(`[Performance] Average FPS: ${fps}`);
@@ -267,7 +291,7 @@ app.post('/render', async (req, res) => {
267
 
268
  console.log(`[Upload] Uploaded to ${publicUrl}`);
269
 
270
- // Update Project in DB with performance metrics
271
  const { error: dbError } = await supabase
272
  .from('projects')
273
  .update({
@@ -290,14 +314,9 @@ app.post('/render', async (req, res) => {
290
  } catch (error) {
291
  console.error(`[Render] Error for ${projectId}:`, error.message);
292
 
293
- // Try software encoding as fallback
294
- console.log('[Fallback] Trying software encoding...');
295
- try {
296
- // We could implement a retry with software encoding here
297
- // But for now, just log the error
298
- } catch (fallbackError) {
299
- console.error('[Fallback] Also failed:', fallbackError.message);
300
- }
301
 
302
  // Update project status to 'error'
303
  try {
@@ -315,7 +334,7 @@ app.post('/render', async (req, res) => {
315
  })();
316
  });
317
 
318
- // Status endpoint with GPU info
319
  app.get('/status', async (req, res) => {
320
  const os = await import('os');
321
  const { execSync } = await import('child_process');
@@ -324,119 +343,99 @@ app.get('/status', async (req, res) => {
324
  let nvencInfo = 'Not detected';
325
 
326
  try {
327
- // Check for NVIDIA GPU
328
- const gpu = execSync('lspci | grep -i "vga\|3d\|display"', { encoding: 'utf8' });
329
- gpuInfo = gpu.trim() || 'No GPU detected';
 
 
 
 
330
 
331
- // Check for NVENC
332
  try {
333
  execSync('ffmpeg -encoders 2>/dev/null | grep -i nvenc', { stdio: 'pipe' });
334
- nvencInfo = 'NVENC available';
335
  } catch {
336
- nvencInfo = 'NVENC not available';
337
  }
338
  } catch (error) {
339
- gpuInfo = 'GPU check failed';
340
  }
341
 
342
  res.json({
343
  status: 'running',
344
- hardware: 'L4 GPU Optimized',
345
  cpu_cores: os.cpus().length,
346
  total_memory: Math.round(os.totalmem() / (1024 * 1024 * 1024)) + 'GB',
347
  free_memory: Math.round(os.freemem() / (1024 * 1024 * 1024)) + 'GB',
348
  gpu: gpuInfo,
349
  nvenc: nvencInfo,
350
  bundle_cached: cachedBundle !== null,
351
- uptime: Math.round(process.uptime()) + 's'
 
352
  });
353
  });
354
 
355
- // Test NVENC endpoint
356
- app.get('/test-nvenc', async (req, res) => {
357
  try {
358
  const { execSync } = await import('child_process');
359
 
360
- // Test 1: Check GPU
361
- const gpuTest = execSync('lspci | grep -i "vga\|3d\|display"', { encoding: 'utf8' });
362
 
363
- // Test 2: Check NVENC
364
- let nvencTest = 'Not detected';
365
- try {
366
- const nvenc = execSync('ffmpeg -encoders 2>/dev/null | grep -i nvenc', { encoding: 'utf8' });
367
- nvencTest = nvenc.trim();
368
- } catch {
369
- nvencTest = 'NVENC not found';
370
- }
371
 
372
- // Test 3: Simple FFmpeg NVENC test
373
- let encodeTest = 'Not tested';
374
- try {
375
- execSync('ffmpeg -f lavfi -i testsrc=duration=1:size=1280x720:rate=30 -c:v h264_nvenc -f null - 2>&1 | tail -5', { stdio: 'pipe' });
376
- encodeTest = 'NVENC encoding works';
377
- } catch (error) {
378
- encodeTest = 'NVENC encoding failed: ' + error.message;
379
- }
380
 
381
  res.json({
382
- gpu: gpuTest.trim(),
383
- nvenc: nvencTest,
384
- encode_test: encodeTest,
385
- hardware: 'L4 GPU Test'
386
  });
387
  } catch (error) {
388
- res.status(500).json({ error: error.message });
 
 
 
 
389
  }
390
  });
391
 
392
  // Start server
393
  app.listen(PORT, async () => {
394
- console.log(`🎬 FacelessFlowAI Renderer (L4 GPU) running on port ${PORT}`);
395
 
396
  const os = await import('os');
397
  console.log(`💾 Memory: ${Math.round(os.totalmem() / (1024 * 1024 * 1024))}GB`);
398
  console.log(`⚡ CPU Cores: ${os.cpus().length}`);
399
 
400
- // Check GPU
401
  try {
402
  const { execSync } = await import('child_process');
403
- const gpu = execSync('lspci | grep -i "vga\|3d\|display"', { encoding: 'utf8' });
404
- console.log(`🎮 GPU: ${gpu.trim()}`);
405
-
406
- // Check NVENC
407
- try {
408
- const nvenc = execSync('ffmpeg -encoders 2>/dev/null | grep -i nvenc', { encoding: 'utf8' });
409
- console.log(`⚡ NVENC: ${nvenc.trim()}`);
410
- } catch {
411
- console.log('⚡ NVENC: Not detected');
412
- }
413
- } catch (error) {
414
- console.log('🎮 GPU: Check failed');
415
  }
416
 
417
- console.log('--- L4 Configuration ---');
418
- console.log('GPU: Enabled with ANGLE/OpenGL');
419
- console.log('ENCODING: NVENC hardware encoding');
420
- console.log('CONCURRENCY: 12 threads');
421
- console.log('QUALITY: High (CQ 18)');
422
- console.log('-----------------------');
423
 
424
  // Auto-warmup
425
  setTimeout(async () => {
426
  try {
427
  await getCachedBundle();
428
  console.log('[Auto-Warmup] Bundle ready');
429
-
430
- // Test NVENC
431
- try {
432
- const { execSync } = await import('child_process');
433
- execSync('ffmpeg -encoders 2>/dev/null | grep -i nvenc', { stdio: 'pipe' });
434
- console.log('[Auto-Warmup] NVENC ready');
435
- } catch {
436
- console.log('[Auto-Warmup] NVENC not available');
437
- }
438
  } catch (error) {
439
  console.error('[Auto-Warmup] Failed:', error.message);
440
  }
441
- }, 5000);
442
  });
 
26
  app.get('/', (req, res) => {
27
  res.json({
28
  status: 'ok',
29
+ service: 'FacelessFlowAI Video Renderer (L4 GPU Optimized)',
30
+ note: 'NVENC hardware encoding enabled'
31
  });
32
  });
33
 
 
79
  try {
80
  const { execSync } = await import('child_process');
81
  const result = execSync('ffmpeg -encoders 2>/dev/null | grep -i nvenc', { encoding: 'utf8' });
82
+ console.log('[GPU] NVENC detected');
83
  return true;
84
  } catch (error) {
85
+ console.log('[GPU] NVENC not available');
86
  return false;
87
  }
88
  }
89
 
90
+ // Get optimal concurrency (respects Remotion limits)
91
+ async function getOptimalConcurrency() {
92
+ try {
93
+ const os = await import('os');
94
+ const cpuCount = os.cpus().length;
95
+
96
+ // Remotion suggests max concurrency = number of cores
97
+ // For L4 with 8 vCPUs, use 6 (as suggested by Remotion)
98
+ const optimal = Math.min(cpuCount, 6);
99
+ console.log(`[CPU] Detected ${cpuCount} cores, using concurrency: ${optimal}`);
100
+ return optimal;
101
+ } catch (error) {
102
+ console.log('[CPU] Using default concurrency: 4');
103
+ return 4;
104
+ }
105
+ }
106
+
107
+ // Pre-check Chrome to avoid download during render
108
+ async function ensureChrome() {
109
+ console.log('[Chrome] Checking Chrome...');
110
+ try {
111
+ const { execSync } = await import('child_process');
112
+ execSync('/usr/bin/google-chrome-stable --version', { stdio: 'pipe' });
113
+ console.log('[Chrome] Chrome is ready');
114
+ return true;
115
+ } catch (error) {
116
+ console.log('[Chrome] Will use headless shell');
117
+ return false;
118
+ }
119
+ }
120
+
121
+ // Render endpoint - OPTIMIZED FOR L4
122
  app.post('/render', async (req, res) => {
123
  const { projectId, scenes, settings } = req.body;
124
 
 
142
  res.json({
143
  success: true,
144
  message: 'Rendering started in background',
145
+ hardware: 'L4 GPU with NVENC'
146
  });
147
 
148
  // 2. Start Background Process
 
150
  const startTime = Date.now();
151
 
152
  try {
153
+ console.log(`[Render] Starting render for project ${projectId}`);
154
 
155
+ // Pre-checks
156
+ const nvencAvailable = await checkNvenc();
157
+ await ensureChrome();
158
+
159
  const bundleLocation = await getCachedBundle();
160
  console.log('[Bundle] Bundle ready');
161
 
 
 
 
162
  const composition = await selectComposition({
163
  serveUrl: bundleLocation,
164
  id: 'Main',
 
168
  args: [
169
  '--no-sandbox',
170
  '--disable-dev-shm-usage',
171
+ // GPU acceleration
172
  '--use-gl=angle',
173
  '--use-angle=gl-egl',
174
  '--enable-gpu-rasterization',
175
  '--enable-oop-rasterization',
176
+ ],
177
+ onBrowserDownload: (progress) => {
178
+ const downloadedMB = (progress.downloadedBytes / 1024 / 1024).toFixed(1);
179
+ const totalMB = (progress.totalSize / 1024 / 1024).toFixed(1);
180
+ console.log(`[Chrome] Downloading: ${downloadedMB}Mb/${totalMB}Mb`);
181
+ }
 
182
  },
183
  });
184
 
 
189
  await mkdir(tempDir, { recursive: true });
190
  const outputPath = join(tempDir, 'output.mp4');
191
 
192
+ // Get optimal concurrency (respects system limits)
193
+ const concurrency = await getOptimalConcurrency();
 
194
 
195
+ console.log('[Render] Starting video rendering...');
196
 
197
  await renderMedia({
198
  composition,
 
201
  pixelFormat: 'yuv420p',
202
  outputLocation: outputPath,
203
  imageFormat: 'jpeg',
204
+ jpegQuality: 85,
205
  inputProps: { scenes, settings },
206
  chromiumOptions: {
207
  executablePath: '/usr/bin/google-chrome-stable',
 
210
  '--disable-dev-shm-usage',
211
  '--use-gl=angle',
212
  '--use-angle=gl-egl',
 
 
213
  ]
214
  },
215
+ concurrency: concurrency,
216
+ disallowParallelEncoding: false,
217
  onProgress: ({ progress, renderedFrames }) => {
218
  const percent = Math.round(progress * 100);
219
  const elapsed = (Date.now() - startTime) / 1000;
220
  const fps = elapsed > 0 ? Math.round(renderedFrames / elapsed) : 0;
221
+ console.log(`[Progress] ${percent}% | FPS: ${fps} | Frames: ${renderedFrames}`);
222
  },
223
  ffmpegOverride: ({ args }) => {
224
  if (nvencAvailable) {
225
  console.log('[L4 GPU] Using NVENC hardware encoding');
226
+ // OPTIMIZED NVENC SETTINGS FOR L4
227
  return [
228
  ...args,
229
  '-c:v', 'h264_nvenc',
230
+ '-preset', 'p1', // Fastest quality preset
231
+ '-tune', 'll', // Low latency
232
+ '-cq', '20', // Quality level (20 = good quality)
 
 
233
  '-movflags', '+faststart',
234
  '-profile:v', 'high',
235
  '-level', '5.1',
236
+ '-bf', '2', // B-frames
237
+ '-gpu', '0', // Use GPU 0
238
+ '-surfaces', '24', // Surfaces for L4
 
 
 
239
  '-c:a', 'aac',
240
  '-b:a', '192k',
241
  '-ac', '2',
242
  ];
243
  } else {
244
+ console.log('[CPU] Using software encoding');
245
  return [
246
  ...args,
247
  '-c:v', 'libx264',
 
254
  }
255
  },
256
  audioBitrate: '192k',
257
+ videoBitrate: '10M',
258
  muted: false,
259
  });
260
 
261
  const renderTime = Date.now() - startTime;
262
+ console.log(`[Render] Completed in ${Math.round(renderTime / 1000)}s`);
263
 
264
  const fps = Math.round(composition.durationInFrames / (renderTime / 1000));
265
  console.log(`[Performance] Average FPS: ${fps}`);
 
291
 
292
  console.log(`[Upload] Uploaded to ${publicUrl}`);
293
 
294
+ // Update Project in DB
295
  const { error: dbError } = await supabase
296
  .from('projects')
297
  .update({
 
314
  } catch (error) {
315
  console.error(`[Render] Error for ${projectId}:`, error.message);
316
 
317
+ // Try fallback with reduced concurrency
318
+ console.log('[Fallback] Trying with reduced concurrency...');
319
+ // (You could implement a retry logic here if needed)
 
 
 
 
 
320
 
321
  // Update project status to 'error'
322
  try {
 
334
  })();
335
  });
336
 
337
+ // Status endpoint
338
  app.get('/status', async (req, res) => {
339
  const os = await import('os');
340
  const { execSync } = await import('child_process');
 
343
  let nvencInfo = 'Not detected';
344
 
345
  try {
346
+ // Check GPU
347
+ try {
348
+ const gpu = execSync('lspci 2>/dev/null | grep -i "vga\\|3d\\|display" || echo "No GPU"', { encoding: 'utf8' });
349
+ gpuInfo = gpu.trim();
350
+ } catch {
351
+ gpuInfo = 'GPU check failed';
352
+ }
353
 
354
+ // Check NVENC
355
  try {
356
  execSync('ffmpeg -encoders 2>/dev/null | grep -i nvenc', { stdio: 'pipe' });
357
+ nvencInfo = 'Available';
358
  } catch {
359
+ nvencInfo = 'Not available';
360
  }
361
  } catch (error) {
362
+ gpuInfo = 'Check error';
363
  }
364
 
365
  res.json({
366
  status: 'running',
367
+ hardware: 'L4 GPU',
368
  cpu_cores: os.cpus().length,
369
  total_memory: Math.round(os.totalmem() / (1024 * 1024 * 1024)) + 'GB',
370
  free_memory: Math.round(os.freemem() / (1024 * 1024 * 1024)) + 'GB',
371
  gpu: gpuInfo,
372
  nvenc: nvencInfo,
373
  bundle_cached: cachedBundle !== null,
374
+ uptime: Math.round(process.uptime()) + 's',
375
+ concurrency_limit: 'Max 8 (6 recommended)'
376
  });
377
  });
378
 
379
+ // Quick NVENC test
380
+ app.get('/test-encode', async (req, res) => {
381
  try {
382
  const { execSync } = await import('child_process');
383
 
384
+ // Create a test video with NVENC
385
+ const testCommand = 'ffmpeg -f lavfi -i testsrc=duration=2:size=640x360:rate=30 -c:v h264_nvenc -preset p1 -tune ll -f mp4 -y /tmp/test_nvenc.mp4 2>&1';
386
 
387
+ console.log('[Test] Running:', testCommand);
388
+ const output = execSync(testCommand, { encoding: 'utf8', maxBuffer: 1024 * 1024 * 10 });
 
 
 
 
 
 
389
 
390
+ // Check if file was created
391
+ const fs = await import('fs');
392
+ const stats = fs.statSync('/tmp/test_nvenc.mp4');
 
 
 
 
 
393
 
394
  res.json({
395
+ success: true,
396
+ file_size: stats.size + ' bytes',
397
+ test: 'NVENC encoding works',
398
+ output_preview: output.substring(0, 500) + '...'
399
  });
400
  } catch (error) {
401
+ res.json({
402
+ success: false,
403
+ error: error.message,
404
+ test: 'NVENC encoding failed'
405
+ });
406
  }
407
  });
408
 
409
  // Start server
410
  app.listen(PORT, async () => {
411
+ console.log(`🎬 FacelessFlowAI Renderer running on port ${PORT}`);
412
 
413
  const os = await import('os');
414
  console.log(`💾 Memory: ${Math.round(os.totalmem() / (1024 * 1024 * 1024))}GB`);
415
  console.log(`⚡ CPU Cores: ${os.cpus().length}`);
416
 
417
+ // Check NVENC
418
  try {
419
  const { execSync } = await import('child_process');
420
+ const nvenc = execSync('ffmpeg -encoders 2>/dev/null | grep -i nvenc | head -1', { encoding: 'utf8' });
421
+ console.log(`⚡ NVENC: ${nvenc.trim()}`);
422
+ } catch {
423
+ console.log('⚡ NVENC: Not detected');
 
 
 
 
 
 
 
 
424
  }
425
 
426
+ console.log('--- Configuration ---');
427
+ console.log('CONCURRENCY: Dynamic (max 6)');
428
+ console.log('ENCODING: NVENC hardware when available');
429
+ console.log('CHROME: GPU accelerated');
430
+ console.log('---------------------');
 
431
 
432
  // Auto-warmup
433
  setTimeout(async () => {
434
  try {
435
  await getCachedBundle();
436
  console.log('[Auto-Warmup] Bundle ready');
 
 
 
 
 
 
 
 
 
437
  } catch (error) {
438
  console.error('[Auto-Warmup] Failed:', error.message);
439
  }
440
+ }, 3000);
441
  });