Repository navigation
Expand file tree
/
Copy pathprocess_puppeteer.ts
More file actions
154 lines (127 loc) · 5.34 KB
/
Copy pathprocess_puppeteer.ts
File metadata and controls
154 lines (127 loc) · 5.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import * as fs from 'fs';
import * as path from 'path';
import { execSync } from 'child_process';
import express from 'express';
import puppeteer from 'puppeteer';
async function run() {
const inputVideo = process.argv[2];
const outputVideo = process.argv[3];
if (!inputVideo || !outputVideo) {
console.error("Usage: npx ts-node process_puppeteer.ts <input> <output>");
process.exit(1);
}
const framesDir = path.join(__dirname, 'frames_in');
const outFramesDir = path.join(__dirname, 'frames_out');
let frames = [];
if (fs.existsSync(framesDir) && fs.readdirSync(framesDir).length > 1000) {
console.log("Frames already extracted.");
if (fs.existsSync(outFramesDir)) fs.rmSync(outFramesDir, { recursive: true, force: true });
fs.mkdirSync(outFramesDir);
frames = fs.readdirSync(framesDir).filter(f => f.endsWith('.jpg')).sort();
} else {
if (fs.existsSync(framesDir)) fs.rmSync(framesDir, { recursive: true, force: true });
if (fs.existsSync(outFramesDir)) fs.rmSync(outFramesDir, { recursive: true, force: true });
fs.mkdirSync(framesDir);
fs.mkdirSync(outFramesDir);
console.log("Extracting frames...");
execSync(`ffmpeg -y -i "${inputVideo}" -vf fps=30 "${framesDir}/frame_%04d.jpg"`, { stdio: 'inherit' });
frames = fs.readdirSync(framesDir).filter(f => f.endsWith('.jpg')).sort();
console.log(`Extracted ${frames.length} frames.`);
}
// 1. Start Express to serve frames and receive output
const app = (express as any)();
app.use((req: any, res: any, next: any) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use((express as any).json({ limit: '10mb' }));
app.use('/frames_in', (express as any).static(framesDir));
app.get('/list', (req: any, res: any) => res.json(frames));
app.post('/save', (req: any, res: any) => {
const { file, base64 } = req.body;
const data = base64.replace(/^data:image\/\w+;base64,/, "");
fs.writeFileSync(path.join(outFramesDir, file), data, 'base64');
res.json({ ok: true });
});
const server = app.listen(4000, () => console.log('Backend listening on 4000'));
// 2. Start Vite server for the runner
const runnerDir = path.join(__dirname, 'runner');
if (!fs.existsSync(runnerDir)) fs.mkdirSync(runnerDir);
fs.writeFileSync(path.join(runnerDir, 'index.html'), `
<!DOCTYPE html>
<html>
<body>
<h1>Processing...</h1>
<script type="module" src="/main.ts"></script>
</body>
</html>
`);
fs.writeFileSync(path.join(runnerDir, 'main.ts'), `
import { Encoder, Decoder } from '../src/index.ts';
async function process() {
try {
const encoder = new Encoder({ keyframeInterval: 3 });
const decoder = new Decoder();
console.log("Initializing...");
await encoder.initialize();
await decoder.initialize();
console.log("Initialized.");
const res = await fetch('http://localhost:4000/list');
const frames = await res.json();
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
for (let i = 0; i < frames.length; i++) {
const file = frames[i];
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = 'http://localhost:4000/frames_in/' + file;
await new Promise(r => { img.onload = r; });
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, img.width, img.height);
const payload = await encoder.encode(imageData, i * (1000/30));
let finalImageData = imageData; // Fallback to original
if (payload) {
const decoded = await decoder.decode(payload);
if (decoded) {
finalImageData = decoded;
}
}
ctx.putImageData(finalImageData, 0, 0);
const base64 = canvas.toDataURL('image/jpeg', 0.9);
await fetch('http://localhost:4000/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file, base64 })
});
if (i % 10 === 0) console.log('Processed ' + i + '/' + frames.length);
}
console.log('DONE');
(window as any).DONE = true;
} catch(e) {
console.error(e);
(window as any).ERROR = e.toString();
}
}
process();
`);
const viteProc = require('child_process').spawn('npx', ['vite', 'serve', 'runner', '--port', '5174'], { stdio: 'pipe' });
await new Promise(r => setTimeout(r, 2000));
console.log("Launching Puppeteer...");
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] });
const page = await browser.newPage();
page.on('console', msg => console.log('PAGE:', msg.text()));
await page.goto('http://localhost:5174', { waitUntil: 'networkidle2' });
await page.waitForFunction(() => (window as any).DONE || (window as any).ERROR, { timeout: 0 });
const err = await page.evaluate(() => (window as any).ERROR);
if (err) console.error("Page Error:", err);
await browser.close();
viteProc.kill();
server.close();
console.log("Reassembling video...");
execSync(`ffmpeg -y -framerate 30 -pattern_type glob -i "${outFramesDir}/*.jpg" -c:v libx264 -pix_fmt yuv420p "${outputVideo}"`, { stdio: 'inherit' });
console.log("Finished! Output at " + outputVideo);
}
run().catch(console.error);