Update server.js
Browse files
server.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
|
|
| 1 |
import express from 'express';
|
| 2 |
import cors from 'cors';
|
| 3 |
import { bundle } from '@remotion/bundler';
|
| 4 |
import { renderMedia, selectComposition } from '@remotion/renderer';
|
| 5 |
-
import { readFile, mkdir, rm
|
| 6 |
import { tmpdir } from 'os';
|
| 7 |
import { join, dirname } from 'path';
|
| 8 |
import { randomUUID } from 'crypto';
|
|
@@ -17,16 +18,6 @@ const PORT = process.env.PORT || 7860;
|
|
| 17 |
app.use(cors());
|
| 18 |
app.use(express.json({ limit: '50mb' }));
|
| 19 |
|
| 20 |
-
// Global Error Handlers to prevent crash on ProtocolError
|
| 21 |
-
process.on('uncaughtException', (err) => {
|
| 22 |
-
console.error('[Fatal] Uncaught Exception:', err);
|
| 23 |
-
// Keep process alive if possible, or at least log fully
|
| 24 |
-
});
|
| 25 |
-
|
| 26 |
-
process.on('unhandledRejection', (reason, promise) => {
|
| 27 |
-
console.error('[Fatal] Unhandled Rejection at:', promise, 'reason:', reason);
|
| 28 |
-
});
|
| 29 |
-
|
| 30 |
// Health check
|
| 31 |
app.get('/', (req, res) => {
|
| 32 |
res.json({ status: 'ok', service: 'FacelessFlowAI Video Renderer' });
|
|
@@ -65,27 +56,11 @@ app.post('/render', async (req, res) => {
|
|
| 65 |
webpackOverride: (config) => config,
|
| 66 |
});
|
| 67 |
|
| 68 |
-
// Nuclear Chrome Flags for Container Stability
|
| 69 |
-
// nuclear Chrome Flags for Container Stability
|
| 70 |
-
// Removing --single-process as it can be unstable
|
| 71 |
-
const CHROMIUM_FLAGS = [
|
| 72 |
-
'--no-sandbox',
|
| 73 |
-
'--disable-setuid-sandbox',
|
| 74 |
-
'--disable-dev-shm-usage',
|
| 75 |
-
'--disable-accelerated-2d-canvas',
|
| 76 |
-
'--disable-gpu',
|
| 77 |
-
'--no-first-run',
|
| 78 |
-
'--disable-extensions'
|
| 79 |
-
];
|
| 80 |
-
|
| 81 |
const composition = await selectComposition({
|
| 82 |
serveUrl: bundleLocation,
|
| 83 |
id: 'Main',
|
| 84 |
inputProps: { scenes, settings },
|
| 85 |
-
chromiumOptions: {
|
| 86 |
-
executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome-stable',
|
| 87 |
-
args: CHROMIUM_FLAGS
|
| 88 |
-
},
|
| 89 |
});
|
| 90 |
|
| 91 |
const tempDir = join(tmpdir(), `remotion-${randomUUID()}`);
|
|
@@ -99,112 +74,40 @@ app.post('/render', async (req, res) => {
|
|
| 99 |
// Tuning for CPU Only
|
| 100 |
// Remotion is CPU-bound. Concurrency = CPU Cores is usually good,
|
| 101 |
// but we leave 1 core for OS/Orchestration.
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
const safeConcurrency = 1;
|
| 105 |
-
console.log(`[Render] Requesting concurrency: ${safeConcurrency} (Stability Mode)`);
|
| 106 |
-
|
| 107 |
-
// --- CHUNKED RENDERING STRATEGY ---
|
| 108 |
-
// To prevent OOM on long videos (1hr+), we render in small chunks
|
| 109 |
-
// and stitch them together with FFmpeg.
|
| 110 |
-
|
| 111 |
-
const totalFrames = composition.durationInFrames;
|
| 112 |
-
// Reduced to 1000 frames (~33 sec) to be ultra-safe against crashes
|
| 113 |
-
const CHUNK_SIZE = 1000;
|
| 114 |
-
const chunkPaths = [];
|
| 115 |
-
|
| 116 |
-
console.log(`[Render] Total Frames: ${totalFrames}. Chunk Size: ${CHUNK_SIZE}. Total Chunks: ${Math.ceil(totalFrames / CHUNK_SIZE)}`);
|
| 117 |
-
|
| 118 |
-
for (let i = 0; i < totalFrames; i += CHUNK_SIZE) {
|
| 119 |
-
const startFrame = i;
|
| 120 |
-
const endFrame = Math.min(i + CHUNK_SIZE - 1, totalFrames - 1);
|
| 121 |
-
const chunkIndex = Math.floor(i / CHUNK_SIZE);
|
| 122 |
-
const chunkPath = join(tempDir, `chunk_${chunkIndex}.mp4`);
|
| 123 |
-
|
| 124 |
-
console.log(`[Render] Processing Chunk ${chunkIndex + 1}/${Math.ceil(totalFrames / CHUNK_SIZE)} (Frames ${startFrame}-${endFrame})`);
|
| 125 |
-
|
| 126 |
-
let attempts = 0;
|
| 127 |
-
const maxRetries = 3;
|
| 128 |
-
let success = false;
|
| 129 |
-
|
| 130 |
-
while (attempts < maxRetries && !success) {
|
| 131 |
-
attempts++;
|
| 132 |
-
try {
|
| 133 |
-
let lastLog = 0; // Fix: Define lastLog per attempt
|
| 134 |
|
| 135 |
-
|
| 136 |
-
await renderMedia({
|
| 137 |
-
composition,
|
| 138 |
-
serveUrl: bundleLocation,
|
| 139 |
-
codec: 'h264',
|
| 140 |
-
pixelFormat: 'yuv420p',
|
| 141 |
-
outputLocation: chunkPath,
|
| 142 |
-
imageFormat: 'jpeg',
|
| 143 |
-
jpegQuality: 80,
|
| 144 |
-
inputProps: { scenes, settings },
|
| 145 |
-
frameRange: [startFrame, endFrame], // Only render this segment
|
| 146 |
-
chromiumOptions: {
|
| 147 |
-
executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome-stable',
|
| 148 |
-
enableMultiProcessRendering: true, // Re-enable multi-process (default)
|
| 149 |
-
args: [
|
| 150 |
-
'--no-sandbox',
|
| 151 |
-
'--disable-setuid-sandbox',
|
| 152 |
-
'--disable-dev-shm-usage',
|
| 153 |
-
'--disable-accelerated-2d-canvas',
|
| 154 |
-
'--disable-gpu',
|
| 155 |
-
'--no-first-run',
|
| 156 |
-
'--disable-extensions'
|
| 157 |
-
],
|
| 158 |
-
dumpio: true,
|
| 159 |
-
},
|
| 160 |
-
concurrency: safeConcurrency,
|
| 161 |
-
disallowParallelEncoding: false,
|
| 162 |
-
onProgress: ({ progress }) => {
|
| 163 |
-
// Normalize progress relative to the whole video
|
| 164 |
-
// Chunk progress (0-1) * Fraction of Total + Start Fraction
|
| 165 |
-
const chunkProgress = progress;
|
| 166 |
-
const totalProgress = (i + (chunkProgress * (endFrame - startFrame))) / totalFrames;
|
| 167 |
-
const percent = Math.round(totalProgress * 100);
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
}
|
| 182 |
-
}
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
// Small delay to let system settle/GC
|
| 187 |
-
await new Promise(r => setTimeout(r, 1000));
|
| 188 |
-
}
|
| 189 |
-
|
| 190 |
-
console.log(`[Render] All chunks rendered. Stitching with FFmpeg...`);
|
| 191 |
-
|
| 192 |
-
// Creates a text file for FFmpeg concat demuxer
|
| 193 |
-
// Format: file '/path/to/chunk_0.mp4'
|
| 194 |
-
const listPath = join(tempDir, 'chunks_list.txt');
|
| 195 |
-
const fileContent = chunkPaths.map(p => `file '${p}'`).join('\n');
|
| 196 |
-
await writeFile(listPath, fileContent);
|
| 197 |
-
|
| 198 |
-
// Execute FFmpeg Stitch
|
| 199 |
-
const { exec } = await import('child_process');
|
| 200 |
-
const { promisify } = await import('util');
|
| 201 |
-
const execAsync = promisify(exec);
|
| 202 |
-
|
| 203 |
-
// -f concat -safe 0 -i list.txt -c copy (copy is purely lossless and instant)
|
| 204 |
-
await execAsync(`ffmpeg -f concat -safe 0 -i "${listPath}" -c copy "${outputPath}"`);
|
| 205 |
|
| 206 |
-
console.log(`[Render]
|
| 207 |
-
console.log(`[Render] Uploading to Supabase...`);
|
| 208 |
|
| 209 |
const videoBuffer = await readFile(outputPath);
|
| 210 |
|
|
@@ -212,7 +115,7 @@ app.post('/render', async (req, res) => {
|
|
| 212 |
const fileName = `${projectId}/video-${Date.now()}.mp4`;
|
| 213 |
const { data: uploadData, error: uploadError } = await supabase
|
| 214 |
.storage
|
| 215 |
-
.from('projects')
|
| 216 |
.upload(fileName, videoBuffer, {
|
| 217 |
contentType: 'video/mp4',
|
| 218 |
upsert: true
|
|
|
|
| 1 |
+
import 'dotenv/config';
|
| 2 |
import express from 'express';
|
| 3 |
import cors from 'cors';
|
| 4 |
import { bundle } from '@remotion/bundler';
|
| 5 |
import { renderMedia, selectComposition } from '@remotion/renderer';
|
| 6 |
+
import { readFile, mkdir, rm } from 'fs/promises';
|
| 7 |
import { tmpdir } from 'os';
|
| 8 |
import { join, dirname } from 'path';
|
| 9 |
import { randomUUID } from 'crypto';
|
|
|
|
| 18 |
app.use(cors());
|
| 19 |
app.use(express.json({ limit: '50mb' }));
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
// Health check
|
| 22 |
app.get('/', (req, res) => {
|
| 23 |
res.json({ status: 'ok', service: 'FacelessFlowAI Video Renderer' });
|
|
|
|
| 56 |
webpackOverride: (config) => config,
|
| 57 |
});
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
const composition = await selectComposition({
|
| 60 |
serveUrl: bundleLocation,
|
| 61 |
id: 'Main',
|
| 62 |
inputProps: { scenes, settings },
|
| 63 |
+
chromiumOptions: { executablePath: process.env.CHROME_BIN },
|
|
|
|
|
|
|
|
|
|
| 64 |
});
|
| 65 |
|
| 66 |
const tempDir = join(tmpdir(), `remotion-${randomUUID()}`);
|
|
|
|
| 74 |
// Tuning for CPU Only
|
| 75 |
// Remotion is CPU-bound. Concurrency = CPU Cores is usually good,
|
| 76 |
// but we leave 1 core for OS/Orchestration.
|
| 77 |
+
const safeConcurrency = 4;
|
| 78 |
+
console.log(`[Render] Requesting concurrency: ${safeConcurrency} (Host has ${cpuCount})`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
let lastLog = 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
await renderMedia({
|
| 83 |
+
composition,
|
| 84 |
+
serveUrl: bundleLocation,
|
| 85 |
+
codec: 'h264',
|
| 86 |
+
pixelFormat: 'yuv420p',
|
| 87 |
+
outputLocation: outputPath,
|
| 88 |
+
imageFormat: 'jpeg',
|
| 89 |
+
jpegQuality: 80,
|
| 90 |
+
inputProps: { scenes, settings },
|
| 91 |
+
chromiumOptions: {
|
| 92 |
+
executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome-stable',
|
| 93 |
+
enableMultiProcessRendering: true,
|
| 94 |
+
args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-software-rasterizer']
|
| 95 |
+
},
|
| 96 |
+
concurrency: 1,
|
| 97 |
+
disallowParallelEncoding: false,
|
| 98 |
+
timeoutInMilliseconds: 300000, // 5 minutes timeout for slow downloads
|
| 99 |
+
onProgress: ({ progress }) => {
|
| 100 |
+
const percent = Math.round(progress * 100);
|
| 101 |
+
// Log every 1%
|
| 102 |
+
if (percent - lastLog >= 1 || percent === 100) {
|
| 103 |
+
console.log(`[Render] Progress: ${percent}%`);
|
| 104 |
+
lastLog = percent;
|
| 105 |
}
|
| 106 |
+
},
|
| 107 |
+
// Default software encoder (libx264) is robust and decent speed on high CPU
|
| 108 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
console.log(`[Render] Render complete. Uploading to Supabase...`);
|
|
|
|
| 111 |
|
| 112 |
const videoBuffer = await readFile(outputPath);
|
| 113 |
|
|
|
|
| 115 |
const fileName = `${projectId}/video-${Date.now()}.mp4`;
|
| 116 |
const { data: uploadData, error: uploadError } = await supabase
|
| 117 |
.storage
|
| 118 |
+
.from('projects') // Assuming 'projects' bucket exists
|
| 119 |
.upload(fileName, videoBuffer, {
|
| 120 |
contentType: 'video/mp4',
|
| 121 |
upsert: true
|