-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
570 lines (465 loc) · 19.8 KB
/
script.js
File metadata and controls
570 lines (465 loc) · 19.8 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
const state = {
videos: {},
resolutions: {},
names: {},
processedVideos: new Set(),
recordedBlob: null,
isGenerating: false
};
document.addEventListener('DOMContentLoaded', () => {
initializeApp();
});
function initializeApp() {
// Setup file input listeners
for (let i = 1; i <= 5; i++) {
const videoInput = document.getElementById(`video${i}`);
const resSelector = document.getElementById(`res${i}`);
const magicBtn = document.querySelector(`[data-video="${i}"].magic-btn`);
const nameInput = document.getElementById(`name${i}`);
if (videoInput) {
videoInput.addEventListener('change', (e) => handleVideoUpload(e, i));
}
if (resSelector) {
resSelector.addEventListener('change', (e) => {
state.resolutions[i] = e.target.value;
});
}
if (magicBtn) {
magicBtn.addEventListener('click', () => enhanceName(i));
}
if (nameInput) {
nameInput.addEventListener('input', (e) => {
state.names[i] = e.target.value;
});
}
}
// Setup generate button
const generateBtn = document.getElementById('generateBtn');
if (generateBtn) generateBtn.addEventListener('click', generateVideo);
// Setup download button
const downloadBtn = document.getElementById('downloadBtn');
if (downloadBtn) downloadBtn.addEventListener('click', downloadVideo);
// Initialize default values
initializeDefaults();
}
function initializeDefaults() {
// Set default values from inputs
for (let i = 1; i <= 5; i++) {
const resSelector = document.getElementById(`res${i}`);
if (resSelector) {
state.resolutions[i] = resSelector.value;
}
const nameInput = document.getElementById(`name${i}`);
if (nameInput) {
state.names[i] = nameInput.value;
}
}
}
function enhanceName(videoNum) {
const nameInput = document.getElementById(`name${videoNum}`);
const magicBtn = document.querySelector(`[data-video="${videoNum}"].magic-btn`);
if (!nameInput || !nameInput.value) {
showMessage('Please enter a name first', 'error');
return;
}
// Add sparkle emojis
let enhanced = nameInput.value;
if (!enhanced.includes('✨')) {
enhanced = `✨ ${enhanced} ✨`;
}
nameInput.value = enhanced;
state.names[videoNum] = enhanced;
// Animate the button
if (magicBtn) {
magicBtn.style.transform = 'scale(1.2) rotate(360deg)';
setTimeout(() => {
magicBtn.style.transform = 'scale(1) rotate(0deg)';
}, 300);
}
showMessage('Name enhanced! ✨', 'success');
}
function handleVideoUpload(event, videoNum) {
const file = event.target.files[0];
const statusEl = document.getElementById(`status${videoNum}`);
if (!file) {
console.log(`No file selected for video ${videoNum}`);
return;
}
console.log(`Loading video ${videoNum}:`, file.name, file.type, file.size);
try {
showMessage(`Loading video ${videoNum}...`, 'info');
if (statusEl) statusEl.textContent = '⏳ Loading...';
const video = document.createElement('video');
video.preload = 'metadata';
video.src = URL.createObjectURL(file);
// Add timeout for metadata loading
const timeout = setTimeout(() => {
console.error(`Video ${videoNum} metadata loading timeout`);
if (statusEl) statusEl.textContent = '❌ Timeout';
showMessage(`Video ${videoNum} loading timeout`, 'error');
URL.revokeObjectURL(video.src);
}, 10000);
video.onloadedmetadata = () => {
clearTimeout(timeout);
console.log(`Video ${videoNum} metadata loaded successfully`);
console.log(`Video dimensions: ${video.videoWidth}x${video.videoHeight}, duration: ${video.duration}s`);
state.videos[videoNum] = video;
if (statusEl) statusEl.textContent = '✅ Loaded';
showMessage(`Video ${videoNum} loaded!`, 'success');
checkReady();
};
video.onerror = (e) => {
clearTimeout(timeout);
console.error(`Video ${videoNum} error:`, e);
if (statusEl) statusEl.textContent = '❌ Failed';
showMessage(`Failed to load video ${videoNum}`, 'error');
URL.revokeObjectURL(video.src);
};
} catch (error) {
console.error('Error handling video upload:', error);
if (statusEl) statusEl.textContent = '❌ Error';
showMessage(`Error loading video ${videoNum}: ${error.message}`, 'error');
}
}
function checkReady() {
const allLoaded = Object.keys(state.videos).length === 5;
const generateBtn = document.getElementById('generateBtn');
if (generateBtn) generateBtn.disabled = !allLoaded;
if (allLoaded) {
showMessage('✅ All videos loaded! Click Generate.', 'success');
}
}
function showMessage(text, type) {
const msg = document.getElementById('message');
if (msg) {
msg.textContent = text;
msg.className = type;
}
}
function showProgress(percent, text) {
const progress = document.getElementById('progress');
const progressBar = document.getElementById('progressBar');
const progressText = document.getElementById('progressText');
if (progress) progress.style.display = 'block';
if (progressBar) progressBar.style.width = `${percent}%`;
if (progressText) progressText.textContent = text;
}
function hideProgress() {
const progress = document.getElementById('progress');
if (progress) progress.style.display = 'none';
}
async function generateVideo() {
if (state.isGenerating) {
showMessage('Already generating...', 'error');
return;
}
try {
state.isGenerating = true;
console.log('Starting video generation...');
console.log('Loaded videos:', Object.keys(state.videos));
showMessage('Starting video generation...', 'info');
// Get title settings
const titleText = document.getElementById('titleText').value || 'Best';
const top5Text = document.getElementById('top5Text').value || 'TOP 5';
const top5Color = document.getElementById('top5Color').value || '#FF0000';
const rankingObject = document.getElementById('rankingObject').value || 'Moments';
const objectColor = document.getElementById('objectColor').value || '#FFD700';
const endingText = document.getElementById('endingText').value || 'Ever';
const subscribeText = document.getElementById('subscribeText').value || 'Subscribe for more!';
// Setup canvas
const canvas = document.createElement('canvas');
canvas.width = 1080;
canvas.height = 1920;
const ctx = canvas.getContext('2d');
// Setup media recorder
const stream = canvas.captureStream(30);
const mediaRecorder = new MediaRecorder(stream, {
mimeType: 'video/webm',
videoBitsPerSecond: 2500000
});
const chunks = [];
mediaRecorder.ondataavailable = (e) => chunks.push(e.data);
mediaRecorder.onstop = () => {
const blob = new Blob(chunks, { type: 'video/webm' });
state.recordedBlob = blob;
// Show download button
const downloadBtn = document.getElementById('downloadBtn');
if (downloadBtn) {
downloadBtn.style.display = 'block';
downloadBtn.style.background = 'linear-gradient(135deg, #4CAF50 0%, #45a049 100%)';
}
hideProgress();
showMessage('✅ Video generated successfully!', 'success');
};
mediaRecorder.start();
showProgress(0, 'Initializing...');
// Video play order: 3,4,5,2,1
const videoOrder = [3, 4, 5, 2, 1];
for (let i = 0; i < videoOrder.length; i++) {
const videoNum = videoOrder[i];
const video = state.videos[videoNum];
console.log(`Processing video ${videoNum} (index ${i})`);
if (!video) {
console.error(`Video ${videoNum} not found in state.videos:`, Object.keys(state.videos));
throw new Error(`Video ${videoNum} not loaded`);
}
// Show subscribe button before video 2 (after video 5)
if (i === 3) { // After 3,4,5 and before 2
showProgress(60, 'Showing subscribe...');
await showSubscribeButton(ctx, canvas.width, canvas.height, video);
await new Promise(resolve => setTimeout(resolve, 5000)); // 5 seconds
}
showProgress(20 + (i * 15), `Processing video ${i + 1}/5...`);
video.currentTime = 0;
video.muted = true;
await video.play();
state.processedVideos.add(videoNum);
await new Promise((resolve) => {
let frameCount = 0;
const maxFrames = 600;
const renderFrame = () => {
frameCount++;
if (video.ended || video.paused || frameCount > maxFrames) {
resolve();
return;
}
// Draw black background
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw video with zoom/crop
drawVideoFrame(ctx, video, canvas.width, canvas.height, videoNum);
// Draw overlays
drawOverlays(ctx, canvas.width, canvas.height, titleText, top5Text, top5Color,
rankingObject, objectColor, endingText, videoNum);
requestAnimationFrame(renderFrame);
};
renderFrame();
});
video.pause();
}
showProgress(95, 'Finalizing...');
await new Promise(resolve => setTimeout(resolve, 1000));
mediaRecorder.stop();
showProgress(100, 'Complete!');
} catch (error) {
console.error('Error:', error);
showMessage('❌ Error: ' + error.message, 'error');
hideProgress();
} finally {
state.isGenerating = false;
}
}
function drawVideoFrame(ctx, video, canvasWidth, canvasHeight, videoNum) {
const resolution = state.resolutions[videoNum] || 'mobile';
try {
const videoAspect = video.videoWidth / video.videoHeight;
const canvasAspect = canvasWidth / canvasHeight;
let drawWidth, drawHeight, offsetX = 0, offsetY = 0;
if (resolution === 'pc') {
// PC resolution - zoom in and crop
const zoomFactor = 1.15; // 15% zoom
if (videoAspect > canvasAspect) {
drawHeight = canvasHeight * zoomFactor;
drawWidth = drawHeight * videoAspect;
offsetX = (canvasWidth - drawWidth) / 2;
offsetY = (canvasHeight - drawHeight) / 2;
} else {
drawWidth = canvasWidth * zoomFactor;
drawHeight = drawWidth / videoAspect;
offsetX = (canvasWidth - drawWidth) / 2;
offsetY = (canvasHeight - drawHeight) / 2;
}
} else {
// Mobile resolution - fit normally
if (videoAspect > canvasAspect) {
drawHeight = canvasHeight;
drawWidth = canvasHeight * videoAspect;
offsetX = (canvasWidth - drawWidth) / 2;
} else {
drawWidth = canvasWidth;
drawHeight = canvasWidth / videoAspect;
offsetY = (canvasHeight - drawHeight) / 2;
}
}
ctx.drawImage(video, offsetX, offsetY, drawWidth, drawHeight);
} catch (e) {
console.warn('Failed to draw video frame:', e);
}
}
function roundRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
async function showSubscribeButton(ctx, width, height, currentVideo) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
// Draw the current video frame (paused)
if (currentVideo) {
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, width, height);
// Draw video frame
drawVideoFrame(ctx, currentVideo, width, height, 2); // Video 2 since it's before video 2
}
// Add semi-transparent overlay
ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
ctx.fillRect(0, 0, width, height);
// Draw subscribe button with transparency
const imgAspect = img.width / img.height;
const targetWidth = width * 0.5;
const targetHeight = targetWidth / imgAspect;
const x = (width - targetWidth) / 2;
const y = (height - targetHeight) / 2;
// Add white border for better visibility
ctx.strokeStyle = 'rgba(255, 255, 255, 0.8)';
ctx.lineWidth = 4;
ctx.strokeRect(x - 2, y - 2, targetWidth + 4, targetHeight + 4);
ctx.drawImage(img, x, y, targetWidth, targetHeight);
resolve();
};
img.onerror = () => {
// Fallback if image doesn't load
if (currentVideo) {
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, width, height);
// Draw video frame
drawVideoFrame(ctx, currentVideo, width, height, 2); // Video 2 since it's before video 2
}
// Add semi-transparent overlay
ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
ctx.fillRect(0, 0, width, height);
// Draw fallback subscribe button
ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
ctx.strokeStyle = 'rgba(255, 255, 255, 0.9)';
ctx.lineWidth = 3;
const buttonWidth = 500;
const buttonHeight = 100;
const buttonX = (width - buttonWidth) / 2;
const buttonY = (height - buttonHeight) / 2;
// Draw rounded rectangle with transparency
roundRect(ctx, buttonX, buttonY, buttonWidth, buttonHeight, 20);
ctx.fill();
ctx.stroke();
// Draw subscribe text
ctx.fillStyle = '#ffffff';
ctx.font = 'bold 42px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('SUBSCRIBE', width / 2, height / 2);
resolve();
};
img.src = 'autosub.png';
});
}
function drawOverlays(ctx, width, height, titleText, top5Text, top5Color, rankingObject, objectColor, endingText, currentVideo) {
const titleFontSize = Math.floor(width * 0.055);
const numberFontSize = Math.floor(width * 0.09);
const nameFontSize = Math.floor(width * 0.045);
// Draw title
ctx.font = `bold ${titleFontSize}px Arial`;
ctx.textAlign = 'center';
ctx.strokeStyle = '#000';
ctx.lineWidth = Math.max(Math.floor(titleFontSize * 0.12), 4);
const titleY = height * 0.06;
// Build title parts
const fullTitle = `${titleText} ${top5Text} ${rankingObject} ${endingText}`;
const titleWidth = ctx.measureText(titleText).width;
const top5Width = ctx.measureText(top5Text).width;
const objectWidth = ctx.measureText(rankingObject).width;
const endingWidth = ctx.measureText(endingText).width;
const totalWidth = titleWidth + top5Width + objectWidth + endingWidth + 30; // spacing
let x = (width - totalWidth) / 2;
// Draw title
ctx.fillStyle = '#FFF';
ctx.strokeText(titleText, x + titleWidth / 2, titleY);
ctx.fillText(titleText, x + titleWidth / 2, titleY);
x += titleWidth + 10;
// Draw TOP 5 in custom color
ctx.fillStyle = top5Color;
ctx.strokeText(top5Text, x + top5Width / 2, titleY);
ctx.fillText(top5Text, x + top5Width / 2, titleY);
x += top5Width + 10;
// Draw ranking object in custom color
ctx.fillStyle = objectColor;
ctx.strokeText(rankingObject, x + objectWidth / 2, titleY);
ctx.fillText(rankingObject, x + objectWidth / 2, titleY);
x += objectWidth + 10;
// Draw ending
ctx.fillStyle = '#FFF';
ctx.strokeText(endingText, x + endingWidth / 2, titleY);
ctx.fillText(endingText, x + endingWidth / 2, titleY);
// Draw numbers with gold/silver/bronze
ctx.font = `bold ${numberFontSize}px Arial`;
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
let numberY = height * 0.18;
const numberX = width * 0.05;
const nameX = width * 0.18;
const numberSpacing = height * 0.12;
const numberColors = {
1: '#FFD700', // Gold
2: '#C0C0C0', // Silver
3: '#CD7F32', // Bronze
4: '#FFFFFF', // White
5: '#FFFFFF' // White
};
for (let i = 1; i <= 5; i++) {
const numberText = `${i}.`;
ctx.fillStyle = numberColors[i];
ctx.strokeText(numberText, numberX, numberY);
ctx.fillText(numberText, numberX, numberY);
// Draw clip name if processed
if (state.processedVideos.has(i) && state.names[i]) {
ctx.font = `bold ${nameFontSize}px Arial`;
ctx.fillStyle = '#FFF';
ctx.strokeText(state.names[i], nameX, numberY + 5);
ctx.fillText(state.names[i], nameX, numberY + 5);
ctx.font = `bold ${numberFontSize}px Arial`;
}
numberY += numberSpacing;
}
// Note: Big number overlay removed as requested
}
function downloadVideo() {
if (!state.recordedBlob) {
showMessage('❌ Generate video first!', 'error');
return;
}
try {
showMessage('Preparing download...', 'info');
const url = URL.createObjectURL(state.recordedBlob);
const a = document.createElement('a');
a.href = url;
a.download = getFilename();
a.style.display = 'none';
document.body.appendChild(a);
setTimeout(() => {
a.click();
setTimeout(() => {
if (document.body.contains(a)) {
document.body.removeChild(a);
}
URL.revokeObjectURL(url);
showMessage('✅ Downloaded!', 'success');
}, 100);
}, 100);
} catch (error) {
console.error('Download error:', error);
showMessage('❌ Download failed: ' + error.message, 'error');
}
}
function getFilename() {
const titleText = document.getElementById('titleText').value || 'Best';
const top5Text = document.getElementById('top5Text').value || 'TOP 5';
const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
return `${titleText} ${top5Text} - ${timestamp}.webm`;
}