Stylique commited on
Commit
d052d5e
·
verified ·
1 Parent(s): f0ec536

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +78 -31
server.js CHANGED
@@ -2,7 +2,7 @@ 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 } from 'fs/promises';
6
  import { tmpdir } from 'os';
7
  import { join, dirname } from 'path';
8
  import { randomUUID } from 'crypto';
@@ -73,39 +73,86 @@ app.post('/render', async (req, res) => {
73
  // Tuning for CPU Only
74
  // Remotion is CPU-bound. Concurrency = CPU Cores is usually good,
75
  // but we leave 1 core for OS/Orchestration.
 
 
76
  const safeConcurrency = 1;
77
- console.log(`[Render] Requesting concurrency: ${safeConcurrency} (Host has ${cpuCount})`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
- let lastLog = 0;
80
 
81
- await renderMedia({
82
- composition,
83
- serveUrl: bundleLocation,
84
- codec: 'h264',
85
- pixelFormat: 'yuv420p',
86
- outputLocation: outputPath,
87
- imageFormat: 'jpeg',
88
- jpegQuality: 80,
89
- inputProps: { scenes, settings },
90
- chromiumOptions: {
91
- executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome-stable',
92
- enableMultiProcessRendering: true,
93
- args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-software-rasterizer']
94
- },
95
- concurrency: safeConcurrency,
96
- disallowParallelEncoding: false,
97
- onProgress: ({ progress }) => {
98
- const percent = Math.round(progress * 100);
99
- // Log every 1%
100
- if (percent - lastLog >= 1 || percent === 100) {
101
- console.log(`[Render] Progress: ${percent}%`);
102
- lastLog = percent;
103
- }
104
- },
105
- // Default software encoder (libx264) is robust and decent speed on high CPU
106
- });
107
 
108
- console.log(`[Render] Render complete. Uploading to Supabase...`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
  const videoBuffer = await readFile(outputPath);
111
 
@@ -113,7 +160,7 @@ app.post('/render', async (req, res) => {
113
  const fileName = `${projectId}/video-${Date.now()}.mp4`;
114
  const { data: uploadData, error: uploadError } = await supabase
115
  .storage
116
- .from('projects') // Assuming 'projects' bucket exists
117
  .upload(fileName, videoBuffer, {
118
  contentType: 'video/mp4',
119
  upsert: true
 
2
  import cors from 'cors';
3
  import { bundle } from '@remotion/bundler';
4
  import { renderMedia, selectComposition } from '@remotion/renderer';
5
+ import { readFile, mkdir, rm, writeFile } from 'fs/promises';
6
  import { tmpdir } from 'os';
7
  import { join, dirname } from 'path';
8
  import { randomUUID } from 'crypto';
 
73
  // Tuning for CPU Only
74
  // Remotion is CPU-bound. Concurrency = CPU Cores is usually good,
75
  // but we leave 1 core for OS/Orchestration.
76
+ // Tuning for Maximum Stability (Hugging Face Spaces)
77
+ // We reduce concurrency to 1 to drastically minimize memory usage.
78
  const safeConcurrency = 1;
79
+ console.log(`[Render] Requesting concurrency: ${safeConcurrency} (Stability Mode)`);
80
+
81
+ // --- CHUNKED RENDERING STRATEGY ---
82
+ // To prevent OOM on long videos (1hr+), we render in small chunks (e.g. 5000 frames / ~2.5 mins)
83
+ // and stitch them together with FFmpeg.
84
+ // This ensures the browser session doesn't accumulate too much memory.
85
+
86
+ const totalFrames = composition.durationInFrames;
87
+ const CHUNK_SIZE = 4500; // ~2.5 minutes at 30fps. Conservative safe limit.
88
+ const chunkPaths = [];
89
+
90
+ console.log(`[Render] Total Frames: ${totalFrames}. Chunk Size: ${CHUNK_SIZE}. Total Chunks: ${Math.ceil(totalFrames / CHUNK_SIZE)}`);
91
+
92
+ for (let i = 0; i < totalFrames; i += CHUNK_SIZE) {
93
+ const startFrame = i;
94
+ const endFrame = Math.min(i + CHUNK_SIZE - 1, totalFrames - 1);
95
+ const chunkIndex = Math.floor(i / CHUNK_SIZE);
96
+ const chunkPath = join(tempDir, `chunk_${chunkIndex}.mp4`);
97
+
98
+ console.log(`[Render] Processing Chunk ${chunkIndex + 1}/${Math.ceil(totalFrames / CHUNK_SIZE)} (Frames ${startFrame}-${endFrame})`);
99
+
100
+ // Explicitly launching a fresh render for each chunk clears memory
101
+ await renderMedia({
102
+ composition,
103
+ serveUrl: bundleLocation,
104
+ codec: 'h264',
105
+ pixelFormat: 'yuv420p',
106
+ outputLocation: chunkPath,
107
+ imageFormat: 'jpeg',
108
+ jpegQuality: 80,
109
+ inputProps: { scenes, settings },
110
+ frameRange: [startFrame, endFrame], // Only render this segment
111
+ chromiumOptions: {
112
+ executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome-stable',
113
+ enableMultiProcessRendering: true,
114
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-software-rasterizer']
115
+ },
116
+ concurrency: safeConcurrency,
117
+ disallowParallelEncoding: false,
118
+ onProgress: ({ progress }) => {
119
+ // Normalize progress relative to the whole video
120
+ // Chunk progress (0-1) * Fraction of Total + Start Fraction
121
+ const chunkProgress = progress;
122
+ const totalProgress = (i + (chunkProgress * (endFrame - startFrame))) / totalFrames;
123
+ const percent = Math.round(totalProgress * 100);
124
+
125
+ if (percent - lastLog >= 1 || percent === 100) {
126
+ console.log(`[Render] Total Progress: ${percent}% (Chunk ${chunkIndex}: ${Math.round(chunkProgress * 100)}%)`);
127
+ lastLog = percent;
128
+ }
129
+ },
130
+ });
131
 
132
+ chunkPaths.push(chunkPath);
133
 
134
+ // Small delay to let system settle/GC
135
+ await new Promise(r => setTimeout(r, 1000));
136
+ }
137
+
138
+ console.log(`[Render] All chunks rendered. Stitching with FFmpeg...`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
+ // Creates a text file for FFmpeg concat demuxer
141
+ // Format: file '/path/to/chunk_0.mp4'
142
+ const listPath = join(tempDir, 'chunks_list.txt');
143
+ const fileContent = chunkPaths.map(p => `file '${p}'`).join('\n');
144
+ await writeFile(listPath, fileContent);
145
+
146
+ // Execute FFmpeg Stitch
147
+ const { exec } = await import('child_process');
148
+ const { promisify } = await import('util');
149
+ const execAsync = promisify(exec);
150
+
151
+ // -f concat -safe 0 -i list.txt -c copy (copy is purely lossless and instant)
152
+ await execAsync(`ffmpeg -f concat -safe 0 -i "${listPath}" -c copy "${outputPath}"`);
153
+
154
+ console.log(`[Render] Stitch complete. Output size: ${(await (await import('fs/promises')).stat(outputPath)).size} bytes.`);
155
+ console.log(`[Render] Uploading to Supabase...`);
156
 
157
  const videoBuffer = await readFile(outputPath);
158
 
 
160
  const fileName = `${projectId}/video-${Date.now()}.mp4`;
161
  const { data: uploadData, error: uploadError } = await supabase
162
  .storage
163
+ .from('projects')
164
  .upload(fileName, videoBuffer, {
165
  contentType: 'video/mp4',
166
  upsert: true