-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathVideoGeneratorModal.tsx
More file actions
2437 lines (2186 loc) · 103 KB
/
VideoGeneratorModal.tsx
File metadata and controls
2437 lines (2186 loc) · 103 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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useRef, useEffect, useState, useCallback } from 'react';
import { Song } from '../types';
import { X, Play, Pause, Download, Wand2, Image as ImageIcon, Music, Video, Loader2, Palette, Layers, Zap, Type, Monitor, Aperture, Activity, Circle, Grid, Box, BarChart2, Waves, Disc, Upload, Plus, Trash2, Settings2, MousePointer2, Search, ExternalLink, Sun, Film, Minus } from 'lucide-react';
import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile, toBlobURL } from '@ffmpeg/util';
import { useResponsive } from '../context/ResponsiveContext';
interface VideoGeneratorModalProps {
isOpen: boolean;
onClose: () => void;
song: Song | null;
}
type PresetType =
| 'NCS Circle' | 'Linear Bars' | 'Dual Mirror' | 'Center Wave'
| 'Orbital' | 'Digital Rain' | 'Hexagon' | 'Shockwave'
| 'Oscilloscope' | 'Minimal';
interface VisualizerConfig {
preset: PresetType;
primaryColor: string;
secondaryColor: string;
bgDim: number;
particleCount: number;
}
interface EffectConfig {
shake: boolean;
glitch: boolean;
vhs: boolean;
cctv: boolean;
scanlines: boolean;
chromatic: boolean;
bloom: boolean;
filmGrain: boolean;
pixelate: boolean;
strobe: boolean;
vignette: boolean;
hueShift: boolean;
letterbox: boolean;
}
interface EffectIntensities {
shake: number;
glitch: number;
vhs: number;
cctv: number;
scanlines: number;
chromatic: number;
bloom: number;
filmGrain: number;
pixelate: number;
strobe: number;
vignette: number;
hueShift: number;
letterbox: number;
}
interface TextLayer {
id: string;
text: string;
x: number; // 0-100 percentage
y: number; // 0-100 percentage
size: number;
color: string;
font: string;
}
interface PexelsPhoto {
id: number;
src: { large: string; original: string };
photographer: string;
}
interface PexelsVideo {
id: number;
image: string;
video_files: { link: string; quality: string; width: number }[];
user: { name: string };
}
const PRESETS: { id: PresetType; label: string; icon: React.ReactNode }[] = [
{ id: 'NCS Circle', label: 'Classic NCS', icon: <Circle size={16} /> },
{ id: 'Linear Bars', label: 'Spectrum', icon: <BarChart2 size={16} /> },
{ id: 'Dual Mirror', label: 'Mirror', icon: <ColumnsIcon /> },
{ id: 'Center Wave', label: 'Shockwave', icon: <Waves size={16} /> },
{ id: 'Orbital', label: 'Orbital', icon: <Disc size={16} /> },
{ id: 'Hexagon', label: 'Hex Core', icon: <Box size={16} /> },
{ id: 'Oscilloscope', label: 'Analog', icon: <Activity size={16} /> },
{ id: 'Digital Rain', label: 'Matrix', icon: <Grid size={16} /> },
{ id: 'Shockwave', label: 'Pulse', icon: <Aperture size={16} /> },
{ id: 'Minimal', label: 'Clean', icon: <Type size={16} /> },
];
function ColumnsIcon() {
return (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M12 3v18"/>
<rect width="18" height="18" x="3" y="3" rx="2" />
</svg>
);
}
export const VideoGeneratorModal: React.FC<VideoGeneratorModalProps> = ({ isOpen, onClose, song }) => {
const { isMobile } = useResponsive();
const canvasRef = useRef<HTMLCanvasElement>(null);
const audioRef = useRef<HTMLAudioElement | null>(null);
const animationRef = useRef<number>(0);
const analyserRef = useRef<AnalyserNode | null>(null);
const audioContextRef = useRef<AudioContext | null>(null);
const bgImageRef = useRef<HTMLImageElement | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const videoFileInputRef = useRef<HTMLInputElement>(null);
// FFmpeg Refs
const ffmpegRef = useRef<FFmpeg | null>(null);
// Tabs: 'presets' | 'style' | 'text' | 'effects'
const [activeTab, setActiveTab] = useState('presets');
// State
const [isPlaying, setIsPlaying] = useState(false);
const [backgroundType, setBackgroundType] = useState<'random' | 'custom' | 'video'>('random');
const [backgroundSeed, setBackgroundSeed] = useState(Date.now());
const [customImage, setCustomImage] = useState<string | null>(null);
const [videoUrl, setVideoUrl] = useState<string>('');
const bgVideoRef = useRef<HTMLVideoElement | null>(null);
// Custom Album Art
const [customAlbumArt, setCustomAlbumArt] = useState<string | null>(null);
const albumArtInputRef = useRef<HTMLInputElement>(null);
const customAlbumArtImageRef = useRef<HTMLImageElement | null>(null);
// Pexels Browser State
const [showPexelsBrowser, setShowPexelsBrowser] = useState(false);
const [pexelsTarget, setPexelsTarget] = useState<'background' | 'albumArt'>('background');
const [pexelsTab, setPexelsTab] = useState<'photos' | 'videos'>('photos');
const [pexelsQuery, setPexelsQuery] = useState('abstract');
const [pexelsPhotos, setPexelsPhotos] = useState<PexelsPhoto[]>([]);
const [pexelsVideos, setPexelsVideos] = useState<PexelsVideo[]>([]);
const [pexelsLoading, setPexelsLoading] = useState(false);
const [pexelsApiKey, setPexelsApiKey] = useState<string>(() => localStorage.getItem('pexels_api_key') || '');
const [showPexelsApiKeyInput, setShowPexelsApiKeyInput] = useState(false);
const [pexelsError, setPexelsError] = useState<string | null>(null);
const [isExporting, setIsExporting] = useState(false);
const [exportProgress, setExportProgress] = useState(0);
const [exportStage, setExportStage] = useState<'idle' | 'capturing' | 'encoding'>('idle');
const [ffmpegLoaded, setFfmpegLoaded] = useState(false);
const [ffmpegLoading, setFfmpegLoading] = useState(false);
// Config State
const [config, setConfig] = useState<VisualizerConfig>({
preset: 'NCS Circle',
primaryColor: '#ec4899', // Pink-500
secondaryColor: '#3b82f6', // Blue-500
bgDim: 0.6,
particleCount: 50
});
const [effects, setEffects] = useState<EffectConfig>({
shake: true,
glitch: false,
vhs: false,
cctv: false,
scanlines: false,
chromatic: false,
bloom: false,
filmGrain: false,
pixelate: false,
strobe: false,
vignette: false,
hueShift: false,
letterbox: false
});
const [intensities, setIntensities] = useState<EffectIntensities>({
shake: 0.05,
glitch: 0.3,
vhs: 0.5,
cctv: 0.8,
scanlines: 0.4,
chromatic: 0.5,
bloom: 0.5,
filmGrain: 0.3,
pixelate: 0.3,
strobe: 0.5,
vignette: 0.5,
hueShift: 0.5,
letterbox: 0.5
});
// Text Layers State
const [textLayers, setTextLayers] = useState<TextLayer[]>([]);
// Init default text on load
useEffect(() => {
if (song) {
setTextLayers([
{ id: '1', text: song.title, x: 50, y: 85, size: 52, color: '#ffffff', font: 'Inter' },
{ id: '2', text: song.style.toUpperCase(), x: 50, y: 92, size: 24, color: '#3b82f6', font: 'Inter' }
]);
}
}, [song]);
// Use refs for render loop to access latest state without re-binding
const configRef = useRef(config);
const effectsRef = useRef(effects);
const intensitiesRef = useRef(intensities);
const textLayersRef = useRef(textLayers);
useEffect(() => { configRef.current = config; }, [config]);
useEffect(() => { effectsRef.current = effects; }, [effects]);
useEffect(() => { intensitiesRef.current = intensities; }, [intensities]);
useEffect(() => { textLayersRef.current = textLayers; }, [textLayers]);
// Load FFmpeg
const loadFFmpeg = useCallback(async () => {
if (ffmpegRef.current || ffmpegLoading) return;
setFfmpegLoading(true);
try {
const ffmpeg = new FFmpeg();
ffmpeg.on('progress', ({ progress }) => {
if (exportStage === 'encoding') {
setExportProgress(Math.round(progress * 100));
}
});
// Try local server first (bundled, works offline, no CSP issues),
// then fall back to CDN if somehow missing.
const localBase = `${window.location.protocol}//${window.location.hostname}:${window.location.port || (window.location.protocol === 'https:' ? '443' : '80')}/ffmpeg-core`;
// Load ffmpeg-core from local server (always served by Express with proper CORP headers)
// classWorkerURL overrides the Worker file path so ffmpeg uses our local copy
const loadOptions = {
coreURL: await toBlobURL(`${localBase}/ffmpeg-core.js`, 'text/javascript'),
wasmURL: await toBlobURL(`${localBase}/ffmpeg-core.wasm`, 'application/wasm'),
};
let loaded = false;
try {
await ffmpeg.load(loadOptions);
loaded = true;
console.log('FFmpeg loaded from local server');
} catch (e) {
console.warn('Local FFmpeg load failed, trying CDN...', e);
}
// CDN fallback (still uses local worker to avoid CSP issues)
if (!loaded) {
const cdnSources = [
'https://unpkg.com/@ffmpeg/core@0.12.6/dist/esm',
'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.6/dist/esm',
];
for (const baseURL of cdnSources) {
try {
await ffmpeg.load({
coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, 'text/javascript'),
wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, 'application/wasm'),
});
loaded = true;
console.log(`FFmpeg loaded from CDN: ${baseURL}`);
break;
} catch {
console.warn(`FFmpeg load failed from ${baseURL}`);
}
}
}
if (!loaded) throw new Error('Failed to load FFmpeg from all sources');
ffmpegRef.current = ffmpeg;
setFfmpegLoaded(true);
} catch (error) {
console.error('Failed to load FFmpeg:', error);
alert('Failed to load video encoder. Check your internet connection and try again.');
} finally {
setFfmpegLoading(false);
}
}, [ffmpegLoading, exportStage]);
// Load Background Image
useEffect(() => {
if (backgroundType === 'video') {
bgImageRef.current = null;
return;
}
const img = new Image();
img.crossOrigin = "Anonymous";
if (backgroundType === 'custom' && customImage) {
img.src = customImage;
} else {
img.src = `https://picsum.photos/seed/${backgroundSeed}/1920/1080?blur=4`;
}
img.onload = () => {
bgImageRef.current = img;
};
}, [backgroundSeed, backgroundType, customImage]);
// Load Background Video
useEffect(() => {
if (backgroundType !== 'video' || !videoUrl) {
if (bgVideoRef.current) {
bgVideoRef.current.pause();
bgVideoRef.current = null;
}
return;
}
const video = document.createElement('video');
video.crossOrigin = 'anonymous';
video.src = videoUrl;
video.loop = true;
video.muted = true;
video.playsInline = true;
video.autoplay = true;
video.onloadeddata = () => {
bgVideoRef.current = video;
video.play().catch(console.error);
};
video.onerror = () => {
console.error('Failed to load video:', videoUrl);
bgVideoRef.current = null;
};
return () => {
video.pause();
video.src = '';
};
}, [backgroundType, videoUrl]);
// Load Custom Album Art
useEffect(() => {
if (!customAlbumArt) {
customAlbumArtImageRef.current = null;
return;
}
// Clear ref immediately so we don't show stale image
customAlbumArtImageRef.current = null;
const img = new Image();
img.crossOrigin = 'anonymous';
// Use proxy for external URLs to avoid CORS issues
const isExternal = customAlbumArt.startsWith('http');
img.src = isExternal ? `/api/proxy/image?url=${encodeURIComponent(customAlbumArt)}` : customAlbumArt;
img.onload = () => {
customAlbumArtImageRef.current = img;
};
img.onerror = () => {
console.error('Failed to load custom album art:', customAlbumArt);
customAlbumArtImageRef.current = null;
};
}, [customAlbumArt]);
// Initialize Audio & Canvas
useEffect(() => {
if (!isOpen || !song) return;
// Reset basics
setIsPlaying(false);
setIsExporting(false);
setExportProgress(0);
setExportStage('idle');
// Audio Setup
const audio = new Audio();
audio.crossOrigin = "anonymous";
audio.src = song.audioUrl || '';
audioRef.current = audio;
const AudioContextClass = window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
const audioCtx = new AudioContextClass();
audioContextRef.current = audioCtx;
const analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
analyserRef.current = analyser;
const source = audioCtx.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(audioCtx.destination);
audio.onended = () => {
setIsPlaying(false);
};
// Start Loop
cancelAnimationFrame(animationRef.current);
renderLoop();
return () => {
audio.pause();
if (audioContextRef.current?.state !== 'closed') {
audioContextRef.current?.close();
}
cancelAnimationFrame(animationRef.current);
};
}, [isOpen, song]);
const togglePlay = async () => {
if (!audioRef.current || !audioContextRef.current) return;
if (audioContextRef.current.state === 'suspended') {
await audioContextRef.current.resume();
}
if (isPlaying) audioRef.current.pause();
else audioRef.current.play();
setIsPlaying(!isPlaying);
};
const startRecording = async () => {
if (!canvasRef.current || !song) return;
// Load FFmpeg if not loaded
if (!ffmpegRef.current) {
await loadFFmpeg();
if (!ffmpegRef.current) return;
}
setIsExporting(true);
setExportStage('capturing');
setExportProgress(0);
try {
await renderOffline();
} catch (error) {
console.error('Rendering failed:', error);
alert('Video rendering failed. Please try again.');
setIsExporting(false);
setExportStage('idle');
}
};
const analyzeAudioOffline = async (audioBuffer: AudioBuffer, fps: number): Promise<Uint8Array[]> => {
const duration = audioBuffer.duration;
const totalFrames = Math.ceil(duration * fps);
const samplesPerFrame = Math.floor(audioBuffer.sampleRate / fps);
const fftSize = 2048;
const frequencyBinCount = fftSize / 2;
// Get raw audio data from first channel
const channelData = audioBuffer.getChannelData(0);
const frequencyDataFrames: Uint8Array[] = [];
// Simple FFT approximation using amplitude analysis
// For each frame, compute frequency-like data from audio samples
for (let frame = 0; frame < totalFrames; frame++) {
const startSample = frame * samplesPerFrame;
const endSample = Math.min(startSample + fftSize, channelData.length);
const frameData = new Uint8Array(frequencyBinCount);
// Compute amplitude spectrum approximation
for (let bin = 0; bin < frequencyBinCount; bin++) {
let sum = 0;
const binSize = Math.max(1, Math.floor((endSample - startSample) / frequencyBinCount));
const binStart = startSample + bin * binSize;
const binEnd = Math.min(binStart + binSize, endSample);
for (let i = binStart; i < binEnd && i < channelData.length; i++) {
sum += Math.abs(channelData[i]);
}
const avg = binSize > 0 ? sum / binSize : 0;
// Scale to 0-255 range with some amplification
frameData[bin] = Math.min(255, Math.floor(avg * 512));
}
frequencyDataFrames.push(frameData);
}
return frequencyDataFrames;
};
const loadImageAsDataUrl = async (url: string): Promise<string | null> => {
try {
// Use proxy for external URLs to avoid CORS issues
const isExternal = url.startsWith('http') && !url.includes(window.location.host);
const fetchUrl = isExternal ? `/api/proxy/image?url=${encodeURIComponent(url)}` : url;
const response = await fetch(fetchUrl);
const blob = await response.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => resolve(null);
reader.readAsDataURL(blob);
});
} catch {
return null;
}
};
const renderOffline = async () => {
if (!song || !ffmpegRef.current) return;
// Create a separate clean canvas to avoid tainted canvas issues
const canvas = document.createElement('canvas');
canvas.width = 1920;
canvas.height = 1080;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const ffmpeg = ffmpegRef.current;
const fps = 30;
const width = canvas.width;
const height = canvas.height;
const centerX = width / 2;
const centerY = height / 2;
setExportProgress(1);
// Pre-load images via proxy to avoid CORS/tainted canvas issues
let bgImage: HTMLImageElement | null = null;
let bgVideo: HTMLVideoElement | null = null;
let albumImage: HTMLImageElement | null = null;
// Load background video or image
if (backgroundType === 'video' && videoUrl) {
bgVideo = document.createElement('video');
bgVideo.crossOrigin = 'anonymous';
bgVideo.src = videoUrl;
bgVideo.muted = true;
bgVideo.playsInline = true;
await new Promise<void>((resolve) => {
bgVideo!.onloadeddata = () => resolve();
bgVideo!.onerror = () => {
console.warn('Failed to load background video, falling back to image');
bgVideo = null;
resolve();
};
bgVideo!.load();
});
} else if (bgImageRef.current?.src) {
const bgDataUrl = await loadImageAsDataUrl(bgImageRef.current.src);
if (bgDataUrl) {
bgImage = new Image();
bgImage.src = bgDataUrl;
await new Promise<void>((resolve) => {
bgImage!.onload = () => resolve();
bgImage!.onerror = () => resolve();
});
}
}
// Load album art (use custom if set, otherwise song cover)
const albumArtSource = customAlbumArt || song.coverUrl;
if (albumArtSource) {
// Custom album art might already be a data URL
const albumDataUrl = albumArtSource.startsWith('data:')
? albumArtSource
: await loadImageAsDataUrl(albumArtSource);
if (albumDataUrl) {
albumImage = new Image();
albumImage.src = albumDataUrl;
await new Promise<void>((resolve) => {
albumImage!.onload = () => resolve();
albumImage!.onerror = () => resolve();
});
}
}
// Fetch and decode audio
setExportProgress(2);
const audioUrl = song.audioUrl || '';
const audioResponse = await fetch(audioUrl);
const audioArrayBuffer = await audioResponse.arrayBuffer();
// Keep a copy for FFmpeg
const audioDataCopy = audioArrayBuffer.slice(0);
setExportProgress(5);
// Decode audio for analysis
const audioCtx = new (window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)();
const audioBuffer = await audioCtx.decodeAudioData(audioArrayBuffer);
const duration = audioBuffer.duration;
const totalFrames = Math.ceil(duration * fps);
setExportProgress(10);
// Analyze audio to get frequency data for each frame
const frequencyDataFrames = await analyzeAudioOffline(audioBuffer, fps);
setExportProgress(15);
// Render all frames
const currentConfig = configRef.current;
const currentEffects = effectsRef.current;
const currentIntensities = intensitiesRef.current;
const currentTexts = textLayersRef.current;
for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
const time = frameIndex / fps;
const dataArray = frequencyDataFrames[frameIndex] || new Uint8Array(1024);
// Create time domain data (simple sine wave approximation based on bass)
const timeDomain = new Uint8Array(1024);
let bassSum = 0;
for (let i = 0; i < 20; i++) bassSum += dataArray[i];
const bassLevel = bassSum / 20 / 255;
for (let i = 0; i < timeDomain.length; i++) {
timeDomain[i] = 128 + Math.sin(i * 0.1 + time * 10) * 64 * bassLevel;
}
// Calculate bass and pulse
let bass = 0;
for (let i = 0; i < 20; i++) bass += dataArray[i];
bass = bass / 20;
const normBass = bass / 255;
const pulse = 1 + normBass * 0.15;
// Clear canvas
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, width, height);
// Draw background (video or image)
let bgSource: HTMLImageElement | HTMLVideoElement | null = bgImage;
if (bgVideo) {
// Seek video to current frame time (loop if video is shorter)
const videoTime = time % (bgVideo.duration || 1);
bgVideo.currentTime = videoTime;
// Wait for seek to complete
await new Promise<void>((resolve) => {
const onSeeked = () => {
bgVideo!.removeEventListener('seeked', onSeeked);
resolve();
};
bgVideo!.addEventListener('seeked', onSeeked);
// Fallback timeout in case seeked never fires
setTimeout(resolve, 50);
});
bgSource = bgVideo;
}
if (bgSource) {
ctx.save();
ctx.globalAlpha = 1 - currentConfig.bgDim;
if (currentEffects.shake && normBass > (0.6 - (currentIntensities.shake * 0.3))) {
const magnitude = currentIntensities.shake * 50;
const shakeX = (Math.random() - 0.5) * magnitude * normBass;
const shakeY = (Math.random() - 0.5) * magnitude * normBass;
ctx.translate(shakeX, shakeY);
}
const zoom = 1 + (Math.sin(time * 0.5) * 0.05);
ctx.translate(centerX, centerY);
ctx.scale(zoom, zoom);
ctx.drawImage(bgSource, -width/2, -height/2, width, height);
ctx.restore();
}
// Draw preset
ctx.save();
if (currentEffects.shake && normBass > 0.6) {
const magnitude = currentIntensities.shake * 30;
const shakeX = (Math.random() - 0.5) * magnitude * normBass;
const shakeY = (Math.random() - 0.5) * magnitude * normBass;
ctx.translate(shakeX, shakeY);
}
switch(currentConfig.preset) {
case 'NCS Circle':
drawNCSCircle(ctx, centerX, centerY, dataArray, pulse, time, currentConfig.primaryColor, currentConfig.secondaryColor);
break;
case 'Linear Bars':
drawLinearBars(ctx, width, height, dataArray, currentConfig.primaryColor, currentConfig.secondaryColor);
break;
case 'Dual Mirror':
drawDualMirror(ctx, width, height, dataArray, currentConfig.primaryColor);
break;
case 'Center Wave':
drawCenterWave(ctx, centerX, centerY, dataArray, time, currentConfig.primaryColor);
break;
case 'Orbital':
drawOrbital(ctx, centerX, centerY, dataArray, time, currentConfig.primaryColor, currentConfig.secondaryColor);
break;
case 'Hexagon':
drawHexagon(ctx, centerX, centerY, dataArray, pulse, time, currentConfig.primaryColor);
break;
case 'Oscilloscope':
drawOscilloscope(ctx, width, height, timeDomain, currentConfig.primaryColor);
break;
case 'Digital Rain':
drawDigitalRain(ctx, width, height, dataArray, time, currentConfig.primaryColor);
break;
case 'Shockwave':
drawShockwave(ctx, centerX, centerY, bass, time, currentConfig.primaryColor);
break;
}
drawParticles(ctx, width, height, time, bass, currentConfig.particleCount, currentConfig.primaryColor);
if (['NCS Circle', 'Hexagon', 'Orbital', 'Shockwave'].includes(currentConfig.preset) && albumImage) {
// Draw album art inline with pre-loaded image
ctx.save();
ctx.translate(centerX, centerY);
ctx.scale(pulse, pulse);
ctx.shadowBlur = 40;
ctx.shadowColor = currentConfig.primaryColor;
ctx.beginPath();
ctx.arc(0, 0, 150, 0, Math.PI * 2);
ctx.closePath();
ctx.lineWidth = 5;
ctx.strokeStyle = 'white';
ctx.stroke();
ctx.clip();
ctx.drawImage(albumImage, -150, -150, 300, 300);
ctx.restore();
}
// Pixelate effect (applied before text so text stays sharp)
if (currentEffects.pixelate) {
const pixelSize = Math.max(4, Math.floor(16 * currentIntensities.pixelate));
ctx.imageSmoothingEnabled = false;
const tempCanvas2 = document.createElement('canvas');
const smallW = Math.floor(width / pixelSize);
const smallH = Math.floor(height / pixelSize);
tempCanvas2.width = smallW;
tempCanvas2.height = smallH;
const tempCtx2 = tempCanvas2.getContext('2d')!;
tempCtx2.drawImage(canvas, 0, 0, smallW, smallH);
ctx.clearRect(0, 0, width, height);
ctx.drawImage(tempCanvas2, 0, 0, smallW, smallH, 0, 0, width, height);
ctx.imageSmoothingEnabled = true;
}
// Draw text layers
ctx.shadowBlur = 10;
ctx.shadowColor = 'black';
ctx.textAlign = 'center';
currentTexts.forEach(layer => {
ctx.fillStyle = layer.color;
const dynamicSize = layer.id === '1' && currentConfig.preset === 'Minimal' ? layer.size * pulse : layer.size;
ctx.font = `bold ${dynamicSize}px ${layer.font}, sans-serif`;
const xPos = (layer.x / 100) * width;
const yPos = (layer.y / 100) * height;
ctx.fillText(layer.text, xPos, yPos);
});
ctx.restore();
// Apply post-processing effects
if (currentEffects.scanlines || currentEffects.cctv) {
ctx.fillStyle = `rgba(0,0,0,${currentIntensities.scanlines * 0.8})`;
for (let i = 0; i < height; i += 4) {
ctx.fillRect(0, i, width, 2);
}
}
if (currentEffects.vhs || currentEffects.chromatic || (currentEffects.glitch && Math.random() > (1 - currentIntensities.glitch))) {
const intensity = currentEffects.vhs ? currentIntensities.vhs : currentIntensities.chromatic;
const offset = (10 * intensity) * normBass;
ctx.globalCompositeOperation = 'screen';
ctx.fillStyle = `rgba(255,0,0,${0.2 * intensity})`;
ctx.fillRect(-offset, 0, width, height);
ctx.fillStyle = `rgba(0,0,255,${0.2 * intensity})`;
ctx.fillRect(offset, 0, width, height);
ctx.globalCompositeOperation = 'source-over';
}
if (currentEffects.glitch && Math.random() > (1 - currentIntensities.glitch)) {
ctx.fillStyle = Math.random() > 0.5 ? currentConfig.primaryColor : '#fff';
ctx.fillRect(Math.random() * width, Math.random() * height, Math.random() * 200, 4);
}
if (currentEffects.cctv) {
const intensity = currentIntensities.cctv;
ctx.globalCompositeOperation = 'overlay';
ctx.fillStyle = `rgba(0, 50, 0, ${0.4 * intensity})`;
ctx.fillRect(0, 0, width, height);
const grad = ctx.createRadialGradient(centerX, centerY, height * 0.4, centerX, centerY, height * 0.9);
grad.addColorStop(0, 'transparent');
grad.addColorStop(1, 'black');
ctx.globalCompositeOperation = 'multiply';
ctx.fillStyle = grad;
ctx.fillRect(0, 0, width, height);
ctx.globalCompositeOperation = 'source-over';
}
// Bloom / Glow effect
if (currentEffects.bloom) {
const intensity = currentIntensities.bloom;
ctx.globalCompositeOperation = 'screen';
ctx.filter = `blur(${15 * intensity}px)`;
ctx.globalAlpha = 0.4 * intensity;
ctx.drawImage(canvas, 0, 0);
ctx.filter = 'none';
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
}
// Film Grain
if (currentEffects.filmGrain) {
const intensity = currentIntensities.filmGrain;
const imageData = ctx.getImageData(0, 0, width, height);
const data = imageData.data;
const grainAmount = intensity * 50;
for (let i = 0; i < data.length; i += 16) {
const noise = (Math.random() - 0.5) * grainAmount;
data[i] += noise;
data[i + 1] += noise;
data[i + 2] += noise;
}
ctx.putImageData(imageData, 0, 0);
}
// Strobe effect
if (currentEffects.strobe && normBass > (0.7 - currentIntensities.strobe * 0.3)) {
ctx.globalCompositeOperation = 'screen';
ctx.fillStyle = `rgba(255, 255, 255, ${currentIntensities.strobe * normBass * 0.8})`;
ctx.fillRect(0, 0, width, height);
ctx.globalCompositeOperation = 'source-over';
}
// Vignette effect
if (currentEffects.vignette) {
const intensity = currentIntensities.vignette;
const grad = ctx.createRadialGradient(centerX, centerY, height * 0.3, centerX, centerY, height * 0.8);
grad.addColorStop(0, 'transparent');
grad.addColorStop(1, `rgba(0, 0, 0, ${0.8 * intensity})`);
ctx.fillStyle = grad;
ctx.fillRect(0, 0, width, height);
}
// Hue Shift effect
if (currentEffects.hueShift) {
const hueRotation = currentIntensities.hueShift * 360 * (1 + normBass * 0.5);
ctx.filter = `hue-rotate(${hueRotation}deg)`;
ctx.drawImage(canvas, 0, 0);
ctx.filter = 'none';
}
// Letterbox effect
if (currentEffects.letterbox) {
const barHeight = height * 0.12 * currentIntensities.letterbox;
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, width, barHeight);
ctx.fillRect(0, height - barHeight, width, barHeight);
}
// Capture frame
const frameData = canvas.toDataURL('image/jpeg', 0.85);
const base64Data = frameData.split(',')[1];
const binaryData = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
await ffmpeg.writeFile(`frame${String(frameIndex).padStart(6, '0')}.jpg`, binaryData);
// Update progress (15-70% for frame rendering)
if (frameIndex % 10 === 0) {
setExportProgress(15 + Math.round((frameIndex / totalFrames) * 55));
}
}
setExportStage('encoding');
setExportProgress(70);
// Write audio file
console.log('[Video] Writing audio file...');
await ffmpeg.writeFile('audio.mp3', new Uint8Array(audioDataCopy));
setExportProgress(75);
// Encode video - use ultrafast preset for browser performance
console.log(`[Video] Encoding ${totalFrames} frames at ${fps}fps...`);
console.log('[Video] This may take a while in the browser. Please wait...');
const encodeResult = await ffmpeg.exec([
'-framerate', String(fps),
'-i', 'frame%06d.jpg',
'-i', 'audio.mp3',
'-c:v', 'libx264',
'-preset', 'ultrafast', // Fastest encoding
'-tune', 'fastdecode', // Optimize for fast decoding
'-crf', '28', // Slightly lower quality but much faster
'-pix_fmt', 'yuv420p',
'-c:a', 'aac',
'-b:a', '128k', // Lower bitrate audio
'-shortest',
'-movflags', '+faststart',
'output.mp4'
]);
console.log('[Video] FFmpeg encode result:', encodeResult);
setExportProgress(95);
// Read and download output
console.log('[Video] Reading output file...');
const outputData = await ffmpeg.readFile('output.mp4');
console.log('[Video] Output file size:', outputData.length, 'bytes');
if (outputData.length === 0) {
throw new Error('FFmpeg produced an empty output file');
}
const blob = new Blob([outputData], { type: 'video/mp4' });
const url = URL.createObjectURL(blob);
console.log('[Video] Created blob URL:', url, 'Size:', blob.size);
// More reliable download method
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = `${song.title || 'suno-video'}.mp4`;
document.body.appendChild(a);
a.click();
// Delay cleanup to ensure download starts
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 1000);
console.log('[Video] Download triggered!');
// Cleanup FFmpeg filesystem
setExportProgress(98);
for (let i = 0; i < totalFrames; i++) {
await ffmpeg.deleteFile(`frame${String(i).padStart(6, '0')}.jpg`).catch(() => {});
}
await ffmpeg.deleteFile('audio.mp3').catch(() => {});
await ffmpeg.deleteFile('output.mp4').catch(() => {});
await audioCtx.close();
setExportProgress(100);
// Small delay before hiding the progress to show completion
setTimeout(() => {
setIsExporting(false);
setExportStage('idle');
}, 500);
};
const stopRecording = () => {
// For offline rendering, we can't really stop mid-process
// This is kept for compatibility but offline render runs to completion
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onload = (ev) => {
const result = ev.target?.result as string;
setCustomImage(result);
setBackgroundType('custom');
};
reader.readAsDataURL(file);
}
};
const handleVideoFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
const url = URL.createObjectURL(file);
setVideoUrl(url);
setBackgroundType('video');
}
};
const searchPexels = async (query: string, type: 'photos' | 'videos') => {
setPexelsLoading(true);
setPexelsError(null);
try {
const endpoint = type === 'photos'
? `/api/pexels/photos?query=${encodeURIComponent(query)}`
: `/api/pexels/videos?query=${encodeURIComponent(query)}`;
const headers: HeadersInit = {};
if (pexelsApiKey) {
headers['X-Pexels-Api-Key'] = pexelsApiKey;
}
const response = await fetch(endpoint, { headers });
const data = await response.json();
if (!response.ok) {
if (response.status === 400 || response.status === 401) {
setPexelsError(data.error || 'API key required');
setShowPexelsApiKeyInput(true);
} else {
setPexelsError(data.error || 'Search failed');
}
return;
}
if (type === 'photos') {
setPexelsPhotos(data.photos || []);
} else {
setPexelsVideos(data.videos || []);