import {SpatialAudio, parseFOAWav, clamp, wrapYaw} from './lib/foa.js'; import {Panorama} from './lib/panorama.js'; import {letters, newSession, canAnswer, submission, validSession} from './model.js'; const $ = id => document.getElementById(id); const storageKey = 'panogen-mos-random-four-v1'; const video = $('video'), audio = new SpatialAudio(); let study, session, panorama, trial, draft, active, request, ready = false, saving = false; let yaw = 0, pitch = 0, fov = 90, generation = 0, playbackGeneration = 0; let lastMediaTime = null, lastPersist = 0, lastSync = 0, scrubbing = false, resumeAfterScrub = false; let audioCache = new Map(); const url = asset => '/media/' + encodeURIComponent(asset); function error(message) { $('error').textContent = message; $('error').hidden = !message; } function persist() { try { localStorage.setItem(storageKey, JSON.stringify(session)); } catch { $('save-status').textContent = 'Browser backup is unavailable. Your ratings will still be saved to the study server when you continue.'; } } function show(screen) { for (const name of ['welcome', 'trial-screen', 'complete-screen']) $(name).hidden = name !== screen; window.scrollTo({top: 0, behavior: 'instant'}); } function updatePose() { yaw = wrapYaw(yaw); pitch = clamp(pitch, -85, 85); fov = clamp(fov, 35, 120); if (draft) draft.pose = {yaw, pitch, fov}; audio.setPose(yaw, pitch); $('pose-label').textContent = `${Math.round(yaw)}° yaw · ${Math.round(pitch)}° pitch · ${Math.round(fov)}° field of view`; } function applyGain() { audio.setGain((active?.gain_db || 0) + session.volume_db); $('volume').value = session.volume_db; $('volume-value').textContent = session.volume_db + ' dB'; } function pause() { playbackGeneration++; video.pause(); audio.stop(); lastMediaTime = null; $('play').textContent = '▶ Play'; $('play').setAttribute('aria-label', 'Play current option'); } async function play() { if (!ready) return; const token = ++playbackGeneration; try { await audio.context.resume(); if (token !== playbackGeneration || !ready) return; if (video.currentTime >= trial.duration - 0.02) video.currentTime = 0; await video.play(); if (token !== playbackGeneration || !ready) return; $('play').textContent = 'Ⅱ Pause'; $('play').setAttribute('aria-label', 'Pause current option'); $('playback-status').textContent = trial.kind === 'audio' ? 'Playing · sound follows your view' : 'Playing · silent video'; } catch (e) { if (token === playbackGeneration) { pause(); error('Playback could not start: ' + e.message); } } } function syncAudio() { if (!ready || video.paused || video.seeking || video.readyState < 3 || trial.kind !== 'audio') return; audio.start(video.currentTime); if (audio.source) audio.source.stop(audio.context.currentTime + Math.max(0, trial.duration - video.currentTime)); } function finishClip() { pause(); if ($('loop').checked && ready) { video.currentTime = 0; play(); } else $('playback-status').textContent = 'Clip finished · replay or compare another option'; } function updateChoices() { if (!trial) return; const assignment = session.option_order[trial.id]; let played = 0; for (const id of assignment) { const row = $('choice-' + id), hasPlayed = (draft.reviewed_seconds[id] || 0) > 0; played += Number(hasPlayed); row.classList.toggle('active', active?.id === id); const rated = trial.questions.filter(q => Number.isInteger(draft.ratings[id]?.[q.id])).length; row.querySelector('small').textContent = rated === 3 ? '✓ Rated' : `${rated}/3 rated`; row.querySelector('button').setAttribute('aria-pressed', String(active?.id === id)); } $('review-count').textContent = `${played} / ${assignment.length} played`; for (const card of $('questions').children) card.hidden = card.dataset.candidate !== active?.id; for (const input of $('questions').querySelectorAll('input')) { input.checked = draft.ratings[input.dataset.candidate]?.[input.dataset.criterion] === Number(input.value); input.disabled = saving || session.pending_trial === trial.id; } const answered = assignment.reduce((sum, id) => sum + trial.questions.filter(q => Number.isInteger(draft.ratings[id]?.[q.id])).length, 0); const total = assignment.length * trial.questions.length; const valid = canAnswer(assignment, trial.questions, draft.ratings); $('continue').disabled = (!valid && session.pending_trial !== trial.id) || saving; $('choice-help').textContent = `${answered} of ${total} ratings completed. ` + (valid ? 'Ready to save your ratings.' : 'Rate all four samples on all three criteria.'); if (session.pending_trial === trial.id) $('choice-help').textContent = 'Your ratings are ready to save. Retry the save button if the connection was interrupted.'; } function videoLoaded(asset, signal) { return new Promise((resolve, reject) => { const cleanup = () => { video.removeEventListener('loadeddata', loaded); video.removeEventListener('error', failed); signal.removeEventListener('abort', aborted); }; const loaded = () => { cleanup(); resolve(); }; const failed = () => { cleanup(); reject(new Error('Video could not load. Please retry, or use a browser with H.264 video support.')); }; const aborted = () => { cleanup(); reject(new DOMException('Selection changed', 'AbortError')); }; video.addEventListener('loadeddata', loaded); video.addEventListener('error', failed); signal.addEventListener('abort', aborted, {once: true}); video.src = url(asset); video.load(); }); } async function activateOption(id, autoplay = false) { const token = ++generation; request?.abort(); request = new AbortController(); const signal = request.signal; pause(); ready = false; error(''); active = trial.candidates.find(c => c.id === id); draft.active = id; $('play').disabled = $('timeline').disabled = true; $('loading').hidden = false; $('loading').textContent = 'Preparing option…'; $('retry-media').hidden = true; $('active-label').textContent = 'OPTION ' + letters[session.option_order[trial.id].indexOf(id)]; updateChoices(); persist(); if (autoplay) audio.context.resume().catch(e => error(e.message)); try { let wavPromise = Promise.resolve(null); if (active.audio) { wavPromise = audioCache.has(id) ? Promise.resolve(audioCache.get(id)) : fetch(url(active.audio), {signal}).then(response => { if (!response.ok) throw new Error('Audio could not load. Please retry.'); return response.arrayBuffer(); }).then(parseFOAWav); } const [, wav] = await Promise.all([videoLoaded(active.video, signal), wavPromise]); if (token !== generation) return; if (wav) { audioCache.set(id, wav); audio.setBuffer(wav); } applyGain(); updatePose(); ready = true; $('loading').hidden = true; $('play').disabled = $('timeline').disabled = false; $('timeline').max = trial.duration; $('timeline').value = 0; $('playback-status').textContent = trial.kind === 'audio' ? 'Ready · use headphones and explore' : 'Ready · same view, same two-second window'; if (autoplay) await play(); } catch (e) { if (token === generation && e.name !== 'AbortError') { $('loading').textContent = e.message; $('retry-media').hidden = false; } } } function enterTrial() { pause(); ready = false; trial = study.trials.find(t => t.id === session.trial_order[session.index]); if (!trial) return; audioCache.clear(); draft = session.drafts[trial.id] ||= {ratings: {}, reviewed_seconds: Object.fromEntries(trial.candidates.map(c => [c.id, 0])), pose: {yaw: 0, pitch: 0, fov: 90}, started_at: Date.now()}; ({yaw, pitch, fov} = draft.pose); active = null; $('trial-count').textContent = `COMPARISON ${session.index + 1} OF ${study.trials.length}`; $('section-name').textContent = trial.kind === 'audio' ? 'SPATIAL AUDIO' : 'VIDEO QUALITY'; $('scene-title').textContent = trial.title; $('choices-title').textContent = 'Play & rate each sample'; $('question').textContent = trial.kind === 'audio' ? 'Rate each soundtrack' : 'Rate each video'; $('criteria').textContent = 'Choose a sample, then rate Q1, Q2 and Q3 beside the player. Your scores stay saved when you switch.'; const objects = Object.fromEntries(trial.foreground_objects.map(o => [o.id, o.description])); $('global-prompt').replaceChildren(...trial.prompt_segments.map(segment => { if (!segment.object_id) return document.createTextNode(segment.text); const mark = document.createElement('mark'); mark.textContent = segment.text; mark.title = objects[segment.object_id]; return mark; })); $('trial-meta').textContent = trial.kind === 'audio' ? '6-second clips · Headphones' : '2-second clips · Silent'; $('sound-label').textContent = trial.kind === 'audio' ? 'HEADPHONE AUDIO' : 'SILENT VIDEO'; $('volume-control').hidden = trial.kind !== 'audio'; $('progress').replaceChildren(...session.trial_order.map((_, i) => { const step = document.createElement('span'); step.className = i < session.index ? 'done' : i === session.index ? 'current' : ''; return step; })); $('continue').textContent = session.index === study.trials.length - 1 ? 'Submit my answers ✓' : 'Save ratings & continue →'; $('participant-label').textContent = 'Participant ' + session.participant_id.slice(0, 8); $('choices').replaceChildren(); for (const [index, id] of session.option_order[trial.id].entries()) { const row = document.createElement('div'); row.className = 'option'; row.id = 'choice-' + id; row.innerHTML = ``; row.querySelector('button').onclick = () => activateOption(id, true); $('choices').append(row); } $('questions').replaceChildren(); for (const [index, id] of session.option_order[trial.id].entries()) { const card = document.createElement('section'); card.className = 'sample-ratings'; card.dataset.candidate = id; const heading = document.createElement('div'); heading.className = 'section-top'; const title = document.createElement('h2'); title.textContent = `Option ${letters[index]}`; heading.append(title); card.append(heading); const criteria = document.createElement('div'); criteria.className = 'sample-criteria'; for (const [number, question] of trial.questions.entries()) { const field = document.createElement('fieldset'); field.className = 'criterion'; const legend = document.createElement('legend'); const numberLabel = document.createElement('strong'); numberLabel.textContent = `Q${number + 1}`; const questionLabel = document.createElement('span'); questionLabel.textContent = question.label; legend.append(numberLabel, questionLabel); field.title = question.description; const options = document.createElement('div'); options.className = 'criterion-options'; for (const [value, anchor] of Object.entries(study.rating_scale)) { const label = document.createElement('label'); label.className = 'criterion-option'; const input = document.createElement('input'); input.type = 'radio'; input.name = `${id}-${question.id}`; input.value = value; input.dataset.candidate = id; input.dataset.criterion = question.id; input.setAttribute('aria-label', `Option ${letters[index]}, ${question.label}: ${value} ${anchor}`); input.onchange = () => { (draft.ratings[id] ||= {})[question.id] = Number(value); updateChoices(); persist(); }; const text = document.createElement('span'); text.textContent = `${value} · ${anchor}`; label.append(input, text); options.append(label); } field.append(legend, options); criteria.append(field); } card.append(criteria); $('questions').append(card); } $('loop').checked = false; show('trial-screen'); updateChoices(); updatePose(); activateOption(draft.active || session.option_order[trial.id][0]); } async function saveChoice() { if (saving || (session.pending_trial !== trial.id && !canAnswer(session.option_order[trial.id], trial.questions, draft.ratings))) return; pause(); saving = true; error(''); updateChoices(); // Freeze the payload until acknowledgment: a retry after a lost response must be identical. if (session.pending_trial !== trial.id) { session.answers[trial.id] = {ratings: structuredClone(draft.ratings), reviewed_seconds: {...draft.reviewed_seconds}, pose: {...draft.pose}, elapsed_seconds: Math.min(86400 * 30, (Date.now() - draft.started_at) / 1000), volume_db: session.volume_db}; session.pending_trial = trial.id; session.complete = session.index === study.trials.length - 1; } persist(); updateChoices(); $('save-status').textContent = 'Saving to the study server…'; try { const response = await fetch('/api/responses', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(submission(session)), signal: AbortSignal.timeout(15000)}); const result = await response.json(); if (!response.ok || !result.saved) throw new Error(result.error || 'Saving failed.'); delete session.pending_trial; session.receipt = result; if (session.complete) { session.submitted = true; session.index = study.trials.length; persist(); showComplete(); } else { session.index++; persist(); $('save-status').textContent = 'Previous ratings saved to the study server.'; enterTrial(); } } catch (e) { $('save-status').textContent = 'Not yet saved to the study server. Your browser backup is retained.'; error('We could not confirm that your ratings were saved. Keep this page open and press the save button again. ' + e.message); } finally { saving = false; updateChoices(); } } function showComplete() { pause(); ready = false; show('complete-screen'); $('receipt').replaceChildren(); const questionCount = Object.values(session.answers).reduce((sum, answer) => sum + Object.values(answer.ratings).reduce((n, scores) => n + Object.keys(scores).length, 0), 0); for (const text of [`${questionCount} ratings saved across ${study.trials.length} scenes`, 'Participant: ' + session.participant_id, 'Saved: ' + new Date(session.receipt.saved_at).toLocaleString()]) { const line = document.createElement('div'); line.textContent = text; $('receipt').append(line); } } function download(type) { const payload = submission(session); const rows = session.trial_order.flatMap((id, i) => { const answer = session.answers[id], t = study.trials.find(t => t.id === id); return session.option_order[id].flatMap((candidate, index) => t.questions.map(q => ({participant_id: session.participant_id, version: session.version, trial_number: i + 1, trial_id: id, kind: t.kind, scene: t.title, criterion_id: q.id, criterion: q.label, option: letters[index], candidate_id: candidate, score: answer.ratings[candidate]?.[q.id] ?? '', elapsed_seconds: answer.elapsed_seconds}))); }); const quote = text => '"' + String(text).replaceAll('"', '""') + '"'; const content = type === 'json' ? JSON.stringify({...payload, receipt: session.receipt}, null, 2) : [Object.keys(rows[0]), ...rows.map(Object.values)].map(row => row.map(quote).join(',')).join('\r\n'); const link = document.createElement('a'), objectURL = URL.createObjectURL(new Blob([content], {type: type === 'json' ? 'application/json' : 'text/csv;charset=utf-8'})); link.href = objectURL; link.download = `study-${session.participant_id}.${type}`; link.click(); setTimeout(() => URL.revokeObjectURL(objectURL), 1000); } $('headphones').onchange = () => { $('start').disabled = !study || !$('headphones').checked; }; $('start').onclick = async () => { $('start').disabled = true; error(''); try { const initializing = audio.initialize(); await audio.context.resume(); await initializing; persist(); enterTrial(); } catch (e) { error('Could not initialize audio: ' + e.message); $('start').disabled = false; } }; $('continue').onclick = () => saveChoice(); $('play').onclick = () => video.paused ? play() : pause(); $('retry-media').onclick = () => activateOption(active.id); $('reset-view').onclick = () => { yaw = pitch = 0; fov = 90; updatePose(); persist(); }; $('volume').oninput = () => { session.volume_db = Number($('volume').value); applyGain(); persist(); }; $('timeline').oninput = () => { if (!scrubbing) { resumeAfterScrub = !video.paused; scrubbing = true; pause(); } video.currentTime = Number($('timeline').value); }; $('timeline').onchange = () => { scrubbing = false; if (resumeAfterScrub) play(); }; $('download-json').onclick = () => download('json'); $('download-csv').onclick = () => download('csv'); $('new-participant').onclick = async () => { try { study = await fetchStudy(); } catch (e) { error(e.message); return; } session = newSession(study); trial = draft = active = null; persist(); $('headphones').checked = false; $('start').textContent = 'Begin study →'; $('start').disabled = true; $('resume-note').textContent = ''; error(''); show('welcome'); }; let drag; $('perspective').onpointerdown = e => { if (e.button !== 0) return; drag = {x: e.clientX, y: e.clientY, yaw, pitch}; $('perspective').setPointerCapture(e.pointerId); }; $('perspective').onpointermove = e => { if (!drag) return; const scale = fov / $('perspective').clientWidth; yaw = drag.yaw + (e.clientX - drag.x) * scale; pitch = drag.pitch + (e.clientY - drag.y) * scale; updatePose(); }; $('perspective').onpointerup = $('perspective').onpointercancel = () => { drag = null; if (session) persist(); }; $('perspective').addEventListener('wheel', e => { e.preventDefault(); fov += e.deltaY * 0.04; updatePose(); }, {passive: false}); $('overview').onclick = e => { const rect = $('overview').getBoundingClientRect(); yaw = 180 - 360 * (e.clientX - rect.left) / rect.width; pitch = 90 - 180 * (e.clientY - rect.top) / rect.height; updatePose(); persist(); }; document.addEventListener('keydown', e => { if ($('trial-screen').hidden || ['INPUT','BUTTON','A'].includes(e.target.tagName)) return; if (e.code === 'Space') { e.preventDefault(); video.paused ? play() : pause(); } if (e.key.startsWith('Arrow')) { e.preventDefault(); yaw += e.key === 'ArrowLeft' ? 5 : e.key === 'ArrowRight' ? -5 : 0; pitch += e.key === 'ArrowUp' ? 5 : e.key === 'ArrowDown' ? -5 : 0; updatePose(); } }); video.muted = true; video.addEventListener('playing', syncAudio); video.addEventListener('waiting', () => { audio.stop(); lastMediaTime = null; $('playback-status').textContent = 'Buffering…'; }); video.addEventListener('pause', () => { audio.stop(); }); video.addEventListener('seeking', () => { audio.stop(); lastMediaTime = null; }); video.addEventListener('seeked', syncAudio); video.addEventListener('ended', () => { if (ready) finishClip(); }); document.addEventListener('visibilitychange', () => { if (document.hidden) { pause(); if (session) persist(); } }); window.addEventListener('pagehide', () => { pause(); if (session) persist(); }); function animate(now) { if (ready && !$('trial-screen').hidden) { panorama.draw(yaw, pitch, fov); if (!scrubbing) $('timeline').value = Math.min(video.currentTime, trial.duration); $('time').textContent = `${Math.min(video.currentTime,trial.duration).toFixed(1)} / ${trial.duration.toFixed(1)} s`; if (!video.paused && !video.seeking && video.readyState >= 3) { const time = Math.min(video.currentTime, trial.duration); if (lastMediaTime !== null) { const delta = time - lastMediaTime; if (delta > 0 && delta < 0.3) { draft.reviewed_seconds[active.id] = Math.min(trial.duration, (draft.reviewed_seconds[active.id] || 0) + delta); updateChoices(); } } lastMediaTime = time; if (now - lastSync > 250 && trial.kind === 'audio' && audio.position !== null) { if (Math.abs(audio.position - video.currentTime) > 0.08) syncAudio(); lastSync = now; } if (video.currentTime >= trial.duration) finishClip(); } if (now - lastPersist > 1000) { persist(); lastPersist = now; } } requestAnimationFrame(animate); } async function fetchStudy(participantId) { const response = await fetch('/api/study' + (participantId ? '?participant_id=' + encodeURIComponent(participantId) : '')); if (!response.ok) throw new Error('The study could not load. Please refresh and try again.'); return response.json(); } async function main() { if (location.protocol === 'file:') throw new Error('Open launch.command in this folder to start the study website and enable response saving.'); try { session = JSON.parse(localStorage.getItem(storageKey)); } catch { session = null; } const savedId = /^[0-9a-f-]{36}$/i.test(session?.participant_id || '') ? session.participant_id : null; study = await fetchStudy(savedId); if (!validSession(session, study)) { if (savedId) study = await fetchStudy(); session = newSession(study); } persist(); $('total-trials').textContent = study.trials.length; $('video-trials').textContent = study.trials.filter(t => t.kind === 'video').length; $('audio-trials').textContent = study.trials.filter(t => t.kind === 'audio').length; panorama = new Panorama($('perspective'), $('overview'), video); requestAnimationFrame(animate); if (session.submitted) { showComplete(); return; } const resuming = session.index > 0 || Object.keys(session.drafts).length > 0; $('start').textContent = resuming ? 'Resume study →' : 'Begin study →'; $('resume-note').textContent = resuming ? `Your progress is saved. Continue at comparison ${session.index + 1} of ${study.trials.length}.` : 'The audio comparisons come first in this audition round.'; $('start').disabled = !$('headphones').checked; } main().catch(e => error(e.message));