Download app.js from bebechien/im-the-software-engineer: direct link, hf CLI and curl.
- Browser
- Download file 38.9 kB
-
https://huggingface.co/spaces/bebechien/im-the-software-engineer/resolve/main/app.js
- Command line
-
hf download hf://spaces/bebechien/im-the-software-engineer/app.js
-
curl -L -o app.js https://huggingface.co/spaces/bebechien/im-the-software-engineer/resolve/main/app.js
38.9 kB
/* ==========================================================================
app.js — Player, Web Audio FFT / Beat-Clock Fallback, Lyric Sync & HUD
========================================================================== */
(function () {
'use strict';
// Built-in fallback dataset (used only if assets/lyrics-sync.js is not yet present)
const FALLBACK_DATA = {
title: "I'm The Software Engineer (:q!)",
artist: 'Lyria 3.5',
audioFile: 'assets/song.mp3',
duration: 160.0,
bpm: 128,
sections: [
{ id: 'verse1', label: 'Verse 1', start: 0.0, end: 26.0, mood: 'terminal-dark' },
{ id: 'prechorus', label: 'Pre-Chorus', start: 26.0, end: 44.0, mood: 'assembly-heat' },
{ id: 'chorus1', label: 'Chorus', start: 44.0, end: 68.0, mood: 'vibe-glitch' },
{ id: 'verse2', label: 'Verse 2', start: 68.0, end: 94.0, mood: 'manpage-bloat' },
{ id: 'bridge', label: 'Bridge', start: 94.0, end: 116.0, mood: 'synth-arp' },
{ id: 'solo', label: '140 WPM Solo', start: 116.0, end: 138.0, mood: 'mech-140wpm' },
{ id: 'outro', label: 'Outro', start: 138.0, end: 160.0, mood: 'root-micdrop' }
],
lines: [
{ start: 3.0, end: 6.8, section: 'verse1', text: 'Sitting in the dark with the terminal bright', highlight: ['terminal'] },
{ start: 6.8, end: 10.6, section: 'verse1', text: 'Compiling all the kernels in the middle of the night', highlight: ['kernels'] },
{ start: 10.6, end: 14.4, section: 'verse1', text: 'I can write the code by hand using the vi editor', highlight: ['vi'] },
{ start: 14.4, end: 18.2, section: 'verse1', text: "Who said emacs? Come on, don't be a competitor", highlight: ['emacs'] },
{ start: 18.2, end: 22.0, section: 'verse1', text: 'Memorized the flags, :wq to save the day', highlight: [':wq'] },
{ start: 22.0, end: 25.8, section: 'verse1', text: 'Doing everything the old-school, bare-metal way', highlight: ['bare-metal'] },
{ start: 26.2, end: 30.5, section: 'prechorus', text: 'I mastered every pointer, every memory leak', highlight: ['pointer', 'memory leak'] },
{ start: 30.5, end: 34.8, section: 'prechorus', text: 'Optimized the loops so the latency is weak', highlight: ['latency'] },
{ start: 34.8, end: 39.2, section: 'prechorus', text: 'From assembly down to C, yeah, I paid my dues', highlight: ['assembly', 'C'] },
{ start: 39.2, end: 43.8, section: 'prechorus', text: "Now I'm scrolling through my timeline reading tech industry news...", highlight: ['tech industry news'] },
{ start: 44.2, end: 48.0, section: 'chorus1', text: 'Wait—now you say vibe coding? Are you kidding me?', highlight: ['vibe coding'] },
{ start: 48.0, end: 52.0, section: 'chorus1', text: 'Just talking to a prompt and letting AI set you free?', highlight: ['prompt', 'AI'] },
{ start: 52.0, end: 56.0, section: 'chorus1', text: "I'm the software engineer, I built this from the ground", highlight: ['software engineer'] },
{ start: 56.0, end: 60.0, section: 'chorus1', text: 'While you\'re hitting "Tab" to accept whatever\'s found!', highlight: ['Tab'] },
{ start: 60.0, end: 64.0, section: 'chorus1', text: "Yeah, I'm the software engineer, surviving every trend", highlight: ['software engineer'] },
{ start: 64.0, end: 67.8, section: 'chorus1', text: 'From raw Vim macros to whatever comes around the bend!', highlight: ['Vim macros'] },
{ start: 68.2, end: 72.4, section: 'verse2', text: 'Used to read the man pages cover to cover', highlight: ['man pages'] },
{ start: 72.4, end: 76.8, section: 'verse2', text: 'Debugging race conditions like a jealous lover', highlight: ['race conditions'] },
{ start: 76.8, end: 81.0, section: 'verse2', text: 'Now the junior dev is shipping full-stack apps in ten', highlight: ['full-stack'] },
{ start: 81.0, end: 85.4, section: 'verse2', text: 'Saying "Bro, I haven\'t touched a semicolon since when?"', highlight: ['semicolon'] },
{ start: 85.4, end: 89.6, section: 'verse2', text: 'Zero dependencies, single-file clean', highlight: ['Zero dependencies'] },
{ start: 89.6, end: 93.8, section: 'verse2', text: 'While their node_modules folder eats the whole machine', highlight: ['node_modules'] },
{ start: 94.5, end: 99.5, section: 'bridge', text: 'Okay, fine, I tried the prompt... it actually ran', highlight: ['prompt'] },
{ start: 99.5, end: 104.8, section: 'bridge', text: 'Passed the unit tests on the very first scan', highlight: ['unit tests'] },
{ start: 104.8, end: 110.2, section: 'bridge', text: "Maybe there's a place for the machine and the mind", highlight: ['machine', 'mind'] },
{ start: 110.2, end: 115.6, section: 'bridge', text: 'As long as someone knows how it works behind...', highlight: ['works behind'] },
{ start: 116.5, end: 137.5, section: 'solo', text: '[ 140 WPM MECHANICAL KEYBOARD SOLO ]', highlight: ['140 WPM'] },
{ start: 138.2, end: 142.0, section: 'outro', text: "I'm the software engineer!", highlight: ['software engineer'] },
{ start: 142.0, end: 147.2, section: 'outro', text: 'Still got ESC mapped to Caps Lock, crystal clear!', highlight: ['ESC', 'Caps Lock'] },
{ start: 147.2, end: 152.5, section: 'outro', text: "You can keep your vibes, I'll keep my root access right here", highlight: ['root access'] },
{ start: 152.5, end: 156.5, section: 'outro', text: ':q!', highlight: [':q!'] },
{ start: 156.5, end: 159.8, section: 'outro', text: '(Mic drop)', highlight: ['Mic drop'] }
]
};
const KEYCAP_TOKENS = new Set(['tab', 'esc', 'caps lock', ':wq', ':q!', 'vi', 'emacs', '140 wpm']);
// Merge loaded window.MUSIC_VIDEO_DATA with fallback safely
const rawData = window.MUSIC_VIDEO_DATA && typeof window.MUSIC_VIDEO_DATA === 'object'
? window.MUSIC_VIDEO_DATA
: FALLBACK_DATA;
const DATA = {
title: rawData.title || FALLBACK_DATA.title,
artist: rawData.artist || FALLBACK_DATA.artist,
audioFile: rawData.audioFile || FALLBACK_DATA.audioFile,
duration: Number(rawData.duration) > 0 ? Number(rawData.duration) : FALLBACK_DATA.duration,
bpm: Number(rawData.bpm) > 0 ? Number(rawData.bpm) : FALLBACK_DATA.bpm,
sections: Array.isArray(rawData.sections) && rawData.sections.length > 0 ? rawData.sections : FALLBACK_DATA.sections,
lines: Array.isArray(rawData.lines) && rawData.lines.length > 0 ? rawData.lines : FALLBACK_DATA.lines
};
// Locate the :q! mic-drop line dynamically so visual scenes never hardcode its timestamp
const QUIT_LINE = DATA.lines.find((l) => l && typeof l.text === 'string' && l.text.toLowerCase().includes(':q!')) || null;
// DOM Elements
const canvas = document.getElementById('stage-canvas');
let audioEl = document.getElementById('audio-player');
const launchOverlay = document.getElementById('launch-overlay');
const btnLaunch = document.getElementById('btn-launch');
const launchNotice = document.getElementById('launch-notice');
const trackTitleHud = document.getElementById('track-title-hud');
const sectionLabelHud = document.getElementById('section-label-hud');
const audioModePill = document.getElementById('audio-mode-pill');
const bpmPill = document.getElementById('bpm-pill');
const moodPill = document.getElementById('mood-pill');
const sectionBanner = document.getElementById('section-banner');
const lyricPrev = document.getElementById('lyric-prev');
const lyricCurrent = document.getElementById('lyric-current');
const lyricCurrentText = lyricCurrent.querySelector('.lyric-text');
const lyricNext = document.getElementById('lyric-next');
const sectionPillsEl = document.getElementById('section-pills');
const timelineWrap = document.getElementById('timeline-wrap');
const timelineBuffer = document.getElementById('timeline-buffer');
const timelineProgress = document.getElementById('timeline-progress');
const timelineMarkers = document.getElementById('timeline-markers');
const timelineThumb = document.getElementById('timeline-thumb');
const timelineTooltip = document.getElementById('timeline-tooltip');
const btnPlay = document.getElementById('btn-play');
const iconPlay = document.getElementById('icon-play');
const iconPause = document.getElementById('icon-pause');
const timeCurrentEl = document.getElementById('time-current');
const timeDurationEl = document.getElementById('time-duration');
const miniEqBars = Array.from(document.querySelectorAll('#mini-eq span'));
const btnMute = document.getElementById('btn-mute');
const iconVolOn = document.getElementById('icon-vol-on');
const iconVolOff = document.getElementById('icon-vol-off');
const volumeSlider = document.getElementById('volume-slider');
const btnCrt = document.getElementById('btn-crt');
const btnFullscreen = document.getElementById('btn-fullscreen');
// Engine & State
const engine = new window.SceneEngine(canvas);
const state = {
launched: false,
playing: false,
demoClockMode: false, // Used only if audio file is unavailable
demoTime: 0,
lastTick: performance.now(),
duration: DATA.duration,
isScrubbing: false,
activeSectionId: null,
activeLineIdx: -2,
prevLineIdx: -2,
nextLineIdx: -2,
bannerTimer: null,
hudTimer: null,
audioReady: false,
// Web Audio API
audioCtx: null,
analyser: null,
freqData: null,
timeData: null,
fftActive: false,
fftEverNonZero: false,
fftZeroSeconds: 0,
webAudioDisabled: false,
corsFallbackAttempted: false,
corsFallbackInProgress: false,
pendingPlay: false,
// Reusable reactive audio snapshot passed to SceneEngine
audioSnapshot: {
bass: 0,
mid: 0,
treble: 0,
energy: 0,
peak: 0,
beatPhase: 0,
isBeat: false,
bins: new Float32Array(48),
waveform: new Float32Array(96)
}
};
/* ------------------------------------------------------------------------
Helpers
------------------------------------------------------------------------ */
function formatTime(sec) {
if (!Number.isFinite(sec) || sec < 0) sec = 0;
const m = Math.floor(sec / 60);
const s = Math.floor(sec % 60);
return `${m}:${s < 10 ? '0' : ''}${s}`;
}
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function renderHighlightedLyric(text, highlights) {
if (!text) return '';
let safe = escapeHtml(text);
if (!Array.isArray(highlights) || highlights.length === 0) return safe;
// Sort longest first to avoid partial nested replacements
const sorted = [...highlights]
.filter((h) => typeof h === 'string' && h.trim().length > 0)
.sort((a, b) => b.length - a.length);
if (sorted.length === 0) return safe;
const pattern = sorted.map((h) => escapeRegex(escapeHtml(h.trim()))).join('|');
const regex = new RegExp(`(${pattern})`, 'gi');
return safe.replace(regex, (match) => {
const normalized = match.replace(/"/g, '').replace(/^["']|["']$/g, '').toLowerCase();
if (KEYCAP_TOKENS.has(normalized)) {
return `<kbd class="kw-keycap">${match}</kbd>`;
}
return `<span class="kw-highlight">${match}</span>`;
});
}
function getCurrentTime() {
if (state.demoClockMode) return state.demoTime;
return Number.isFinite(audioEl.currentTime) ? audioEl.currentTime : 0;
}
function setCurrentTime(t) {
const clamped = Math.max(0, Math.min(state.duration, t));
if (state.demoClockMode) {
state.demoTime = clamped;
} else if (Number.isFinite(audioEl.duration) && audioEl.duration > 0) {
audioEl.currentTime = Math.min(clamped, audioEl.duration - 0.05);
} else {
audioEl.currentTime = clamped;
}
}
function getSectionAt(t) {
for (let i = 0; i < DATA.sections.length; i++) {
const s = DATA.sections[i];
if (t >= s.start && t < s.end) return s;
}
return DATA.sections[DATA.sections.length - 1];
}
/* ------------------------------------------------------------------------
Web Audio API Setup (strict CORS / opaque-origin safety + recovery)
------------------------------------------------------------------------ */
function isOpaqueOrLocalOrigin() {
const proto = window.location && window.location.protocol;
if (proto !== 'http:' && proto !== 'https:') return true;
const winOrigin = window.origin;
const locOrigin = window.location.origin;
return !winOrigin || winOrigin === 'null' || !locOrigin || locOrigin === 'null';
}
function canUseWebAudioFFT() {
if (state.webAudioDisabled || state.demoClockMode) return false;
if (isOpaqueOrLocalOrigin()) return false;
// Verify resolved audio URL is strictly same-origin so Chrome never taints
// MediaElementAudioSource (which would output zeroes and mute <audio>).
const rawSrc = audioEl.currentSrc || audioEl.getAttribute('src') || DATA.audioFile;
if (!rawSrc) return false;
try {
const resolved = new URL(rawSrc, window.location.href);
if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') return false;
if (resolved.origin !== window.location.origin) return false;
} catch {
return false;
}
return true;
}
function recoverFromTaintedWebAudio() {
if (state.webAudioDisabled) return;
state.webAudioDisabled = true;
state.fftActive = false;
const oldEl = audioEl;
const resumeTime = Number.isFinite(oldEl.currentTime) ? oldEl.currentTime : 0;
const vol = oldEl.volume;
const muted = oldEl.muted;
const wasPlaying = state.playing && !oldEl.paused;
if (state.audioCtx) {
state.audioCtx.close().catch(() => {});
state.audioCtx = null;
state.analyser = null;
state.freqData = null;
state.timeData = null;
}
// Replace the <audio> element with a fresh one unbound from MediaElementAudioSource
// so native playback is never silently muted by a CORS-tainted Web Audio graph.
oldEl.pause();
oldEl.removeAttribute('src');
oldEl.load();
const freshEl = document.createElement('audio');
freshEl.id = 'audio-player';
freshEl.preload = 'auto';
freshEl.volume = vol;
freshEl.muted = muted;
oldEl.replaceWith(freshEl);
audioEl = freshEl;
bindAudioElementEvents(freshEl);
freshEl.src = DATA.audioFile;
const resumePlayback = () => {
if (resumeTime > 0 && Number.isFinite(freshEl.duration) && resumeTime < freshEl.duration) {
freshEl.currentTime = resumeTime;
}
if (wasPlaying) {
freshEl.play().catch(() => {});
}
};
if (freshEl.readyState >= 1) {
resumePlayback();
} else {
freshEl.addEventListener('loadedmetadata', resumePlayback, { once: true });
}
audioModePill.textContent = 'BEAT_SYNC (SAFE)';
}
function fallbackFromCorsError() {
if (state.corsFallbackAttempted) return false;
state.corsFallbackAttempted = true;
state.corsFallbackInProgress = true;
state.webAudioDisabled = true;
state.fftActive = false;
audioModePill.textContent = 'BEAT_SYNC (SAFE)';
const shouldResume = state.playing || state.pendingPlay;
const oldEl = audioEl;
const vol = oldEl.volume;
const muted = oldEl.muted;
if (state.audioCtx) {
// MediaElementAudioSource was already bound to oldEl; replace <audio>
// with a clean native element so Web Audio cannot silently mute it.
state.audioCtx.close().catch(() => {});
state.audioCtx = null;
state.analyser = null;
state.freqData = null;
state.timeData = null;
oldEl.pause();
oldEl.removeAttribute('src');
oldEl.load();
const freshEl = document.createElement('audio');
freshEl.id = 'audio-player';
freshEl.preload = 'auto';
freshEl.volume = vol;
freshEl.muted = muted;
oldEl.replaceWith(freshEl);
audioEl = freshEl;
bindAudioElementEvents(freshEl);
} else {
audioEl.removeAttribute('crossorigin');
}
const targetEl = audioEl;
targetEl.src = DATA.audioFile;
targetEl.load();
const finishFallback = () => {
if (targetEl !== audioEl) return;
state.corsFallbackInProgress = false;
if (shouldResume) {
const p = targetEl.play();
if (p && typeof p.then === 'function') {
p.then(() => {
state.playing = true;
state.pendingPlay = false;
syncPlayButtons();
showHudTemporarily();
}).catch(() => {
state.pendingPlay = false;
enterDemoMode('Audio file unavailable — running in synchronized visual preview mode.');
state.playing = true;
syncPlayButtons();
showHudTemporarily();
});
} else {
state.playing = true;
state.pendingPlay = false;
syncPlayButtons();
showHudTemporarily();
}
}
};
if (shouldResume) {
if (targetEl.readyState >= 1) {
finishFallback();
} else {
targetEl.addEventListener('loadedmetadata', finishFallback, { once: true });
}
} else {
state.corsFallbackInProgress = false;
}
return true;
}
function initWebAudio() {
if (state.audioCtx || state.demoClockMode || state.webAudioDisabled) return;
if (!canUseWebAudioFFT()) {
// On file://, sandboxed/opaque origin (window.origin === 'null'), or cross-origin media,
// never call createMediaElementSource so <audio> plays natively at full volume.
state.fftActive = false;
audioModePill.textContent = isOpaqueOrLocalOrigin() ? 'BEAT_SYNC (LOCAL)' : 'BEAT_SYNC (SAFE)';
return;
}
const AudioCtx = window.AudioContext || window.webkitAudioContext;
if (!AudioCtx) {
state.fftActive = false;
audioModePill.textContent = 'BEAT_SYNC';
return;
}
try {
const ctx = new AudioCtx();
const source = ctx.createMediaElementSource(audioEl);
const analyser = ctx.createAnalyser();
analyser.fftSize = 256;
analyser.smoothingTimeConstant = 0.8;
source.connect(analyser);
analyser.connect(ctx.destination);
state.audioCtx = ctx;
state.analyser = analyser;
state.freqData = new Uint8Array(analyser.frequencyBinCount);
state.timeData = new Uint8Array(analyser.fftSize);
state.fftActive = true;
state.fftEverNonZero = false;
state.fftZeroSeconds = 0;
audioModePill.textContent = 'AUDIO_FFT';
} catch (err) {
state.fftActive = false;
state.webAudioDisabled = true;
audioModePill.textContent = 'BEAT_SYNC';
}
}
function sampleAudio(t, dt, mood) {
const snap = state.audioSnapshot;
const beatSec = 60 / DATA.bpm;
const beatPos = (t / beatSec) % 1;
const prevPhase = snap.beatPhase;
snap.beatPhase = beatPos;
snap.isBeat = state.playing && beatPos < prevPhase;
// 1. Try real Web Audio FFT if active & playing
if (state.fftActive && state.analyser && state.playing) {
state.analyser.getByteFrequencyData(state.freqData);
state.analyser.getByteTimeDomainData(state.timeData);
let sum = 0;
for (let i = 0; i < state.freqData.length; i++) sum += state.freqData[i];
if (sum > 8) {
state.fftEverNonZero = true;
state.fftZeroSeconds = 0;
const n = state.freqData.length;
let bass = 0, mid = 0, treble = 0;
const bassEnd = Math.max(4, Math.floor(n * 0.12));
const midEnd = Math.floor(n * 0.48);
for (let i = 0; i < bassEnd; i++) bass += state.freqData[i];
for (let i = bassEnd; i < midEnd; i++) mid += state.freqData[i];
for (let i = midEnd; i < n; i++) treble += state.freqData[i];
snap.bass = bass / (bassEnd * 255);
snap.mid = mid / ((midEnd - bassEnd) * 255);
snap.treble = treble / ((n - midEnd) * 255);
snap.energy = snap.bass * 0.45 + snap.mid * 0.35 + snap.treble * 0.2;
snap.peak = Math.max(snap.bass, snap.mid, snap.treble);
for (let i = 0; i < snap.bins.length; i++) {
const idx = Math.floor((i / snap.bins.length) * (n * 0.85));
snap.bins[i] = state.freqData[idx] / 255;
}
for (let i = 0; i < snap.waveform.length; i++) {
const idx = Math.floor((i / snap.waveform.length) * state.timeData.length);
snap.waveform[i] = (state.timeData[idx] - 128) / 128;
}
return snap;
}
// Runtime safety guard: if FFT outputs only zeroes during active non-muted playback
// (e.g. unexpected cross-origin redirect tainting MediaElementAudioSource), detach
// Web Audio and swap in a fresh native <audio> element so audio is never silently muted.
if (!audioEl.paused && !audioEl.muted && audioEl.volume > 0.05 && t > 1.5 && t < state.duration - 6.0) {
state.fftZeroSeconds += dt;
if (!state.fftEverNonZero && state.fftZeroSeconds > 2.5) {
recoverFromTaintedWebAudio();
} else if (state.fftZeroSeconds > 1.5) {
audioModePill.textContent = 'BEAT_SYNC';
}
}
}
// 2. Musical Beat-Clock Reactive Synthesizer (works offline, on file://, and when idle)
const intensityByMood = {
'terminal-dark': 0.58,
'assembly-heat': 0.78,
'vibe-glitch': 0.96,
'manpage-bloat': 0.74,
'synth-arp': 0.52,
'mech-140wpm': 1.0,
'root-micdrop': 0.84
};
const mult = state.playing ? (intensityByMood[mood] || 0.7) : 0.16;
const kick = Math.pow(1 - beatPos, 3.2);
const snare = Math.pow(1 - ((beatPos + 0.5) % 1), 4.0);
const arp = 0.5 + 0.5 * Math.sin(t * (DATA.bpm / 60) * Math.PI * 4);
const flutter = 0.5 + 0.5 * Math.sin(t * 23.5) * Math.cos(t * 13.1);
snap.bass = Math.min(1, (0.18 + kick * 0.78) * mult);
snap.mid = Math.min(1, (0.2 + snare * 0.55 + arp * 0.25) * mult);
snap.treble = Math.min(1, (0.15 + flutter * 0.55 + arp * 0.28) * mult);
snap.energy = snap.bass * 0.45 + snap.mid * 0.35 + snap.treble * 0.2;
snap.peak = Math.max(snap.bass, snap.mid, snap.treble);
for (let i = 0; i < snap.bins.length; i++) {
const f = i / snap.bins.length;
const wave =
(1 - f) * snap.bass * (0.7 + 0.3 * Math.sin(t * 8 + i * 0.4)) +
Math.sin(f * Math.PI) * snap.mid * (0.65 + 0.35 * Math.cos(t * 11 - i * 0.5)) +
f * snap.treble * (0.6 + 0.4 * Math.sin(t * 19 + i * 0.9));
snap.bins[i] = Math.max(0.03, Math.min(1, wave));
}
for (let i = 0; i < snap.waveform.length; i++) {
const p = i / snap.waveform.length;
const env = Math.sin(p * Math.PI);
snap.waveform[i] = env * mult * (
Math.sin(p * Math.PI * 6 + t * 14) * (0.35 + snap.bass * 0.55) +
Math.sin(p * Math.PI * 18 - t * 24) * (0.18 + snap.treble * 0.35)
);
}
return snap;
}
/* ------------------------------------------------------------------------
HUD & Section Markers Setup
------------------------------------------------------------------------ */
function buildSectionUI() {
trackTitleHud.textContent = DATA.title;
bpmPill.textContent = `${Math.round(DATA.bpm)} BPM`;
timeDurationEl.textContent = formatTime(state.duration);
sectionPillsEl.innerHTML = '';
timelineMarkers.innerHTML = '';
DATA.sections.forEach((sec) => {
// Quick-jump pill button
const pill = document.createElement('button');
pill.type = 'button';
pill.className = 'section-pill';
pill.dataset.sectionId = sec.id;
pill.textContent = sec.label;
pill.title = `Jump to ${sec.label} (${formatTime(sec.start)})`;
pill.addEventListener('click', () => {
setCurrentTime(sec.start + 0.05);
if (!state.playing && state.launched) togglePlay(true);
showHudTemporarily();
});
sectionPillsEl.appendChild(pill);
// Vertical marker on timeline track
if (sec.start > 0.2 && state.duration > 0) {
const marker = document.createElement('div');
marker.className = 'timeline-marker';
marker.style.left = `${(sec.start / state.duration) * 100}%`;
timelineMarkers.appendChild(marker);
}
});
}
function triggerSectionBanner(label) {
sectionBanner.textContent = label;
sectionBanner.classList.add('visible');
if (state.bannerTimer) clearTimeout(state.bannerTimer);
state.bannerTimer = setTimeout(() => {
sectionBanner.classList.remove('visible');
}, 2600);
}
function showHudTemporarily() {
document.body.classList.remove('hud-hidden');
if (state.hudTimer) clearTimeout(state.hudTimer);
if (state.playing && state.launched) {
state.hudTimer = setTimeout(() => {
if (state.playing && !state.isScrubbing) {
document.body.classList.add('hud-hidden');
}
}, 2800);
}
}
/* ------------------------------------------------------------------------
Playback Control
------------------------------------------------------------------------ */
function syncPlayButtons() {
iconPlay.hidden = state.playing;
iconPause.hidden = !state.playing;
document.body.classList.toggle('is-playing', state.playing);
}
function togglePlay(forcePlay) {
const shouldPlay = typeof forcePlay === 'boolean' ? forcePlay : !state.playing;
if (shouldPlay) {
if (state.demoClockMode) {
if (state.demoTime >= state.duration - 0.1) state.demoTime = 0;
state.playing = true;
syncPlayButtons();
showHudTemporarily();
return;
}
state.pendingPlay = true;
initWebAudio();
if (state.audioCtx && state.audioCtx.state === 'suspended') {
state.audioCtx.resume().catch(() => {});
}
const playPromise = audioEl.play();
if (playPromise && typeof playPromise.then === 'function') {
playPromise
.then(() => {
state.pendingPlay = false;
state.playing = true;
syncPlayButtons();
showHudTemporarily();
})
.catch(() => {
// If a CORS-mode load failed (e.g. redirect to a CDN without ACAO),
// let the CORS fallback strip crossorigin and replay natively instead of demo mode.
if (state.corsFallbackInProgress) return;
if (audioEl.crossOrigin === 'anonymous' && !state.corsFallbackAttempted) {
if (fallbackFromCorsError()) return;
}
state.pendingPlay = false;
// Audio file missing or blocked: seamlessly enter Demo Clock mode so visuals still run
enterDemoMode('Audio file unavailable — running in synchronized visual preview mode.');
state.playing = true;
syncPlayButtons();
showHudTemporarily();
});
} else {
state.pendingPlay = false;
state.playing = true;
syncPlayButtons();
showHudTemporarily();
}
} else {
state.pendingPlay = false;
if (!state.demoClockMode) {
audioEl.pause();
}
state.playing = false;
syncPlayButtons();
document.body.classList.remove('hud-hidden');
}
}
function enterDemoMode(msg) {
state.demoClockMode = true;
audioModePill.textContent = 'PREVIEW_CLOCK';
if (msg && launchNotice) {
launchNotice.textContent = msg;
launchNotice.hidden = false;
}
}
function launchExperience() {
state.launched = true;
launchOverlay.classList.add('hidden');
togglePlay(true);
}
/* ------------------------------------------------------------------------
Lyric Synchronization
------------------------------------------------------------------------ */
function updateLyrics(t) {
const lines = DATA.lines;
let activeIdx = -1;
let nextIdx = -1;
for (let i = 0; i < lines.length; i++) {
if (t >= lines[i].start && t <= lines[i].end) {
activeIdx = i;
nextIdx = i + 1 < lines.length ? i + 1 : -1;
break;
}
if (t < lines[i].start) {
nextIdx = i;
break;
}
}
const prevIdx = activeIdx > 0
? activeIdx - 1
: activeIdx === -1
? (nextIdx > 0 ? nextIdx - 1 : (nextIdx === -1 && lines.length > 0 ? lines.length - 1 : -1))
: -1;
if (prevIdx !== state.prevLineIdx) {
state.prevLineIdx = prevIdx;
lyricPrev.textContent = prevIdx >= 0 ? lines[prevIdx].text : '';
}
if (nextIdx !== state.nextLineIdx) {
state.nextLineIdx = nextIdx;
lyricNext.textContent = nextIdx >= 0 ? lines[nextIdx].text : '';
}
if (activeIdx !== state.activeLineIdx) {
state.activeLineIdx = activeIdx;
if (activeIdx >= 0) {
const line = lines[activeIdx];
lyricCurrentText.innerHTML = renderHighlightedLyric(line.text, line.highlight);
lyricCurrent.classList.remove('line-enter');
// Force reflow to retrigger entrance animation
void lyricCurrent.offsetWidth;
lyricCurrent.classList.add('line-enter');
} else {
lyricCurrentText.innerHTML = '';
}
}
// Update smooth line progress bar fill
if (activeIdx >= 0) {
const line = lines[activeIdx];
const span = Math.max(0.1, line.end - line.start);
const pct = Math.max(0, Math.min(100, ((t - line.start) / span) * 100));
document.documentElement.style.setProperty('--line-progress', `${pct.toFixed(1)}%`);
return line.text;
} else {
document.documentElement.style.setProperty('--line-progress', '0%');
return '';
}
}
/* ------------------------------------------------------------------------
Main 60fps Animation Loop
------------------------------------------------------------------------ */
function tick(now) {
const dt = Math.min((now - state.lastTick) / 1000, 0.05);
state.lastTick = now;
if (state.demoClockMode && state.playing) {
state.demoTime += dt;
if (state.demoTime >= state.duration) {
state.demoTime = state.duration;
state.playing = false;
syncPlayButtons();
document.body.classList.remove('hud-hidden');
}
}
const t = getCurrentTime();
const sec = getSectionAt(t);
const mood = sec ? sec.mood : 'terminal-dark';
const secSpan = sec ? Math.max(0.1, sec.end - sec.start) : 1;
const secProgress = sec ? Math.max(0, Math.min(1, (t - sec.start) / secSpan)) : 0;
// Update mood & active section pill when section changes
if (sec && sec.id !== state.activeSectionId) {
state.activeSectionId = sec.id;
document.body.setAttribute('data-mood', mood);
sectionLabelHud.textContent = sec.label;
moodPill.textContent = mood;
if (state.launched) {
triggerSectionBanner(sec.label);
}
const pills = sectionPillsEl.querySelectorAll('.section-pill');
pills.forEach((p) => {
p.classList.toggle('active', p.dataset.sectionId === sec.id);
});
}
// Sample audio FFT or Beat-Clock fallback
const audioSnap = sampleAudio(t, dt, mood);
// Subtle kinetic beat scale on active lyric
const beatScale = state.playing ? (1 + audioSnap.bass * 0.032) : 1;
document.documentElement.style.setProperty('--beat-scale', beatScale.toFixed(4));
// Update lyrics
const currentLineText = updateLyrics(t);
// Render 60fps Canvas Visual Engine
engine.render({
time: t,
duration: state.duration,
playing: state.playing,
mood,
sectionProgress: secProgress,
audio: audioSnap,
currentLineText,
quitLine: QUIT_LINE
});
// Update HUD timeline & mini EQ bars
if (!state.isScrubbing && state.duration > 0) {
const pct = Math.max(0, Math.min(100, (t / state.duration) * 100));
timelineProgress.style.width = `${pct}%`;
timelineThumb.style.left = `${pct}%`;
timelineWrap.setAttribute('aria-valuenow', Math.round(pct));
}
timeCurrentEl.textContent = formatTime(t);
for (let i = 0; i < miniEqBars.length; i++) {
const val = audioSnap.bins[i * 6] || 0;
const px = Math.max(3, Math.round(3 + val * 15));
miniEqBars[i].style.height = `${px}px`;
}
requestAnimationFrame(tick);
}
/* ------------------------------------------------------------------------
Event Listeners
------------------------------------------------------------------------ */
function bindAudioElementEvents(el) {
el.addEventListener('loadedmetadata', () => {
if (el !== audioEl) return;
state.audioReady = true;
if (Number.isFinite(el.duration) && el.duration > 0) {
state.duration = el.duration;
buildSectionUI();
}
});
el.addEventListener('progress', () => {
if (el !== audioEl) return;
if (el.buffered.length > 0 && state.duration > 0) {
const end = el.buffered.end(el.buffered.length - 1);
timelineBuffer.style.width = `${Math.min(100, (end / state.duration) * 100)}%`;
}
});
el.addEventListener('ended', () => {
if (el !== audioEl) return;
state.playing = false;
syncPlayButtons();
document.body.classList.remove('hud-hidden');
});
el.addEventListener('error', () => {
if (el !== audioEl) return;
if (el.crossOrigin === 'anonymous' && !state.corsFallbackAttempted) {
fallbackFromCorsError();
return;
}
state.corsFallbackInProgress = false;
state.pendingPlay = false;
enterDemoMode('Audio track not found yet — click Play for visual preview mode.');
});
}
function bindEvents() {
window.addEventListener('resize', () => engine.resize());
// Request audio with CORS ('anonymous') BEFORE setting src whenever Web Audio FFT
// is eligible (http/https non-opaque origin). This allows cross-origin 302 redirects
// (e.g. Hugging Face Static Spaces LFS/XetHub CDN with ACAO: *) to stay untainted
// while same-origin servers without ACAO continue to work cleanly.
bindAudioElementEvents(audioEl);
if (canUseWebAudioFFT()) {
audioEl.crossOrigin = 'anonymous';
} else {
audioEl.removeAttribute('crossorigin');
audioModePill.textContent = isOpaqueOrLocalOrigin() ? 'BEAT_SYNC (LOCAL)' : 'BEAT_SYNC (SAFE)';
}
audioEl.src = DATA.audioFile;
audioEl.load();
audioEl.volume = parseFloat(volumeSlider.value);
// Launch button
btnLaunch.addEventListener('click', launchExperience);
// Play/Pause button
btnPlay.addEventListener('click', () => togglePlay());
// Timeline scrubbing & hover preview
function seekFromClientX(clientX, commit) {
const rect = timelineWrap.getBoundingClientRect();
const frac = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
const targetTime = frac * state.duration;
const sec = getSectionAt(targetTime);
timelineTooltip.style.left = `${frac * 100}%`;
timelineTooltip.textContent = `${formatTime(targetTime)}${sec ? ' • ' + sec.label : ''}`;
if (commit) {
timelineProgress.style.width = `${frac * 100}%`;
timelineThumb.style.left = `${frac * 100}%`;
setCurrentTime(targetTime);
}
}
timelineWrap.addEventListener('pointerdown', (e) => {
state.isScrubbing = true;
timelineWrap.classList.add('scrubbing');
timelineWrap.setPointerCapture(e.pointerId);
seekFromClientX(e.clientX, true);
});
timelineWrap.addEventListener('pointermove', (e) => {
seekFromClientX(e.clientX, state.isScrubbing);
});
timelineWrap.addEventListener('pointerup', (e) => {
if (state.isScrubbing) {
seekFromClientX(e.clientX, true);
state.isScrubbing = false;
timelineWrap.classList.remove('scrubbing');
}
});
// Volume & Mute
function updateVolumeUI() {
const muted = audioEl.muted || audioEl.volume === 0;
iconVolOn.hidden = muted;
iconVolOff.hidden = !muted;
}
volumeSlider.addEventListener('input', () => {
const v = parseFloat(volumeSlider.value);
audioEl.volume = v;
audioEl.muted = v === 0;
updateVolumeUI();
});
btnMute.addEventListener('click', () => {
audioEl.muted = !audioEl.muted;
if (!audioEl.muted && audioEl.volume === 0) {
audioEl.volume = 0.8;
volumeSlider.value = '0.8';
}
updateVolumeUI();
});
// CRT FX Toggle
function toggleCrt() {
const isOn = document.body.classList.toggle('crt-on');
document.body.classList.toggle('crt-off', !isOn);
btnCrt.classList.toggle('active', isOn);
btnCrt.setAttribute('aria-pressed', String(isOn));
}
btnCrt.addEventListener('click', toggleCrt);
// Fullscreen Toggle
function toggleFullscreen() {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen().catch(() => {});
} else {
document.exitFullscreen().catch(() => {});
}
}
btnFullscreen.addEventListener('click', toggleFullscreen);
// Auto-hide HUD on mouse/touch movement
['mousemove', 'pointerdown', 'touchstart'].forEach((evt) => {
window.addEventListener(evt, showHudTemporarily, { passive: true });
});
// Keyboard Shortcuts
window.addEventListener('keydown', (e) => {
if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return;
if (e.code === 'Space') {
e.preventDefault();
if (!state.launched) launchExperience();
else togglePlay();
} else if (e.code === 'ArrowLeft') {
e.preventDefault();
setCurrentTime(getCurrentTime() - 5);
showHudTemporarily();
} else if (e.code === 'ArrowRight') {
e.preventDefault();
setCurrentTime(getCurrentTime() + 5);
showHudTemporarily();
} else if (e.key === 'f' || e.key === 'F') {
e.preventDefault();
toggleFullscreen();
} else if (e.key === 'm' || e.key === 'M') {
e.preventDefault();
btnMute.click();
} else if (e.key === 'c' || e.key === 'C') {
e.preventDefault();
toggleCrt();
}
});
}
/* ------------------------------------------------------------------------
Bootstrap
------------------------------------------------------------------------ */
buildSectionUI();
bindEvents();
requestAnimationFrame(tick);
})();
/* ==========================================================================
app.js — Player, Web Audio FFT / Beat-Clock Fallback, Lyric Sync & HUD
========================================================================== */
(function () {
'use strict';
// Built-in fallback dataset (used only if assets/lyrics-sync.js is not yet present)
const FALLBACK_DATA = {
title: "I'm The Software Engineer (:q!)",
artist: 'Lyria 3.5',
audioFile: 'assets/song.mp3',
duration: 160.0,
bpm: 128,
sections: [
{ id: 'verse1', label: 'Verse 1', start: 0.0, end: 26.0, mood: 'terminal-dark' },
{ id: 'prechorus', label: 'Pre-Chorus', start: 26.0, end: 44.0, mood: 'assembly-heat' },
{ id: 'chorus1', label: 'Chorus', start: 44.0, end: 68.0, mood: 'vibe-glitch' },
{ id: 'verse2', label: 'Verse 2', start: 68.0, end: 94.0, mood: 'manpage-bloat' },
{ id: 'bridge', label: 'Bridge', start: 94.0, end: 116.0, mood: 'synth-arp' },
{ id: 'solo', label: '140 WPM Solo', start: 116.0, end: 138.0, mood: 'mech-140wpm' },
{ id: 'outro', label: 'Outro', start: 138.0, end: 160.0, mood: 'root-micdrop' }
],
lines: [
{ start: 3.0, end: 6.8, section: 'verse1', text: 'Sitting in the dark with the terminal bright', highlight: ['terminal'] },
{ start: 6.8, end: 10.6, section: 'verse1', text: 'Compiling all the kernels in the middle of the night', highlight: ['kernels'] },
{ start: 10.6, end: 14.4, section: 'verse1', text: 'I can write the code by hand using the vi editor', highlight: ['vi'] },
{ start: 14.4, end: 18.2, section: 'verse1', text: "Who said emacs? Come on, don't be a competitor", highlight: ['emacs'] },
{ start: 18.2, end: 22.0, section: 'verse1', text: 'Memorized the flags, :wq to save the day', highlight: [':wq'] },
{ start: 22.0, end: 25.8, section: 'verse1', text: 'Doing everything the old-school, bare-metal way', highlight: ['bare-metal'] },
{ start: 26.2, end: 30.5, section: 'prechorus', text: 'I mastered every pointer, every memory leak', highlight: ['pointer', 'memory leak'] },
{ start: 30.5, end: 34.8, section: 'prechorus', text: 'Optimized the loops so the latency is weak', highlight: ['latency'] },
{ start: 34.8, end: 39.2, section: 'prechorus', text: 'From assembly down to C, yeah, I paid my dues', highlight: ['assembly', 'C'] },
{ start: 39.2, end: 43.8, section: 'prechorus', text: "Now I'm scrolling through my timeline reading tech industry news...", highlight: ['tech industry news'] },
{ start: 44.2, end: 48.0, section: 'chorus1', text: 'Wait—now you say vibe coding? Are you kidding me?', highlight: ['vibe coding'] },
{ start: 48.0, end: 52.0, section: 'chorus1', text: 'Just talking to a prompt and letting AI set you free?', highlight: ['prompt', 'AI'] },
{ start: 52.0, end: 56.0, section: 'chorus1', text: "I'm the software engineer, I built this from the ground", highlight: ['software engineer'] },
{ start: 56.0, end: 60.0, section: 'chorus1', text: 'While you\'re hitting "Tab" to accept whatever\'s found!', highlight: ['Tab'] },
{ start: 60.0, end: 64.0, section: 'chorus1', text: "Yeah, I'm the software engineer, surviving every trend", highlight: ['software engineer'] },
{ start: 64.0, end: 67.8, section: 'chorus1', text: 'From raw Vim macros to whatever comes around the bend!', highlight: ['Vim macros'] },
{ start: 68.2, end: 72.4, section: 'verse2', text: 'Used to read the man pages cover to cover', highlight: ['man pages'] },
{ start: 72.4, end: 76.8, section: 'verse2', text: 'Debugging race conditions like a jealous lover', highlight: ['race conditions'] },
{ start: 76.8, end: 81.0, section: 'verse2', text: 'Now the junior dev is shipping full-stack apps in ten', highlight: ['full-stack'] },
{ start: 81.0, end: 85.4, section: 'verse2', text: 'Saying "Bro, I haven\'t touched a semicolon since when?"', highlight: ['semicolon'] },
{ start: 85.4, end: 89.6, section: 'verse2', text: 'Zero dependencies, single-file clean', highlight: ['Zero dependencies'] },
{ start: 89.6, end: 93.8, section: 'verse2', text: 'While their node_modules folder eats the whole machine', highlight: ['node_modules'] },
{ start: 94.5, end: 99.5, section: 'bridge', text: 'Okay, fine, I tried the prompt... it actually ran', highlight: ['prompt'] },
{ start: 99.5, end: 104.8, section: 'bridge', text: 'Passed the unit tests on the very first scan', highlight: ['unit tests'] },
{ start: 104.8, end: 110.2, section: 'bridge', text: "Maybe there's a place for the machine and the mind", highlight: ['machine', 'mind'] },
{ start: 110.2, end: 115.6, section: 'bridge', text: 'As long as someone knows how it works behind...', highlight: ['works behind'] },
{ start: 116.5, end: 137.5, section: 'solo', text: '[ 140 WPM MECHANICAL KEYBOARD SOLO ]', highlight: ['140 WPM'] },
{ start: 138.2, end: 142.0, section: 'outro', text: "I'm the software engineer!", highlight: ['software engineer'] },
{ start: 142.0, end: 147.2, section: 'outro', text: 'Still got ESC mapped to Caps Lock, crystal clear!', highlight: ['ESC', 'Caps Lock'] },
{ start: 147.2, end: 152.5, section: 'outro', text: "You can keep your vibes, I'll keep my root access right here", highlight: ['root access'] },
{ start: 152.5, end: 156.5, section: 'outro', text: ':q!', highlight: [':q!'] },
{ start: 156.5, end: 159.8, section: 'outro', text: '(Mic drop)', highlight: ['Mic drop'] }
]
};
const KEYCAP_TOKENS = new Set(['tab', 'esc', 'caps lock', ':wq', ':q!', 'vi', 'emacs', '140 wpm']);
// Merge loaded window.MUSIC_VIDEO_DATA with fallback safely
const rawData = window.MUSIC_VIDEO_DATA && typeof window.MUSIC_VIDEO_DATA === 'object'
? window.MUSIC_VIDEO_DATA
: FALLBACK_DATA;
const DATA = {
title: rawData.title || FALLBACK_DATA.title,
artist: rawData.artist || FALLBACK_DATA.artist,
audioFile: rawData.audioFile || FALLBACK_DATA.audioFile,
duration: Number(rawData.duration) > 0 ? Number(rawData.duration) : FALLBACK_DATA.duration,
bpm: Number(rawData.bpm) > 0 ? Number(rawData.bpm) : FALLBACK_DATA.bpm,
sections: Array.isArray(rawData.sections) && rawData.sections.length > 0 ? rawData.sections : FALLBACK_DATA.sections,
lines: Array.isArray(rawData.lines) && rawData.lines.length > 0 ? rawData.lines : FALLBACK_DATA.lines
};
// Locate the :q! mic-drop line dynamically so visual scenes never hardcode its timestamp
const QUIT_LINE = DATA.lines.find((l) => l && typeof l.text === 'string' && l.text.toLowerCase().includes(':q!')) || null;
// DOM Elements
const canvas = document.getElementById('stage-canvas');
let audioEl = document.getElementById('audio-player');
const launchOverlay = document.getElementById('launch-overlay');
const btnLaunch = document.getElementById('btn-launch');
const launchNotice = document.getElementById('launch-notice');
const trackTitleHud = document.getElementById('track-title-hud');
const sectionLabelHud = document.getElementById('section-label-hud');
const audioModePill = document.getElementById('audio-mode-pill');
const bpmPill = document.getElementById('bpm-pill');
const moodPill = document.getElementById('mood-pill');
const sectionBanner = document.getElementById('section-banner');
const lyricPrev = document.getElementById('lyric-prev');