-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
424 lines (335 loc) · 13.7 KB
/
Copy pathscript.js
File metadata and controls
424 lines (335 loc) · 13.7 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// =====================================================
// script.js — Green Screen Remover (FIXED)
// Fix 1: Transparent background (no color fill)
// Fix 2: Audio is now captured and included in export
// =====================================================
// ---- Get all DOM elements ----
const videoInput = document.getElementById('videoInput');
const bgInput = document.getElementById('bgInput');
const sourceVideo = document.getElementById('sourceVideo');
const outputCanvas = document.getElementById('outputCanvas');
const ctx = outputCanvas.getContext('2d');
const noVideoMsg = document.getElementById('noVideoMsg');
const playBtn = document.getElementById('playBtn');
const exportBtn = document.getElementById('exportBtn');
const exportStatus = document.getElementById('exportStatus');
const bgLabel = document.getElementById('bgLabel');
// Slider controls
const toleranceSlider = document.getElementById('tolerance');
const softnessSlider = document.getElementById('softness');
const spillSlider = document.getElementById('spill');
const bgColorInput = document.getElementById('bgColor');
// Value badges
const toleranceVal = document.getElementById('toleranceVal');
const softnessVal = document.getElementById('softnessVal');
const spillVal = document.getElementById('spillVal');
// ---- App State ----
let bgImage = null;
let isPlaying = false;
let isExporting = false;
let animFrameId = null;
// ---- FIX 2: Audio state ----
// We set up the Web Audio API ONCE when the video loads.
// This captures the video's audio into a MediaStream so
// we can attach it to the recorder later.
let audioDestination = null;
let audioCtxInstance = null;
let audioSetup = false;
// ---- Off-screen canvas for pixel processing ----
const processCanvas = document.createElement('canvas');
const processCtx = processCanvas.getContext('2d');
// =====================================================
// 1. VIDEO FILE UPLOAD
// =====================================================
videoInput.addEventListener('change', function (e) {
const file = e.target.files[0];
if (!file) return;
sourceVideo.src = URL.createObjectURL(file);
sourceVideo.addEventListener('loadedmetadata', function () {
const w = sourceVideo.videoWidth;
const h = sourceVideo.videoHeight;
outputCanvas.width = processCanvas.width = w;
outputCanvas.height = processCanvas.height = h;
outputCanvas.style.display = 'block';
noVideoMsg.style.display = 'none';
playBtn.disabled = false;
exportBtn.disabled = false;
// FIX 2: Set up audio capture as soon as the video is ready.
// Must be called BEFORE the video plays for the first time.
setupAudio();
sourceVideo.currentTime = 0.01;
}, { once: true });
});
sourceVideo.addEventListener('seeked', function () {
if (!isPlaying && !isExporting) {
renderFrame();
}
});
// =====================================================
// FIX 2: AUDIO SETUP
// Web Audio API grabs the audio FROM the video element
// and routes it into a MediaStreamDestination.
// That destination's stream can then be merged with
// the canvas video stream for export.
// =====================================================
function setupAudio() {
if (audioSetup) return; // Only run once
try {
// AudioContext is the main Web Audio controller
audioCtxInstance = new (window.AudioContext || window.webkitAudioContext)();
// Create a "source node" that reads audio FROM our video element
const source = audioCtxInstance.createMediaElementSource(sourceVideo);
// Create a destination that we can later pull a MediaStream from
audioDestination = audioCtxInstance.createMediaStreamDestination();
// Route 1: source → destination (for recording/export)
source.connect(audioDestination);
// Route 2: source → speakers (so user can HEAR audio during preview)
source.connect(audioCtxInstance.destination);
audioSetup = true;
console.log('✅ Audio capture ready');
} catch (err) {
console.warn('⚠️ Audio setup failed:', err);
}
}
// =====================================================
// 2. BACKGROUND IMAGE UPLOAD
// =====================================================
bgInput.addEventListener('change', function (e) {
const file = e.target.files[0];
if (!file) return;
const img = new Image();
img.onload = function () {
bgImage = img;
bgLabel.textContent = '✅ ' + file.name.slice(0, 22);
if (!isPlaying) renderFrame();
};
img.src = URL.createObjectURL(file);
});
// =====================================================
// 3. SLIDER AND COLOR CONTROLS
// =====================================================
toleranceSlider.addEventListener('input', function () {
toleranceVal.textContent = this.value;
if (!isPlaying) renderFrame();
});
softnessSlider.addEventListener('input', function () {
softnessVal.textContent = this.value;
if (!isPlaying) renderFrame();
});
spillSlider.addEventListener('input', function () {
spillVal.textContent = this.value;
if (!isPlaying) renderFrame();
});
bgColorInput.addEventListener('input', function () {
if (!isPlaying) renderFrame();
});
// =====================================================
// 4. PLAY / PAUSE
// =====================================================
playBtn.addEventListener('click', function () {
if (!sourceVideo.src) return;
// FIX 2: AudioContext requires a user gesture to start (browser rule).
// Resuming it here inside a click event satisfies that requirement.
if (audioCtxInstance && audioCtxInstance.state === 'suspended') {
audioCtxInstance.resume();
}
if (isPlaying) {
sourceVideo.pause();
isPlaying = false;
playBtn.textContent = '▶ Play';
cancelAnimationFrame(animFrameId);
} else {
sourceVideo.play();
isPlaying = true;
playBtn.textContent = '⏸ Pause';
renderLoop();
}
});
sourceVideo.addEventListener('ended', function () {
if (!isExporting) {
isPlaying = false;
playBtn.textContent = '▶ Play';
cancelAnimationFrame(animFrameId);
}
});
// =====================================================
// 5. RENDER LOOP
// =====================================================
function renderLoop() {
renderFrame();
if (isPlaying || isExporting) {
animFrameId = requestAnimationFrame(renderLoop);
}
}
// =====================================================
// 6. RENDER FRAME
// FIX 1: Use clearRect() for transparent background
// instead of filling with a solid color.
// =====================================================
function renderFrame() {
if (!sourceVideo.src || sourceVideo.readyState < 2) return;
const w = outputCanvas.width;
const h = outputCanvas.height;
// Draw raw video frame onto the off-screen canvas
processCtx.drawImage(sourceVideo, 0, 0, w, h);
// Read pixel data
const imageData = processCtx.getImageData(0, 0, w, h);
// Remove green pixels
applyChromaKey(
imageData.data,
parseInt(toleranceSlider.value),
parseInt(softnessSlider.value),
parseInt(spillSlider.value)
);
// Write processed pixels back
processCtx.putImageData(imageData, 0, 0);
// ---- FIX 1: BACKGROUND HANDLING ----
if (bgImage) {
// Draw custom background image first
ctx.drawImage(bgImage, 0, 0, w, h);
} else {
// FIX 1: clearRect makes the canvas pixels fully transparent (0,0,0,0)
// The CSS checkerboard pattern on .canvas-wrapper shows through,
// visually indicating "this area is transparent".
// Previously this was fillRect with a dark color — that's why
// the background looked similar to the saree color!
ctx.clearRect(0, 0, w, h);
}
// Draw the processed (green-removed) video frame on top
ctx.drawImage(processCanvas, 0, 0);
}
// =====================================================
// 7. CHROMA KEY ALGORITHM (unchanged)
// =====================================================
function applyChromaKey(data, tolerance, softness, spillAmt) {
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
// How much green dominates over red and blue
const greenness = g - Math.max(r, b);
if (greenness > tolerance) {
// Fully green → fully transparent
data[i + 3] = 0;
} else if (softness > 0 && greenness > (tolerance - softness)) {
// Soft edge zone → partial transparency
const t = (greenness - (tolerance - softness)) / softness;
data[i + 3] = Math.round((1 - t) * 255);
// Reduce green spill on edges
if (spillAmt > 0) {
const reduce = greenness * (spillAmt / 100) * t;
data[i + 1] = Math.max(0, Math.round(g - reduce));
}
} else if (spillAmt > 0 && greenness > 0) {
// Mild green cast — gentle correction, don't distort skin tones
const reduce = greenness * (spillAmt / 100) * 0.3;
data[i + 1] = Math.max(0, Math.round(g - reduce));
}
}
}
// =====================================================
// 8. EXPORT VIDEO
// FIX 2: Merge canvas video stream + audio stream
// so the exported WebM file HAS AUDIO.
// =====================================================
exportBtn.addEventListener('click', function () {
if (!sourceVideo.src || isExporting) return;
if (typeof MediaRecorder === 'undefined') {
exportStatus.textContent = '❌ Your browser does not support video recording.';
return;
}
// FIX 2: Resume AudioContext (needed before recording)
if (audioCtxInstance && audioCtxInstance.state === 'suspended') {
audioCtxInstance.resume();
}
isExporting = true;
exportBtn.disabled = true;
playBtn.disabled = true;
exportStatus.textContent = '⏳ Recording... Please wait for the video to finish.';
// Get the visual stream from the canvas (30 FPS)
const videoStream = outputCanvas.captureStream(30);
// FIX 2: Build the combined stream with both video AND audio tracks
const allTracks = [...videoStream.getVideoTracks()];
if (audioDestination) {
// Add the audio track from our Web Audio destination
const audioTracks = audioDestination.stream.getAudioTracks();
allTracks.push(...audioTracks);
console.log('✅ Audio track added to recording:', audioTracks.length, 'track(s)');
} else {
console.warn('⚠️ No audio track — recording video only');
}
// Combined stream: video pixels + audio
const combinedStream = new MediaStream(allTracks);
// Pick best available codec
const mimeType = MediaRecorder.isTypeSupported('video/webm;codecs=vp9,opus')
? 'video/webm;codecs=vp9,opus' // VP9 video + Opus audio (best quality)
: MediaRecorder.isTypeSupported('video/webm;codecs=vp8,opus')
? 'video/webm;codecs=vp8,opus' // VP8 video + Opus audio (fallback)
: 'video/webm'; // Browser default
const recorder = new MediaRecorder(combinedStream, { mimeType });
const chunks = [];
recorder.ondataavailable = function (e) {
if (e.data.size > 0) chunks.push(e.data);
};
recorder.onstop = function () {
const blob = new Blob(chunks, { type: 'video/webm' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'green-screen-removed.webm';
a.click();
URL.revokeObjectURL(url);
isExporting = false;
isPlaying = false;
exportBtn.disabled = false;
playBtn.disabled = false;
playBtn.textContent = '▶ Play';
cancelAnimationFrame(animFrameId);
exportStatus.textContent = '✅ Export complete! Check your Downloads folder.';
};
function beginRecording() {
recorder.start(100);
sourceVideo.play();
isPlaying = true;
renderLoop();
sourceVideo.addEventListener('ended', function stopExport() {
sourceVideo.removeEventListener('ended', stopExport);
setTimeout(() => recorder.stop(), 300);
}, { once: true });
}
if (sourceVideo.currentTime < 0.1) {
beginRecording();
} else {
sourceVideo.addEventListener('seeked', function () {
beginRecording();
}, { once: true });
sourceVideo.currentTime = 0;
}
});
// =====================================================
// 9. DRAG AND DROP
// =====================================================
function setupDragDrop(dropZone, fileInput) {
dropZone.addEventListener('dragover', function (e) {
e.preventDefault();
dropZone.style.borderColor = '#00ff88';
dropZone.style.background = '#0a1a0a';
});
dropZone.addEventListener('dragleave', function () {
dropZone.style.borderColor = '';
dropZone.style.background = '';
});
dropZone.addEventListener('drop', function (e) {
e.preventDefault();
dropZone.style.borderColor = '';
dropZone.style.background = '';
const file = e.dataTransfer.files[0];
if (!file) return;
const dt = new DataTransfer();
dt.items.add(file);
fileInput.files = dt.files;
fileInput.dispatchEvent(new Event('change'));
});
}
setupDragDrop(document.getElementById('videoDropZone'), videoInput);
setupDragDrop(document.getElementById('bgDropZone'), bgInput);