/* ==========================================================================
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, ''');
}
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 `${match}`;
}
return `${match}`;
});
}
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