Stylique commited on
Commit
32e5cd3
·
verified ·
1 Parent(s): 3be7756

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +55 -115
server.js CHANGED
@@ -3,7 +3,6 @@ import cors from 'cors';
3
  import { bundle } from '@remotion/bundler';
4
  import { renderMedia, selectComposition } from '@remotion/renderer';
5
  import { readFile, mkdir, rm } from 'fs/promises';
6
- import { existsSync } from 'fs';
7
  import { tmpdir } from 'os';
8
  import { join, dirname } from 'path';
9
  import { randomUUID } from 'crypto';
@@ -43,44 +42,26 @@ async function getCachedBundle() {
43
  console.log('[Performance] Creating new bundle');
44
 
45
  try {
46
- // Clean up old bundle cache
47
- if (cachedBundle && cachedBundle.startsWith('/tmp/remotion-webpack-bundle-')) {
48
- try {
49
- if (existsSync(cachedBundle)) {
50
- await rm(cachedBundle, { recursive: true, force: true });
51
- }
52
- } catch (e) {
53
- // Ignore cleanup errors
54
- }
55
- }
56
-
57
- // Create bundle with explicit output configuration
58
  cachedBundle = await bundle({
59
  entryPoint: join(__dirname, 'remotion', 'index.tsx'),
60
  webpackOverride: (config) => {
61
- // Ensure bundle.js is created properly
62
  config.output = {
63
  ...config.output,
64
- path: join(__dirname, 'dist'),
65
  filename: 'bundle.js',
66
  publicPath: '/',
67
  };
68
 
69
- // Disable code splitting to ensure single bundle
70
  config.optimization = {
71
  ...config.optimization,
72
  splitChunks: false,
73
  runtimeChunk: false,
74
  };
75
 
76
- // Production optimizations
77
  config.mode = 'production';
78
  config.devtool = false;
79
 
80
  return config;
81
  },
82
- // Force fresh build
83
- ignoreRegisterRootWarning: true,
84
  });
85
 
86
  console.log(`[Bundle] Bundle created at: ${cachedBundle}`);
@@ -92,14 +73,17 @@ async function getCachedBundle() {
92
  }
93
  }
94
 
95
- // Function to check if Chrome is available
96
- async function checkChrome() {
 
 
97
  try {
98
  const { execSync } = await import('child_process');
99
- execSync(`${process.env.CHROME_BIN || '/usr/bin/google-chrome-stable'} --version`, { stdio: 'pipe' });
 
100
  return true;
101
  } catch (error) {
102
- console.log('[Chrome] Chrome not found, will download headless shell');
103
  return false;
104
  }
105
  }
@@ -137,50 +121,16 @@ app.post('/render', async (req, res) => {
137
  try {
138
  console.log(`[Render] Starting render for project ${projectId}`);
139
 
140
- // Check Chrome before proceeding
141
- const chromeAvailable = await checkChrome();
142
- if (!chromeAvailable) {
143
- console.log('[Chrome] Using Remotion headless shell');
144
- }
145
-
146
  const bundleLocation = await getCachedBundle();
147
  console.log('[Bundle] Bundle ready');
148
 
149
- // Verify bundle exists
150
- const bundlePath = join(bundleLocation, 'bundle.js');
151
- if (!existsSync(bundlePath)) {
152
- console.log(`[Bundle] bundle.js not found at ${bundlePath}, trying alternative locations`);
153
-
154
- // Try to find bundle.js in the bundleLocation itself (it might be the file)
155
- if (existsSync(bundleLocation) && bundleLocation.endsWith('.js')) {
156
- console.log(`[Bundle] Using bundleLocation as file: ${bundleLocation}`);
157
- } else {
158
- // Check parent directory
159
- const parentDir = dirname(bundleLocation);
160
- const parentBundlePath = join(parentDir, 'bundle.js');
161
- if (existsSync(parentBundlePath)) {
162
- console.log(`[Bundle] Found at parent directory: ${parentBundlePath}`);
163
- } else {
164
- throw new Error(`Bundle not found. Checked: ${bundlePath}, ${bundleLocation}, ${parentBundlePath}`);
165
- }
166
- }
167
- } else {
168
- console.log('[Bundle] bundle.js verified');
169
- }
170
-
171
  const composition = await selectComposition({
172
  serveUrl: bundleLocation,
173
  id: 'Main',
174
  inputProps: { scenes, settings },
175
  chromiumOptions: {
176
- executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome-stable',
177
- args: ['--no-sandbox', '--disable-dev-shm-usage'],
178
- // Prevent downloading if Chrome is available
179
- onBrowserDownload: chromeAvailable ? undefined : (progress) => {
180
- const downloadedMB = (progress.downloadedBytes / 1024 / 1024).toFixed(1);
181
- const totalMB = (progress.totalSize / 1024 / 1024).toFixed(1);
182
- console.log(`[Chrome] Downloading headless shell: ${downloadedMB}Mb/${totalMB}Mb`);
183
- }
184
  },
185
  });
186
 
@@ -192,17 +142,21 @@ app.post('/render', async (req, res) => {
192
 
193
  console.log('[Render] Starting video rendering...');
194
 
195
- // Try to detect NVENC
196
- let useNvenc = false;
197
- try {
198
- const { execSync } = await import('child_process');
199
- execSync('ffmpeg -encoders 2>/dev/null | grep -i nvenc', { stdio: 'pipe' });
200
- useNvenc = true;
201
- console.log('[FFmpeg] NVENC hardware encoding available');
202
- } catch (e) {
203
- console.log('[FFmpeg] Using software encoding (libx264)');
204
  }
205
 
 
 
 
 
 
206
  await renderMedia({
207
  composition,
208
  serveUrl: bundleLocation,
@@ -213,36 +167,34 @@ app.post('/render', async (req, res) => {
213
  jpegQuality: 80,
214
  inputProps: { scenes, settings },
215
  chromiumOptions: {
216
- executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome-stable',
217
- args: ['--no-sandbox', '--disable-dev-shm-usage']
218
  },
219
- concurrency: 8,
220
- disallowParallelEncoding: false,
221
  onProgress: ({ progress }) => {
222
  const percent = Math.round(progress * 100);
223
  console.log(`[Progress] ${percent}%`);
224
  },
225
  ffmpegOverride: ({ args }) => {
226
- if (useNvenc) {
227
- return [
228
- ...args,
229
- '-c:v', 'h264_nvenc',
230
- '-preset', 'p1',
231
- '-cq', '23',
232
- '-movflags', '+faststart',
233
- ];
234
- } else {
235
- return [
236
- ...args,
237
- '-c:v', 'libx264',
238
- '-preset', 'fast',
239
- '-crf', '23',
240
- '-movflags', '+faststart',
241
- ];
242
- }
243
  },
244
  audioBitrate: '192k',
245
  videoBitrate: '8M',
 
246
  });
247
 
248
  const renderTime = Date.now() - startTime;
@@ -295,6 +247,7 @@ app.post('/render', async (req, res) => {
295
 
296
  } catch (error) {
297
  console.error(`[Render] Error for ${projectId}:`, error.message);
 
298
 
299
  // Update project status to 'error'
300
  try {
@@ -316,23 +269,14 @@ app.post('/render', async (req, res) => {
316
  app.get('/status', async (req, res) => {
317
  const os = await import('os');
318
 
319
- let gpuInfo = 'Not detected';
320
- try {
321
- const { execSync } = await import('child_process');
322
- const gpu = execSync('lspci | grep -i vga || echo "No GPU"', { encoding: 'utf8' });
323
- gpuInfo = gpu.trim();
324
- } catch (e) {
325
- gpuInfo = 'GPU check failed';
326
- }
327
-
328
  res.json({
329
  status: 'running',
330
- gpu: gpuInfo,
331
  cpu_cores: os.cpus().length,
332
  total_memory: Math.round(os.totalmem() / (1024 * 1024 * 1024)) + 'GB',
333
  free_memory: Math.round(os.freemem() / (1024 * 1024 * 1024)) + 'GB',
334
  bundle_cached: cachedBundle !== null,
335
- uptime: Math.round(process.uptime()) + 's'
 
336
  });
337
  });
338
 
@@ -343,11 +287,14 @@ app.get('/warmup', async (req, res) => {
343
  await getCachedBundle();
344
  console.log('[Warmup] Bundle ready');
345
 
346
- // Trigger Chrome check
347
- await checkChrome();
348
  console.log('[Warmup] Chrome ready');
349
 
350
- res.json({ status: 'warmed_up' });
 
 
 
351
  } catch (error) {
352
  console.error('[Warmup] Error:', error.message);
353
  res.status(500).json({ error: error.message });
@@ -362,18 +309,11 @@ app.listen(PORT, async () => {
362
  console.log(`💾 Memory: ${Math.round(os.totalmem() / (1024 * 1024 * 1024))}GB`);
363
  console.log(`⚡ CPU Cores: ${os.cpus().length}`);
364
 
365
- // Check GPU
366
- try {
367
- const { execSync } = await import('child_process');
368
- const gpu = execSync('lspci | grep -i vga 2>/dev/null || echo "No GPU detected"', { encoding: 'utf8' });
369
- console.log(`🎮 GPU: ${gpu.trim()}`);
370
- } catch (e) {
371
- console.log(`🎮 GPU: Not detected`);
372
- }
373
-
374
- console.log('--- Environment ---');
375
- console.log('CHROME_BIN:', process.env.CHROME_BIN || 'default');
376
- console.log('------------------');
377
 
378
  // Auto-warmup
379
  setTimeout(async () => {
 
3
  import { bundle } from '@remotion/bundler';
4
  import { renderMedia, selectComposition } from '@remotion/renderer';
5
  import { readFile, mkdir, rm } from 'fs/promises';
 
6
  import { tmpdir } from 'os';
7
  import { join, dirname } from 'path';
8
  import { randomUUID } from 'crypto';
 
42
  console.log('[Performance] Creating new bundle');
43
 
44
  try {
 
 
 
 
 
 
 
 
 
 
 
 
45
  cachedBundle = await bundle({
46
  entryPoint: join(__dirname, 'remotion', 'index.tsx'),
47
  webpackOverride: (config) => {
 
48
  config.output = {
49
  ...config.output,
 
50
  filename: 'bundle.js',
51
  publicPath: '/',
52
  };
53
 
 
54
  config.optimization = {
55
  ...config.optimization,
56
  splitChunks: false,
57
  runtimeChunk: false,
58
  };
59
 
 
60
  config.mode = 'production';
61
  config.devtool = false;
62
 
63
  return config;
64
  },
 
 
65
  });
66
 
67
  console.log(`[Bundle] Bundle created at: ${cachedBundle}`);
 
73
  }
74
  }
75
 
76
+ // Pre-download Chrome to avoid download during render
77
+ async function ensureChrome() {
78
+ console.log('[Chrome] Checking Chrome availability...');
79
+
80
  try {
81
  const { execSync } = await import('child_process');
82
+ execSync('/usr/bin/google-chrome-stable --version', { stdio: 'pipe' });
83
+ console.log('[Chrome] Chrome is available');
84
  return true;
85
  } catch (error) {
86
+ console.log('[Chrome] Chrome not available, will use headless shell');
87
  return false;
88
  }
89
  }
 
121
  try {
122
  console.log(`[Render] Starting render for project ${projectId}`);
123
 
 
 
 
 
 
 
124
  const bundleLocation = await getCachedBundle();
125
  console.log('[Bundle] Bundle ready');
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  const composition = await selectComposition({
128
  serveUrl: bundleLocation,
129
  id: 'Main',
130
  inputProps: { scenes, settings },
131
  chromiumOptions: {
132
+ executablePath: '/usr/bin/google-chrome-stable',
133
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
 
 
 
 
 
 
134
  },
135
  });
136
 
 
142
 
143
  console.log('[Render] Starting video rendering...');
144
 
145
+ // Calculate optimal concurrency based on video length
146
+ const videoDuration = composition.durationInFrames / composition.fps; // in seconds
147
+ let concurrency = 8; // Default for L4
148
+
149
+ if (videoDuration > 120) { // Longer than 2 minutes
150
+ concurrency = 4; // Reduce concurrency for long videos
151
+ } else if (videoDuration < 30) { // Less than 30 seconds
152
+ concurrency = 12; // Increase concurrency for short videos
 
153
  }
154
 
155
+ console.log(`[Config] Video duration: ${Math.round(videoDuration)}s, using concurrency: ${concurrency}`);
156
+
157
+ // FORCE software encoding - NVENC is causing issues on Hugging Face
158
+ const useSoftwareEncoding = true; // Always use software encoding on HF
159
+
160
  await renderMedia({
161
  composition,
162
  serveUrl: bundleLocation,
 
167
  jpegQuality: 80,
168
  inputProps: { scenes, settings },
169
  chromiumOptions: {
170
+ executablePath: '/usr/bin/google-chrome-stable',
171
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
172
  },
173
+ concurrency: concurrency,
174
+ disallowParallelEncoding: true, // Important for stability
175
  onProgress: ({ progress }) => {
176
  const percent = Math.round(progress * 100);
177
  console.log(`[Progress] ${percent}%`);
178
  },
179
  ffmpegOverride: ({ args }) => {
180
+ // ALWAYS use software encoding on Hugging Face
181
+ // NVENC detection is unreliable and causes crashes
182
+ console.log('[FFmpeg] Using software encoding (libx264) for stability');
183
+
184
+ return [
185
+ ...args,
186
+ '-c:v', 'libx264',
187
+ '-preset', 'medium', // Better quality than 'fast'
188
+ '-crf', '23',
189
+ '-movflags', '+faststart',
190
+ '-pix_fmt', 'yuv420p',
191
+ '-maxrate', '8M',
192
+ '-bufsize', '16M',
193
+ ];
 
 
 
194
  },
195
  audioBitrate: '192k',
196
  videoBitrate: '8M',
197
+ muted: false,
198
  });
199
 
200
  const renderTime = Date.now() - startTime;
 
247
 
248
  } catch (error) {
249
  console.error(`[Render] Error for ${projectId}:`, error.message);
250
+ console.error('[Error Details]', error.stack);
251
 
252
  // Update project status to 'error'
253
  try {
 
269
  app.get('/status', async (req, res) => {
270
  const os = await import('os');
271
 
 
 
 
 
 
 
 
 
 
272
  res.json({
273
  status: 'running',
 
274
  cpu_cores: os.cpus().length,
275
  total_memory: Math.round(os.totalmem() / (1024 * 1024 * 1024)) + 'GB',
276
  free_memory: Math.round(os.freemem() / (1024 * 1024 * 1024)) + 'GB',
277
  bundle_cached: cachedBundle !== null,
278
+ uptime: Math.round(process.uptime()) + 's',
279
+ note: 'Using software encoding for stability'
280
  });
281
  });
282
 
 
287
  await getCachedBundle();
288
  console.log('[Warmup] Bundle ready');
289
 
290
+ // Pre-download Chrome if needed
291
+ await ensureChrome();
292
  console.log('[Warmup] Chrome ready');
293
 
294
+ res.json({
295
+ status: 'warmed_up',
296
+ note: 'Renderer is ready for video production'
297
+ });
298
  } catch (error) {
299
  console.error('[Warmup] Error:', error.message);
300
  res.status(500).json({ error: error.message });
 
309
  console.log(`💾 Memory: ${Math.round(os.totalmem() / (1024 * 1024 * 1024))}GB`);
310
  console.log(`⚡ CPU Cores: ${os.cpus().length}`);
311
 
312
+ console.log('--- Configuration ---');
313
+ console.log('ENCODING: Software (libx264) - most stable');
314
+ console.log('CONCURRENCY: Adaptive based on video length');
315
+ console.log('CHROME: Using system Chrome');
316
+ console.log('---------------------');
 
 
 
 
 
 
 
317
 
318
  // Auto-warmup
319
  setTimeout(async () => {