ryanrahman21's picture
Restore native 1920 × 1200 stereo frames and matching camera calibration for all v1 trials
e8be409 verified
Raw History Blame Contribute Delete
32.5 kB
'use strict';
const $ = id => document.getElementById(id);
const video = $('trialVideo');
const state = {
catalog: [], data: null, id: null, frame: 0, generation: 0, seekToken: 0,
ready: false, playing: false, seeking: false, eye: 'right', presented: 0,
videoCallback: null, videoGeneration: 0, trialAbort: null, detailAbort: null,
emg: null, emgDrawAt: 0,
detailAt: 0, detailToken: 0, seekPromise: Promise.resolve(),
pressureMode: 'raw', pressureRecovered: null, pressureSmoothed: null, pressureAxis: null,
timelineBase: document.createElement('canvas'), timelineDirty: true,
};
const fingerColors = ['#f5c36c', '#71baff', '#79ddc1', '#c0a1ff', '#efa0bd'];
const pressureTraces = [
{name:'thumb',color:'#a45713'},
{name:'index',color:'#176650'},
];
const plotColors={paper:'#ffffff',surface:'#fafafa',grid:'#dedede',baseline:'#aaaaaa',label:'#626262',ink:'#111111',emg:'#37655a',unapproved:'#946100'};
const PRESSURE_SIGMA_SECONDS=.050;
const contactColors = {
1: 'rgba(74,222,128,0.16)',
0: 'rgba(148,163,184,0.12)',
'-1': 'rgba(245,158,11,0.22)',
};
function gaussianSmoothPressure(values,times,valid,sigma=PRESSURE_SIGMA_SECONDS,maxGap=1.5/30) {
const result=Array(values.length).fill(null),radius=4*sigma+1e-9;
const supported=i=>valid[i]&&finite(values[i])&&finite(times[i]);
for(let start=0;start<values.length;){
if(!supported(start)){start++;continue;}
let end=start+1;
while(end<values.length&&supported(end)&&times[end]>times[end-1]&&times[end]-times[end-1]<=maxGap)end++;
let left=start,right=start;
for(let i=start;i<end;i++){
while(times[i]-times[left]>radius)left++;
while(right+1<end&&times[right+1]-times[i]<=radius)right++;
let total=0,weightSum=0;
for(let j=left;j<=right;j++){
const distance=(times[j]-times[i])/sigma,weight=Math.exp(-.5*distance*distance);
total+=weight*values[j];weightSum+=weight;
}
result[i]=total/weightSum;
}
start=end;
}
return result;
}
function recoverPressureActivation(value,name) {
if(!finite(value))return null;
if(name==='thumb')return Math.max(0,(value+3.400553667092545)/0.5170289437889563);
if(name==='index')return Math.max(0,(value+5.729761362606111)/0.5819535950321174);
throw new Error(`No activation transform for ${name}`);
}
function preparePressure() {
if(state.pressureRecovered)return;
const c=state.data.columns;
state.pressureRecovered=Object.fromEntries(pressureTraces.map(({name})=>[name,
c[`pressure_${name}_adc`].map((value,i)=>c.model_valid[i]?recoverPressureActivation(value,name):null)]));
let high=0;
for(const samples of Object.values(state.pressureRecovered)){
for(const value of samples)if(finite(value))high=Math.max(high,value);
}
// A Gaussian weighted average stays within the raw range. Fix both modes and
// both fingers to this trial-wide scale; keep an empty/all-zero trial drawable.
state.pressureAxis={low:0,high:high>0?high:1};
}
function pressureSeries(name) {
preparePressure();
const c=state.data.columns;
if(state.pressureMode==='raw')return state.pressureRecovered[name];
if(!state.pressureSmoothed){
state.pressureSmoothed=Object.fromEntries(pressureTraces.map(({name})=>[name,
gaussianSmoothPressure(state.pressureRecovered[name],c.host_seconds,c.model_valid,PRESSURE_SIGMA_SECONDS,1.5/state.data.fps)]));
}
return state.pressureSmoothed[name];
}
// A label covers its frame's playback interval [i/fps, (i+1)/fps).
// Keep this independent of model support and pressure smoothing.
function contactIntervals(contact,fps,start=0,end=contact.length/fps) {
const intervals=[];
if(end<=start)return intervals;
const first=Math.max(0,Math.floor(start*fps)),stop=Math.min(contact.length,Math.ceil(end*fps));
for(let i=first;i<stop;i++){
const from=Math.max(start,i/fps),to=Math.min(end,(i+1)/fps);
if(to<=from)continue;
const value=contact[i]===1?1:contact[i]===0?0:-1;
const previous=intervals.at(-1);
if(previous?.value===value)previous.end=to;
else intervals.push({start:from,end:to,value});
}
return intervals;
}
function drawContactBackground(ctx,contact,fps,start,end,left,right,top,bottom) {
const x=t=>left+(t-start)/(end-start)*(right-left);
for(const interval of contactIntervals(contact,fps,start,end)){
ctx.fillStyle=contactColors[interval.value];
ctx.fillRect(x(interval.start),top,x(interval.end)-x(interval.start),bottom-top);
}
}
const bones = [];
for (let finger=0; finger<5; finger++) {
const base=1+4*finger;
bones.push([0,base,finger], [base,base+1,finger], [base+1,base+2,finger], [base+2,base+3,finger]);
}
const clamp = (v,a,b) => Math.max(a,Math.min(b,v));
const finite = v => typeof v === 'number' && Number.isFinite(v);
const fmt = (v,d=1) => finite(v) ? v.toFixed(d) : 'N/A';
const pad = n => String(n).padStart(2,'0');
function timeLabel(seconds, decimals=2) {
const scale=10**decimals, ticks=Math.max(0,Math.round(seconds*scale));
return `${Math.floor(ticks/(60*scale))}:${((ticks%(60*scale))/scale).toFixed(decimals).padStart(decimals ? decimals+3 : 2,'0')}`;
}
function setStatus(message, error=false) { $('status').textContent=message; $('status').hidden=!message; $('status').classList.toggle('error',error); }
async function api(path, signal) {
const response=await fetch(path,{signal});
const data=await response.json();
if (!response.ok) throw new Error(data.error||`Request failed (${response.status})`);
return data;
}
function setupCanvas(canvas, h=null) {
const width=Math.max(1,canvas.clientWidth), height=h||canvas.clientHeight, ratio=window.devicePixelRatio||1;
const w=Math.round(width*ratio), hh=Math.round(height*ratio);
if(canvas.width!==w||canvas.height!==hh) {canvas.width=w;canvas.height=hh;}
const ctx=canvas.getContext('2d');ctx.setTransform(ratio,0,0,ratio,0,0);
return {ctx,width,height,ratio};
}
function resetSignals() {
$('contactState').textContent='—';$('contactState').className='contact unknown';
for(const {name} of pressureTraces) {
$(name+'HistoryValue').textContent='—';
const canvas=$(name+'History');canvas.getContext('2d').clearRect(0,0,canvas.width,canvas.height);
}
$('timeDisplay').textContent='Loading trial…';$('seek').value=0;
$('trialDetails').textContent='Loading trial…';
$('frameDetails').textContent='Loading trial…';$('detailFrame').textContent='';
for(const id of ['poseOverlay','timeline','emgCanvas','contactHistory']) {const c=$(id);c.getContext('2d').clearRect(0,0,c.width,c.height);}
}
function stopCallbacks() {
state.videoGeneration++;
if(state.videoCallback!=null && video.cancelVideoFrameCallback)video.cancelVideoFrameCallback(state.videoCallback);
state.videoCallback=null;
}
function updateEyeControls() {
$('goSeek').disabled=!state.ready;
for(const eye of ['left','right']){
$(eye+'EyeButton').setAttribute('aria-pressed',String(state.eye===eye));
$(eye+'EyeButton').disabled=!state.ready;
}
video.setAttribute('aria-label',`${state.eye==='left'?'Left':'Right'}-eye trial video`);
$('poseOverlay').setAttribute('aria-label',`Projected hand skeleton in ${state.eye} view`);
}
async function selectEye(eye) {
if(!state.ready||eye===state.eye||!['left','right'].includes(eye))return;
// Finish an in-flight seek before changing sources, keeping the requested frame.
const generation=state.generation;
await state.seekPromise;
if(!state.ready||generation!==state.generation||eye===state.eye)return;
const frame=state.frame,resume=state.playing;
state.ready=false;pause();stopCallbacks();state.eye=eye;updateEyeControls();
$('playButton').disabled=true;$('seek').disabled=true;
document.body.classList.add('switching-eye');
try {
await videoReady(video,state.data.video[eye],state.trialAbort.signal);
if(generation!==state.generation)return;
video.playbackRate=Number($('speed').value);
state.ready=true;await seekFrame(frame);
if(generation!==state.generation)return;
updateEyeControls();$('playButton').disabled=false;$('seek').disabled=false;
document.body.classList.remove('switching-eye');startVideoCallback(generation);
if(resume)await togglePlay();
} catch(error){
if(error.name!=='AbortError'&&generation===state.generation){
document.body.classList.remove('switching-eye');setStatus(error.message,true);
}
}
}
function videoReady(video,url,signal) {
return new Promise((resolve,reject)=>{
let timer;
const finish=(error)=>{clearTimeout(timer);video.removeEventListener('loadeddata',ready);video.removeEventListener('error',failed);signal.removeEventListener('abort',aborted);error?reject(error):resolve();};
const ready=()=>finish(), failed=()=>finish(new Error('Video could not load. Check the local server.'));
const aborted=()=>finish(new DOMException('Cancelled','AbortError'));
video.addEventListener('loadeddata',ready,{once:true});video.addEventListener('error',failed,{once:true});signal.addEventListener('abort',aborted,{once:true});
timer=setTimeout(()=>finish(new Error('Timed out loading video')),30000);
video.src=url;video.load();
});
}
async function loadTrial(id) {
const generation=++state.generation;
state.trialAbort?.abort();state.detailAbort?.abort();
state.trialAbort=new AbortController();
const signal=state.trialAbort.signal;
state.ready=false;pause();stopCallbacks();state.data=null;state.pressureRecovered=null;state.pressureSmoothed=null;state.pressureAxis=null;state.emg=null;
state.seeking=false;state.seekToken++;state.id=id;state.frame=0;state.presented=0;
document.body.classList.remove('switching-eye');updateEyeControls();
document.body.classList.add('loading');resetSignals();
$('playButton').disabled=true;$('seek').disabled=true;$('trialSelect').value=String(id);
const selected=state.catalog.find(t=>t.episode_index===id);
setStatus(`Loading trial ${pad(id)} · ${selected.participant}…`);
$('trialStats').replaceChildren();
const stats=[['Frames',selected.frames.toLocaleString()],['Duration',timeLabel(selected.duration,1)]];
for(const [label,value] of stats) {const s=document.createElement('span');const strong=document.createElement('strong');strong.textContent=value;s.append(document.createTextNode(label),strong);$('trialStats').append(s);}
try {
const [data,emg]=await Promise.all([api(`/api/trial/${id}`,signal),loadFullEmg(selected,signal)]);
if(generation!==state.generation)return;
state.data=data;state.emg=emg;
preparePressure();
$('trialDetails').textContent=JSON.stringify({trial:selected,displayed_emg:data.emg_source,camera_imu:data.camera_imu,calibration:data.calibration,host_origin_ns:data.host_origin_ns},null,2);
const [width,height]=data.image_size;
const canvas=$('poseOverlay');canvas.width=width;canvas.height=height;
canvas.parentElement.style.aspectRatio=`${width}/${height}`;
canvas.parentElement.style.maxWidth=`${420*width/height}px`;
video.playbackRate=Number($('speed').value);
await videoReady(video,data.video[state.eye],signal);
if(generation!==state.generation)return;
state.ready=true;$('playButton').disabled=false;$('seek').disabled=false;$('seek').max=data.length-1;
state.timelineDirty=true;document.body.classList.remove('loading');
await seekFrame(0);
if(generation!==state.generation)return;
updateEyeControls();startVideoCallback(generation);
setStatus('');
history.replaceState(null,'',`#trial=${id}`);
} catch(error) {if(error.name!=='AbortError'&&generation===state.generation){state.trialAbort.abort();document.body.classList.remove('loading');setStatus(error.message,true);}}
}
function pause() {
const wasPlaying=state.playing;
state.playing=false;video.pause();
$('playButton').textContent='▶ Play';
if(wasPlaying&&state.ready&&!state.seeking){seekFrame(state.frame);return;}
if(state.ready&&state.data&&$('details').open)loadDetails();
}
async function togglePlay() {
if(!state.ready)return;
if(state.playing){pause();return;}
const generation=state.generation;
await state.seekPromise;
if(!state.ready||generation!==state.generation)return;
if(state.frame>=state.data.length-1)await seekFrame(0);
try {
await video.play();
if(generation!==state.generation)return;
state.playing=true;$('playButton').textContent='Ⅱ Pause';
if($('details').open)$('frameDetails').textContent='Pause playback to inspect the complete current frame.';
} catch(error){pause();setStatus(`Playback could not start: ${error.message}`,true);}
}
function seekVideo(video,time) {
return new Promise((resolve,reject)=>{
if(!video.seeking&&Math.abs(video.currentTime-time)<.00002&&video.readyState>=2){resolve();return;}
const timer=setTimeout(()=>finish(new Error('Video seek timed out')),10000);
function finish(error){clearTimeout(timer);video.removeEventListener('seeked',done);error?reject(error):resolve();}
function done(){finish();}
video.addEventListener('seeked',done,{once:true});video.currentTime=time;
});
}
function seekFrame(index) {
if(!state.ready)return Promise.resolve();
index=clamp(Math.round(index),0,state.data.length-1);
const token=++state.seekToken,generation=state.generation;
state.seeking=true;
// Hide stale overlays while the decoders resolve the requested exposure.
$('poseOverlay').style.visibility='hidden';
const work=(async()=>{
try {
const t=index/state.data.fps+0.0001;
await seekVideo(video,t);
if(token!==state.seekToken||generation!==state.generation)return;
state.seeking=false;state.presented=index;
$('poseOverlay').style.visibility='';
renderFrame(index,true);
drawOverlay(index);
} catch(error){if(token===state.seekToken&&generation===state.generation){state.seeking=false;setStatus(error.message,true);}}
})();
state.seekPromise=work;return work;
}
function startVideoCallback(generation) {
if(!video.requestVideoFrameCallback)return;
const videoGeneration=state.videoGeneration;
const callback=(now,metadata)=>{
if(generation!==state.generation||videoGeneration!==state.videoGeneration||!state.data)return;
const index=clamp(Math.round(metadata.mediaTime*state.data.fps),0,state.data.length-1);
if(!state.seeking){
state.presented=index;drawOverlay(index);renderFrame(index);
}
state.videoCallback=video.requestVideoFrameCallback(callback);
};
state.videoCallback=video.requestVideoFrameCallback(callback);
}
function drawOverlay(index) {
const canvas=$('poseOverlay'),ctx=canvas.getContext('2d');ctx.clearRect(0,0,canvas.width,canvas.height);
if(!state.data||!$('overlayToggle').checked)return;
const points=state.data.projections[state.eye][index];if(!points)return;
const valid=p=>p&&finite(p[0])&&finite(p[1]);
const scale=canvas.width/960;
ctx.lineCap='round';ctx.lineJoin='round';ctx.lineWidth=3*scale;ctx.shadowColor='#000';ctx.shadowBlur=3*scale;
for(const [a,b,finger] of bones){if(!valid(points[a])||!valid(points[b]))continue;ctx.strokeStyle=fingerColors[finger];ctx.beginPath();ctx.moveTo(...points[a]);ctx.lineTo(...points[b]);ctx.stroke();}
for(let j=0;j<21;j++){if(!valid(points[j]))continue;ctx.fillStyle=j===0?'#fff':fingerColors[Math.floor((j-1)/4)];ctx.beginPath();ctx.arc(...points[j],3.7*scale,0,Math.PI*2);ctx.fill();ctx.strokeStyle='#111827';ctx.lineWidth=scale;ctx.stroke();}
ctx.shadowBlur=0;
}
function renderFrame(index,force=false) {
if(!state.data)return;
state.frame=index;const c=state.data.columns;
$('seek').value=index;
$('timeDisplay').textContent=`${timeLabel(index/state.data.fps)} / ${timeLabel(state.data.duration)} · ${index} / ${state.data.length-1}`;
const contact=c.contact[index];
$('contactState').textContent=contact===1?'Contact':contact===0?'No contact':contact===-1?'Unknown':'Unavailable';
$('contactState').className=`contact ${contact===1?'yes':contact===0?'no':'unknown'}`;
const supported=c.model_valid[index];
const values=pressureTraces.map(({name})=>supported?pressureSeries(name)[index]:null);
pressureTraces.forEach(({name},i)=>$(name+'HistoryValue').textContent=fmt(values[i]));
drawTimeline();drawPressureHistory();
const now=performance.now();
if(force||now-state.emgDrawAt>80){state.emgDrawAt=now;drawEmg();}
if($('details').open){
if(state.playing)$('detailFrame').textContent=`${index} · playing`;
else {state.detailAt=now;loadDetails();}
}
}
function pressureHistoryData() {
if(!state.data)return null;
const seconds=Number($('pressureWindow').value),fps=state.data.fps;
const end=state.frame/fps,start=end-seconds,c=state.data.columns;
// Missing estimates break the traces without changing the trial-wide axis.
const series=pressureTraces.map(trace=>{
const samples=pressureSeries(trace.name);
const runs=[];let run=[];
for(let i=Math.max(0,Math.ceil(start*fps-1e-6));i<=state.frame;i++){
const value=samples[i];
if(c.model_valid[i]&&finite(value)){
run.push({frame:i,time:i/fps,value});
}else if(run.length){runs.push(run);run=[];}
}
if(run.length)runs.push(run);
return {...trace,runs};
});
const {low,high}=state.pressureAxis;
return {start,end,seconds,low,high,series};
}
function drawPressureHistory() {
const history=pressureHistoryData();
if(!history)return;
for(const {name,color,runs} of history.series){
const {ctx,width,height}=setupCanvas($(name+'History'));
const left=31,right=width-6,top=6,bottom=height-6;
const x=t=>left+(t-history.start)/history.seconds*(right-left);
const y=v=>bottom-(v-history.low)/(history.high-history.low)*(bottom-top);
ctx.clearRect(0,0,width,height);
ctx.fillStyle=plotColors.surface;ctx.fillRect(left,top,right-left,bottom-top);
drawContactBackground(ctx,state.data.columns.contact,state.data.fps,history.start,history.end,left,right,top,bottom);
ctx.font='8px ui-monospace,monospace';ctx.textAlign='right';ctx.textBaseline='middle';
for(const value of [...new Set([history.low,0,history.high])]){
ctx.strokeStyle=value===0?plotColors.baseline:plotColors.grid;ctx.lineWidth=.65;
ctx.beginPath();ctx.moveTo(left,y(value));ctx.lineTo(right,y(value));ctx.stroke();
ctx.fillStyle=plotColors.label;ctx.fillText(fmt(value,Math.abs(value)<10&&value%1!==0?1:0),left-5,y(value));
}
ctx.save();ctx.beginPath();ctx.rect(left-2,top-3,right-left+5,bottom-top+6);ctx.clip();
for(const run of runs){
ctx.fillStyle=color+'1c';ctx.beginPath();ctx.moveTo(x(run[0].time),y(0));
for(const point of run)ctx.lineTo(x(point.time),y(point.value));
ctx.lineTo(x(run.at(-1).time),y(0));ctx.closePath();ctx.fill();
ctx.strokeStyle=color;ctx.lineWidth=1.7;ctx.lineJoin='round';ctx.beginPath();
run.forEach((point,i)=>i?ctx.lineTo(x(point.time),y(point.value)):ctx.moveTo(x(point.time),y(point.value)));ctx.stroke();
if(run.length===1){ctx.fillStyle=color;ctx.beginPath();ctx.arc(x(run[0].time),y(run[0].value),1.6,0,Math.PI*2);ctx.fill();}
}
const latest=runs.at(-1)?.at(-1);
if(latest?.frame===state.frame){ctx.fillStyle=color;ctx.beginPath();ctx.arc(right,y(latest.value),2.6,0,Math.PI*2);ctx.fill();}
ctx.restore();
}
drawContactHistory(history);
}
function drawContactHistory(history) {
const {ctx,width,height}=setupCanvas($('contactHistory'));
const left=31,right=width-6,top=6,bottom=height-6;
const x=t=>left+(t-history.start)/history.seconds*(right-left);
const y=value=>value===1?top:bottom;
const contact=state.data.columns.contact;
ctx.clearRect(0,0,width,height);
ctx.fillStyle=plotColors.surface;ctx.fillRect(left,top,right-left,bottom-top);
ctx.font='8px ui-monospace,monospace';ctx.textAlign='right';ctx.textBaseline='middle';
for(const value of [0,1]){
ctx.strokeStyle=plotColors.grid;ctx.lineWidth=.65;
ctx.beginPath();ctx.moveTo(left,y(value));ctx.lineTo(right,y(value));ctx.stroke();
ctx.fillStyle=plotColors.label;ctx.fillText(String(value),left-5,y(value));
}
ctx.strokeStyle=plotColors.emg;ctx.lineWidth=1.7;ctx.lineJoin='round';ctx.beginPath();
let previous=null;
for(const interval of contactIntervals(contact,state.data.fps,history.start,history.end)){
// Unknown labels break the path; only consecutive known states get a vertical step.
if(interval.value===-1){previous=null;continue;}
if(previous)ctx.lineTo(x(interval.start),y(interval.value));
else ctx.moveTo(x(interval.start),y(interval.value));
ctx.lineTo(x(interval.end),y(interval.value));
previous=interval;
}
const current=contact[state.frame];
if(current===0||current===1){
if(previous)ctx.lineTo(right,y(current));
ctx.stroke();
ctx.fillStyle=plotColors.emg;ctx.beginPath();ctx.arc(right,y(current),2.6,0,Math.PI*2);ctx.fill();
}else ctx.stroke();
}
function setPressureMode(mode) {
state.pressureMode=mode;
$('pressureRawButton').setAttribute('aria-pressed',String(mode==='raw'));
$('pressureSmoothedButton').setAttribute('aria-pressed',String(mode==='smoothed'));
state.timelineDirty=true;
if(state.ready)renderFrame(state.frame);
}
function buildTimeline() {
if(!state.data)return;
const {width,height,ratio}=setupCanvas($('timeline'));
const base=state.timelineBase;base.width=Math.round(width*ratio);base.height=Math.round(height*ratio);
const ctx=base.getContext('2d');ctx.setTransform(ratio,0,0,ratio,0,0);
ctx.fillStyle=plotColors.paper;ctx.fillRect(0,0,width,height);
const left=15,right=width-15,w=right-left,c=state.data.columns,n=state.data.length;
drawContactBackground(ctx,c.contact,state.data.fps,0,state.data.duration,left,right,7,83);
const {low,high}=state.pressureAxis;
const y=v=>83-(v-low)/(high-low)*76;
ctx.strokeStyle=plotColors.baseline;ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(left,y(0));ctx.lineTo(right,y(0));ctx.stroke();
pressureTraces.forEach(({name,color})=>{
const samples=pressureSeries(name);
ctx.strokeStyle=color;ctx.lineWidth=1.25;ctx.beginPath();let open=false;
for(let i=0;i<n;i++){const v=samples[i];if(!c.model_valid[i]||!finite(v)){open=false;continue;}const x=left+i/n*w;if(open)ctx.lineTo(x,y(v));else ctx.moveTo(x,y(v));open=true;}ctx.stroke();
});
ctx.fillStyle=plotColors.label;ctx.font='10px ui-monospace,monospace';ctx.textBaseline='top';
for(let k=0;k<=6;k++){ctx.textAlign=k===0?'left':k===6?'right':'center';ctx.fillText(timeLabel(state.data.duration*k/6,0),left+w*k/6,95);}
state.timelineDirty=false;
}
function drawTimeline() {
if(!state.data)return;
const {ctx,width,height}=setupCanvas($('timeline'));
if(state.timelineDirty||state.timelineBase.width!==$('timeline').width)buildTimeline();
ctx.drawImage(state.timelineBase,0,0,width,height);
const x=15+state.frame/state.data.length*(width-30);
ctx.strokeStyle=plotColors.ink;ctx.lineWidth=1.4;ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,height-20);ctx.stroke();
ctx.fillStyle=plotColors.ink;ctx.beginPath();ctx.moveTo(x-4,0);ctx.lineTo(x+4,0);ctx.lineTo(x,5);ctx.fill();
}
function decodeFullEmg(buffer,trial) {
const view=new DataView(buffer),decoder=new TextDecoder();
if(buffer.byteLength<16||decoder.decode(new Uint8Array(buffer,0,8))!=='EMGTRIAL'||view.getUint32(8,true)!==1)
throw new Error('Invalid full-trial EMG response');
const headerBytes=view.getUint32(12,true),offset=Math.ceil((16+headerBytes)/8)*8;
if(offset>buffer.byteLength)throw new Error('Incomplete EMG header');
const metadata=JSON.parse(decoder.decode(new Uint8Array(buffer,16,headerBytes)));
const {samples,channels,segments}=metadata;
if(metadata.episode_index!==trial.episode_index||samples!==trial.emg_samples||!Number.isSafeInteger(samples)||samples<1
||channels!==18||metadata.unit!=='microvolts'||metadata.source?.path!==trial.emg_path
||metadata.source?.signal!=='microvolts_filtered'||offset+samples*(8+4*channels)!==buffer.byteLength)
throw new Error('Full-trial EMG disagrees with trial metadata');
let previous=0;
if(!Array.isArray(segments))throw new Error('Missing EMG quality segments');
for(const segment of segments){
if(!Number.isInteger(segment.start)||!Number.isInteger(segment.stop)||segment.start<previous
||segment.stop<=segment.start||segment.stop>samples||typeof segment.approved!=='boolean')
throw new Error('Invalid EMG quality segment');
previous=segment.stop;
}
return {...metadata,time:new Float64Array(buffer,offset,samples),
values:new Float32Array(buffer,offset+samples*8,samples*channels)};
}
async function loadFullEmg(trial,signal) {
const response=await fetch(`/api/trial/${trial.episode_index}/emg/full`,{signal});
if(!response.ok){const error=await response.json();throw new Error(error.error||'Cannot load trial EMG');}
return decodeFullEmg(await response.arrayBuffer(),trial);
}
function sampleLowerBound(times,value) {
let lo=0,hi=times.length;
while(lo<hi){const mid=(lo+hi)>>>1;if(times[mid]<value)lo=mid+1;else hi=mid;}
return lo;
}
function visibleEmgSegments(emg,start,end) {
const lo=sampleLowerBound(emg.time,start),hi=sampleLowerBound(emg.time,end);
// Include one neighboring sample for continuous clipping at the plot edges.
return emg.segments.filter(segment=>emg.time[segment.stop-1]>=start&&emg.time[segment.start]<=end)
.map(segment=>({...segment,
start:Math.max(segment.start,lo-1),stop:Math.min(segment.stop,hi+1)}))
.filter(segment=>segment.stop>segment.start);
}
function emgGeometry() {
const canvas=$('emgCanvas'),{ctx,width,height}=setupCanvas(canvas);
const center=state.data?state.data.columns.host_seconds[state.frame]:0;
const windowSeconds=Number($('emgWindow').value),left=60,right=width-16,top=6,rowHeight=(height-12)/18;
return {ctx,width,height,center,start:center-windowSeconds/2,end:center+windowSeconds/2,left,right,top,rowHeight};
}
function drawEmg() {
const g=emgGeometry(),{ctx,width,height,left,right,top,rowHeight}=g;
ctx.clearRect(0,0,width,height);ctx.fillStyle=plotColors.surface;ctx.fillRect(left,top,right-left,height-2*top);
if(!state.data)return;
const emg=state.emg;
const segments=emg?visibleEmgSegments(emg,g.start,g.end):[];
ctx.font='10px ui-monospace,monospace';ctx.textBaseline='middle';
const x=t=>left+(t-g.start)/(g.end-g.start)*(right-left);
for(let ch=0;ch<18;ch++){
const y=top+rowHeight*(ch+.5);
ctx.strokeStyle=plotColors.grid;ctx.lineWidth=.65;ctx.beginPath();ctx.moveTo(left,y);ctx.lineTo(right,y);ctx.stroke();
ctx.fillStyle=plotColors.ink;ctx.textAlign='left';ctx.fillText(`CH ${String(ch+1).padStart(2,'0')}`,12,y);
if(!segments.length)continue;
let min=Infinity,max=-Infinity;
for(const segment of segments)for(let i=segment.start;i<segment.stop;i++){
const value=emg.values[i*emg.channels+ch];min=Math.min(min,value);max=Math.max(max,value);
}
const center=(min+max)/2,half=Math.max((max-min)/2,.5),scale=(rowHeight*.39)/half;
ctx.save();ctx.beginPath();ctx.rect(left,y-rowHeight*.45,right-left,rowHeight*.9);ctx.clip();
// Draw every visible sample from the full-trial buffer. Quality segments
// keep unsupported samples and acquisition gaps out of the line paths.
ctx.lineWidth=1;ctx.lineJoin='round';ctx.lineCap='round';
for(const segment of segments){
ctx.strokeStyle=segment.approved?plotColors.emg:plotColors.unapproved;ctx.beginPath();
for(let i=segment.start;i<segment.stop;i++){
const xx=x(emg.time[i]),yy=y-(emg.values[i*emg.channels+ch]-center)*scale;
if(i===segment.start)ctx.moveTo(xx,yy);else ctx.lineTo(xx,yy);
}
ctx.stroke();
}
ctx.restore();
}
ctx.strokeStyle=plotColors.ink;ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(x(g.center),top);ctx.lineTo(x(g.center),height-top);ctx.stroke();
}
async function loadDetails() {
if(!state.data||!$('details').open)return;
if(state.playing){$('frameDetails').textContent='Pause playback to inspect the complete current frame.';return;}
state.detailAbort?.abort();state.detailAbort=new AbortController();
const generation=state.generation,index=state.frame,token=++state.detailToken;
$('detailFrame').textContent=`${index} · loading`;
$('frameDetails').textContent=`Loading frame ${index}…`;
try{
const details=await api(`/api/trial/${state.id}/frame/${index}`,state.detailAbort.signal);
if(generation!==state.generation||token!==state.detailToken||index!==state.frame||state.playing)return;
$('detailFrame').textContent=String(index);$('frameDetails').textContent=JSON.stringify(details,null,2);
}catch(error){if(error.name!=='AbortError'&&generation===state.generation&&token===state.detailToken)$('frameDetails').textContent=error.message;}
}
function jumpFrames(delta){if(!state.ready)return;pause();seekFrame(state.frame+delta);}
$('trialSelect').addEventListener('change',event=>loadTrial(Number(event.target.value)));
$('playButton').addEventListener('click',togglePlay);
$('prevFrame').addEventListener('click',()=>jumpFrames(-1));$('nextFrame').addEventListener('click',()=>jumpFrames(1));
document.querySelectorAll('[data-jump]').forEach(button=>button.addEventListener('click',()=>jumpFrames(Number(button.dataset.jump)*(state.data?.fps||30))));
$('speed').addEventListener('change',()=>{video.playbackRate=Number($('speed').value);});
for(const eye of ['left','right'])$(eye+'EyeButton').addEventListener('click',()=>selectEye(eye));
function seekFromSlider(){if(!state.ready)return;const frame=Number($('seek').value);pause();seekFrame(frame);}
$('seek').addEventListener('input',seekFromSlider);
$('goSeek').addEventListener('click',seekFromSlider);
$('overlayToggle').addEventListener('change',()=>drawOverlay(state.presented));
$('pressureRawButton').addEventListener('click',()=>setPressureMode('raw'));
$('pressureSmoothedButton').addEventListener('click',()=>setPressureMode('smoothed'));
$('pressureWindow').addEventListener('change',drawPressureHistory);
$('emgWindow').addEventListener('change',drawEmg);
$('details').addEventListener('toggle',()=>{if($('details').open)loadDetails();else state.detailAbort?.abort();});
$('timeline').addEventListener('click',event=>{if(!state.data)return;const rect=$('timeline').getBoundingClientRect();pause();seekFrame(Math.floor(clamp((event.clientX-rect.left-15)/(rect.width-30),0,1)*state.data.length));});
document.addEventListener('keydown',event=>{
if(event.target.closest('input,select,textarea,button')||event.target.isContentEditable||event.ctrlKey||event.metaKey||event.altKey)return;
if(event.code==='Space'){event.preventDefault();togglePlay();}
else if(event.key==='ArrowLeft'||event.key==='ArrowRight'){event.preventDefault();jumpFrames((event.key==='ArrowLeft'?-1:1)*(event.shiftKey?(state.data?.fps||30):1));}
else if(event.key.toLowerCase()==='j')jumpFrames(-5*(state.data?.fps||30));
else if(event.key.toLowerCase()==='l')jumpFrames(5*(state.data?.fps||30));
else if(event.key==='Home'){event.preventDefault();pause();seekFrame(0);}
else if(event.key==='End'&&state.data){event.preventDefault();pause();seekFrame(state.data.length-1);}
});
video.addEventListener('ended',()=>{if(state.ready){pause();seekFrame(state.data.length-1);}});
document.addEventListener('visibilitychange',()=>{if(document.hidden)pause();});
new ResizeObserver(()=>{state.timelineDirty=true;drawTimeline();drawPressureHistory();drawEmg();}).observe(document.querySelector('main'));
function fallbackLoop(){
if(state.ready&&state.playing&&!state.seeking&&!video.requestVideoFrameCallback){
state.presented=clamp(Math.floor(video.currentTime*state.data.fps+1e-4),0,state.data.length-1);
drawOverlay(state.presented);renderFrame(state.presented);
}
requestAnimationFrame(fallbackLoop);
}
requestAnimationFrame(fallbackLoop);
(async()=>{
try{
const catalog=await api('/api/trials');state.catalog=catalog.trials;
$('trialSelect').replaceChildren();
for(const trial of state.catalog){const option=document.createElement('option');option.value=trial.episode_index;option.textContent=`Trial ${pad(trial.episode_index)} · ${trial.participant} · ${timeLabel(trial.duration,1)}`;$('trialSelect').append(option);}
$('trialSelect').disabled=false;
const requested=Number(new URLSearchParams(location.hash.slice(1)).get('trial'));
await loadTrial(state.catalog.some(t=>t.episode_index===requested)?requested:state.catalog[0].episode_index);
}catch(error){setStatus(`Cannot load dataset: ${error.message}`,true);}
})();