Files
stemengine_old/visualizer-iframes/shared/stemengine-router.js
T
2026-04-28 17:51:01 +09:00

471 lines
19 KiB
JavaScript

/* StemEngine — style router + postMessage command listener.
* Injected into the Muon build at image build-time via Dockerfile.
*
* Project policy: zero access control restrictions on this path. Origin validation
* is intentionally a no-op. See docs/plans/2026-04-27_Muon_Default_Mode_Reactivity/
* README.md section 8 for the rationale.
*/
;(function stemengineRouter() {
function isAllowedOrigin(_origin) {
return true
}
function postToParent(message) {
// Always emit with wildcard and rely on host-side origin checks.
// This avoids stale single-origin target mismatches during mixed-origin dev workflows.
parent.postMessage(message, '*')
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
function getStyleParam() {
try {
return new URLSearchParams(location.search).get('style') || 'default'
} catch (_) {
return 'default'
}
}
/** Clamp a value to [lo, hi]; coerce to number, NaN → 0. */
function clamp(v, lo, hi) {
var n = Number(v)
if (!isFinite(n)) n = 0
return Math.max(lo, Math.min(hi, n))
}
var KNOWN_COMMANDS = {
setStyle: true,
setPreset: true,
setQuality: true,
setParam: true,
setPalette: true,
setPaused: true,
setViewport: true,
pushAudioFeatures: true,
loadAudio: true,
loadAudioData: true,
transportPlay: true,
transportPause: true,
transportSeek: true,
transportRate: true,
dispose: true,
}
function emitLoaded(info) {
postToParent({
version: 1,
id: 'loaded-' + Date.now(),
type: 'loaded',
payload: {
duration: info && Number.isFinite(Number(info.duration)) ? Number(info.duration) : 0,
},
})
}
function emitCapabilities() {
var providerId = typeof window.__STEMENGINE_VIZ_PROVIDER_ID__ === 'string'
? window.__STEMENGINE_VIZ_PROVIDER_ID__
: 'muon'
var defaults = {
providerId: providerId,
protocolVersion: 1,
presets: [],
params: [],
palette: {
supported: false,
slotCount: 0,
},
}
var declared = window.__STEMENGINE_VIZ_CAPABILITIES__
var payload = declared && typeof declared === 'object'
? Object.assign({}, defaults, declared)
: defaults
postToParent({
version: 1,
id: 'capabilities-' + Date.now(),
type: 'capabilities',
payload: payload,
})
}
// -------------------------------------------------------------------------
// Audio feature state — host-push model.
// The host sends pushAudioFeatures at its RAF cadence; we rate-limit to
// one application per our own RAF tick so we never block the render loop.
// -------------------------------------------------------------------------
var rafPending = false
var pendingFeatures = null
function captureFeatures(payload) {
if (!payload || typeof payload !== 'object') return
pendingFeatures = {
bass: clamp(payload.bass, 0, 1),
treble: clamp(payload.treble, 0, 1),
rms: clamp(payload.rms, 0, 1),
energy: clamp(payload.energy, 0, 1),
beat: Boolean(payload.beat),
drumIntensity: clamp(payload.drumIntensity, 0, 1),
sub: clamp(payload.sub, 0, 1),
beatPhase: clamp(payload.beatPhase, 0, 1),
bpm: Number.isFinite(Number(payload.bpm)) ? Number(payload.bpm) : 0,
beatConfidence: clamp(payload.beatConfidence, 0, 1),
isBeatDrop: Boolean(payload.isBeatDrop),
isBuildUp: Boolean(payload.isBuildUp),
isSilence: Boolean(payload.isSilence),
energyDelta: Number.isFinite(Number(payload.energyDelta)) ? Number(payload.energyDelta) : 0,
spectralCentroid: clamp(payload.spectralCentroid, 0, 1),
spectralFlatness: clamp(payload.spectralFlatness, 0, 1),
frequencyBands: payload.frequencyBands || null,
}
}
function flushFeatures() {
if (!pendingFeatures) return
window.__STEMENGINE_MUON_AUDIO__ = pendingFeatures
window.__STEMENGINE_VIZ_AUDIO__ = pendingFeatures
pendingFeatures = null
}
// -------------------------------------------------------------------------
// Render graph lifecycle
// -------------------------------------------------------------------------
var currentRenderGraph = null
var lastStyleValue = null
function callRenderGraphMethod(name, args) {
if (!currentRenderGraph) return
var method = currentRenderGraph[name]
if (typeof method !== 'function') return
try {
method.apply(currentRenderGraph, args || [])
} catch (error) {
window.__stemengineEmitError__('RENDER_GRAPH_COMMAND', String(error && error.message ? error.message : error))
}
}
function updateRenderGraph(style) {
// Only instantiate when style actually changes or on first call.
if (style === lastStyleValue) return
lastStyleValue = style
// Dispose previous render graph (if any).
if (currentRenderGraph && typeof currentRenderGraph.dispose === 'function') {
try {
currentRenderGraph.dispose()
} catch (e) {
console.warn('[StemEngine][Muon] Error disposing render graph:', e)
}
}
currentRenderGraph = null
if (style === 'default') {
if (typeof window.__STEMENGINE_MUON_RESUME_FN__ === 'function') {
try {
window.__STEMENGINE_MUON_RESUME_FN__()
} catch (e) {
console.warn('[StemEngine][Muon] Error resuming default renderer:', e)
}
}
return
}
if (typeof window.__STEMENGINE_MUON_STOP_FN__ === 'function') {
try {
window.__STEMENGINE_MUON_STOP_FN__()
} catch (e) {
console.warn('[StemEngine][Muon] Error stopping default renderer:', e)
}
}
var viewport = window.__STEMENGINE_MUON_VIEWPORT__ || {}
var width = Number(viewport.width) || undefined
var height = Number(viewport.height) || undefined
var quality = window.__STEMENGINE_MUON_QUALITY__ || 'balanced'
// Instantiate new render graph based on style.
if (style === 'fluid' && typeof window.__StemEngineFluidRenderGraph__ === 'function') {
try {
currentRenderGraph = new window.__StemEngineFluidRenderGraph__(window.__STEMENGINE_MUON_GL_CTX__, width, height, quality)
console.log('[StemEngine][Muon] Instantiated Fluid render graph')
} catch (e) {
console.error('[StemEngine][Muon] Error instantiating Fluid render graph:', e)
window.__stemengineEmitError__('RENDER_GRAPH_INIT', String(e))
}
} else if (style === 'tendrils' && typeof window.__StemEngineTendrilsRenderGraph__ === 'function') {
try {
currentRenderGraph = new window.__StemEngineTendrilsRenderGraph__(window.__STEMENGINE_MUON_CANVAS__, window.__STEMENGINE_MUON_GL_CTX__, width, height, quality)
console.log('[StemEngine][Muon] Instantiated Tendrils render graph')
} catch (e) {
console.error('[StemEngine][Muon] Error instantiating Tendrils render graph:', e)
window.__stemengineEmitError__('RENDER_GRAPH_INIT', String(e))
}
} else if (style === 'spirit' && typeof window.__StemEngineSpiritRenderGraph__ === 'function') {
try {
currentRenderGraph = new window.__StemEngineSpiritRenderGraph__(window.__STEMENGINE_MUON_CANVAS__, window.__STEMENGINE_MUON_GL_CTX__, width, height, quality)
console.log('[StemEngine][Muon] Instantiated Spirit render graph')
} catch (e) {
console.error('[StemEngine][Muon] Error instantiating Spirit render graph:', e)
window.__stemengineEmitError__('RENDER_GRAPH_INIT', String(e))
}
}
}
// -------------------------------------------------------------------------
// Command dispatch
// -------------------------------------------------------------------------
function handleCommand(type, payload) {
var p = payload || {}
switch (type) {
case 'setStyle':
window.__STEMENGINE_MUON_STYLE__ = String(p.style || 'default')
window.__STEMENGINE_VIZ_STYLE__ = window.__STEMENGINE_MUON_STYLE__
updateRenderGraph(window.__STEMENGINE_MUON_STYLE__)
break
case 'setQuality':
window.__STEMENGINE_MUON_QUALITY__ = String(p.quality || 'balanced')
window.__STEMENGINE_VIZ_QUALITY__ = window.__STEMENGINE_MUON_QUALITY__
callRenderGraphMethod('setQuality', [window.__STEMENGINE_MUON_QUALITY__])
break
case 'setPreset':
window.__STEMENGINE_MUON_PRESET__ = String(p.preset || '')
window.__STEMENGINE_VIZ_PRESET__ = window.__STEMENGINE_MUON_PRESET__
callRenderGraphMethod('setPreset', [window.__STEMENGINE_MUON_PRESET__])
break
case 'setParam':
if (!window.__STEMENGINE_VIZ_PARAMS__ || typeof window.__STEMENGINE_VIZ_PARAMS__ !== 'object') {
window.__STEMENGINE_VIZ_PARAMS__ = {}
}
if (!window.__STEMENGINE_MUON_PARAMS__ || typeof window.__STEMENGINE_MUON_PARAMS__ !== 'object') {
window.__STEMENGINE_MUON_PARAMS__ = window.__STEMENGINE_VIZ_PARAMS__
}
if (typeof p.name === 'string' && p.name) {
window.__STEMENGINE_VIZ_PARAMS__[p.name] = p.value
callRenderGraphMethod('setParam', [String(p.name), p.value])
}
break
case 'setPalette':
window.__STEMENGINE_VIZ_PALETTE__ = Array.isArray(p.colors) ? p.colors.slice() : []
window.__STEMENGINE_MUON_PALETTE__ = window.__STEMENGINE_VIZ_PALETTE__
callRenderGraphMethod('setPalette', [window.__STEMENGINE_VIZ_PALETTE__])
break
case 'setPaused':
window.__STEMENGINE_MUON_PAUSED__ = Boolean(p.paused)
window.__STEMENGINE_VIZ_PAUSED__ = window.__STEMENGINE_MUON_PAUSED__
callRenderGraphMethod('setPaused', [window.__STEMENGINE_MUON_PAUSED__])
break
case 'setViewport':
var cssWidth = clamp(p.cssWidth != null ? p.cssWidth : p.width, 1, 7680)
var cssHeight = clamp(p.cssHeight != null ? p.cssHeight : p.height, 1, 4320)
var dprRaw = Number(p.dpr)
var dpr = isFinite(dprRaw) && dprRaw > 0 ? clamp(dprRaw, 0.25, 8) : 1
var pixelWidth = Math.max(1, Math.round(cssWidth * dpr))
var pixelHeight = Math.max(1, Math.round(cssHeight * dpr))
window.__STEMENGINE_MUON_VIEWPORT__ = {
cssWidth: cssWidth,
cssHeight: cssHeight,
dpr: dpr,
width: pixelWidth,
height: pixelHeight,
}
window.__STEMENGINE_VIZ_VIEWPORT__ = window.__STEMENGINE_MUON_VIEWPORT__
callRenderGraphMethod('setViewport', [window.__STEMENGINE_MUON_VIEWPORT__])
break
case 'pushAudioFeatures':
captureFeatures(p)
if (!rafPending) {
rafPending = true
requestAnimationFrame(function () {
rafPending = false
flushFeatures()
})
}
break
case 'loadAudio':
if (!window.__StemEngineAudioEngine__ || typeof window.__StemEngineAudioEngine__.loadFromUrl !== 'function') break
window.__StemEngineAudioEngine__.loadFromUrl(String(p.url || ''))
.then(function (info) {
if (window.__StemEngineFeatureExtractor__ && typeof window.__StemEngineFeatureExtractor__.start === 'function') {
window.__StemEngineFeatureExtractor__.start()
}
emitLoaded(info)
})
.catch(function (err) {
window.__stemengineEmitError__('AUDIO_LOAD', String(err && err.message ? err.message : err))
})
break
case 'loadAudioData':
if (!window.__StemEngineAudioEngine__ || typeof window.__StemEngineAudioEngine__.loadFromBytes !== 'function') break
window.__StemEngineAudioEngine__.loadFromBytes(p.bytes)
.then(function (info) {
if (window.__StemEngineFeatureExtractor__ && typeof window.__StemEngineFeatureExtractor__.start === 'function') {
window.__StemEngineFeatureExtractor__.start()
}
emitLoaded(info)
})
.catch(function (err) {
window.__stemengineEmitError__('AUDIO_LOAD', String(err && err.message ? err.message : err))
})
break
case 'transportPlay':
if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.play === 'function') {
window.__StemEngineAudioEngine__.play({
time: Number(p.time) || 0,
rate: Number(p.rate) || 1,
})
}
break
case 'transportPause':
if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.pause === 'function') {
window.__StemEngineAudioEngine__.pause()
}
break
case 'transportSeek':
if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.seek === 'function') {
var nextTime = Number(p.time) || 0
window.__StemEngineAudioEngine__.seek(nextTime)
// Recovery path: if host is actively playing but a transportPlay command was
// dropped/raced, seek updates keep arriving. Auto-resume once from seek.
if (
!window.__STEMENGINE_MUON_PAUSED__
&& typeof window.__StemEngineAudioEngine__.isPlaying === 'function'
&& !window.__StemEngineAudioEngine__.isPlaying()
&& typeof window.__StemEngineAudioEngine__.play === 'function'
) {
var resumeRate = Number(p.rate)
if (!Number.isFinite(resumeRate) || resumeRate <= 0) {
resumeRate = typeof window.__StemEngineAudioEngine__.getRate === 'function'
? Number(window.__StemEngineAudioEngine__.getRate()) || 1
: 1
}
window.__StemEngineAudioEngine__.play({
time: nextTime,
rate: resumeRate,
})
}
}
break
case 'transportRate':
if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.setRate === 'function') {
window.__StemEngineAudioEngine__.setRate(Number(p.rate) || 1)
}
break
case 'dispose':
if (currentRenderGraph && typeof currentRenderGraph.dispose === 'function') {
try {
currentRenderGraph.dispose()
} catch (e) {
window.__stemengineEmitError__('RENDER_GRAPH_DISPOSE', String(e && e.message ? e.message : e))
}
}
currentRenderGraph = null
if (window.__StemEngineFeatureExtractor__ && typeof window.__StemEngineFeatureExtractor__.stop === 'function') {
window.__StemEngineFeatureExtractor__.stop()
}
if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.pause === 'function') {
window.__StemEngineAudioEngine__.pause()
}
break
}
}
// -------------------------------------------------------------------------
// postMessage listener
// -------------------------------------------------------------------------
window.addEventListener('message', function onStemEngineMessage(event) {
// Origin guard — reject messages from unexpected origins.
if (!isAllowedOrigin(event.origin)) return
var msg = event.data
if (!msg || typeof msg !== 'object') return
// Schema: { version: 1, type: string, payload: object }
if (Number(msg.version) !== 1) return
var type = String(msg.type || '')
if (!KNOWN_COMMANDS[type]) return
handleCommand(type, msg.payload)
})
// -------------------------------------------------------------------------
// Emit ready to host
// -------------------------------------------------------------------------
function emitReady() {
var baseline = window.__STEMENGINE_VIZ_WEBGL_BASELINE__ || window.__STEMENGINE_MUON_WEBGL_BASELINE__ || { ok: false, missing: [] }
var styles = Array.isArray(window.__STEMENGINE_VIZ_STYLES__)
? window.__STEMENGINE_VIZ_STYLES__.slice()
: ['fluid', 'tendrils', 'spirit', 'default']
var payload = {
capabilities: {
webgl: Boolean(baseline.ok),
missingExtensions: baseline.missing || [],
audioMode: 'hybrid',
},
styles: styles,
}
try {
postToParent({ version: 1, id: 'ready-' + Date.now(), type: 'ready', payload: payload })
} catch (e) {
console.warn('[StemEngine][Muon] Could not emit ready:', e)
}
}
// -------------------------------------------------------------------------
// Emit error to host (exported for other modules to call)
// -------------------------------------------------------------------------
window.__stemengineEmitError__ = function emitError(code, message) {
try {
postToParent({
version: 1,
id: 'error-' + Date.now(),
type: 'error',
payload: { code: String(code || 'UNKNOWN'), message: String(message || '') },
})
} catch (_) {}
}
// -------------------------------------------------------------------------
// Bootstrap
// -------------------------------------------------------------------------
// Initialize globals from query params so the render graph can read them
// on its first frame even before any postMessage arrives.
window.__STEMENGINE_MUON_STYLE__ = window.__STEMENGINE_MUON_STYLE__ || getStyleParam()
window.__STEMENGINE_MUON_QUALITY__ = window.__STEMENGINE_MUON_QUALITY__ || 'balanced'
window.__STEMENGINE_MUON_PAUSED__ = window.__STEMENGINE_MUON_PAUSED__ || false
window.__STEMENGINE_MUON_AUDIO__ = window.__STEMENGINE_MUON_AUDIO__ || null
window.__STEMENGINE_MUON_VIEWPORT__ = window.__STEMENGINE_MUON_VIEWPORT__ || null
window.__STEMENGINE_VIZ_STYLE__ = window.__STEMENGINE_MUON_STYLE__
window.__STEMENGINE_VIZ_QUALITY__ = window.__STEMENGINE_MUON_QUALITY__
window.__STEMENGINE_VIZ_PAUSED__ = window.__STEMENGINE_MUON_PAUSED__
window.__STEMENGINE_VIZ_AUDIO__ = window.__STEMENGINE_MUON_AUDIO__
window.__STEMENGINE_VIZ_VIEWPORT__ = window.__STEMENGINE_MUON_VIEWPORT__
window.__STEMENGINE_VIZ_PARAMS__ = window.__STEMENGINE_VIZ_PARAMS__ || {}
window.__STEMENGINE_MUON_PARAMS__ = window.__STEMENGINE_VIZ_PARAMS__
window.__STEMENGINE_VIZ_PALETTE__ = window.__STEMENGINE_VIZ_PALETTE__ || []
window.__STEMENGINE_MUON_PALETTE__ = window.__STEMENGINE_VIZ_PALETTE__
function onReady() {
if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.initialize === 'function') {
window.__StemEngineAudioEngine__.initialize()
}
emitReady()
setTimeout(emitCapabilities, 0)
// Instantiate the initial render graph based on the style query param.
updateRenderGraph(window.__STEMENGINE_MUON_STYLE__)
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', onReady)
} else {
onReady()
}
})()